I'm using a custom monolog processor as described here and I'd like to add the handler name into my logs. The code snippet on above links shows the argument being passed as session. How can I pass in the handler argument?
app.logger.session_request_processor:
class: AppBundle\Logger\SessionRequestProcessor
arguments: ['@session']
tags:
- { name: monolog.processor, method: processRecord }
This is not as easy as it seems. Processor are either registered per logger or per handler.
If the processor is registered in the logger, there is no way of knowing which handler the processor went through, as all handlers are executed after all processors were executed. If you register the processor on a handler, you always know which handler is executed, but registering a processor for every handler manually is quite cumbersome.
In order to solve this, you could add a CompilerPass which does the manual work for you.
Lets assume we have this processor
With this processor you can then create a compiler pass, which creates all the definitions for the different handlers monolog created
As compiler passes can be quite confusing if you never used them before, lets go line by line:
This checks if the monolog bundle is registered. The parameter
monolog.handlers_to_channelsis added to the container in the MonologExtension. The parameter itself contains an array where the key is the name of the handler id and the value is an array with all channels this handler is registered to (or null if this handler is valid for all channels)Here we create a new definition of our
HandlerProcessorand get the definition of the current processed handler.This will fetch the class name of the handler (e.g. Monolog\Handler\SlackHandler) and adds it as a constructor argument to the
HandlerProcessorAnd last but not least we create a new ID for the processor definition we just created at the beginning of the foreach loop and add it with the method call
pushProcessorto our newly created processor.Now that everything is set up, you have to register this compiler pass in your container. I assume you are using symfony 2.x so you have to do that in your
AppBundleHere are some additional links which might be helpful: