amphp / http-server

An advanced async HTTP server library for PHP, perfect for real-time apps and APIs with high concurrency demands.

Home Page:https://amphp.org/http-server

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Sending additional data to logger

enumag opened this issue · comments

When sending errors to an error tracking software such as Sentry, it is nice to be able to attach some additional data when \Psr\Log\LoggerInterface is called.

In particular:

  • Some information about the request itself.
  • Information about the authenticated user.

Since these data are specific to each request it needs to be somehow handled by the HttpServer and the data need to be added to the $context array when logger is called. I'd like to ask for recommendations how to implement this.

First thing I'm wondering about is the ExceptionMiddleware - it is clearly something that takes care of logging the exceptions and sending appropriate html to the client. However it isn't used by default, nor mentioned anywhere in the documentation. So what is different in this middleware from the default behavior? Where in the stack should I use it?

Second thing is integrating user authentication. I assume I should do it as a middleware and add the user data to the request using Request::setAttribute() so that they can be available in both the final RequestHandler and in other middlewares (for logging or something). Does that sound correct?

Third question is about modifying the context when logger is called. Even the ExceptionMiddleware only passes the exception but nothing else. Should I implement my own version of it or should we try to improve the existing one with a callback Closure(Request, Exception): array or something?

ExceptionMiddleware allows dumping stacktraces into the response in debug mode, which we don't do by default. You'll have to find the appropriate position in the stack yourself, like with any other middleware.

I guess we could introduce something like log_context_request_attributes to automatically include these attributes if a Request is available. We could also put Request itself into the context and let the logging library pull the attributes out from it.

We could also put Request itself into the context and let the logging library pull the attributes out from it.

This sounds great to me. I'll try to send a PR.