Jeroen De Dauw
Jeroen De Dauw

Reputation: 10908

Group Symfony/Monolog log messages

This is what my log file looks like after 2 requests:

[2019-03-16 01:20:57] request.INFO: some stuff happened
[2019-03-16 01:20:57] request.INFO: some stuff happened
[2019-03-16 01:21:17] request.INFO: some stuff happened
[2019-03-16 01:21:17] request.INFO: some stuff happened

Is there a way to group log messages per request so you can visually see which ones belong together? This does not need to be fancy. Even a newline would do:

[2019-03-16 01:20:57] request.INFO: some stuff happened
[2019-03-16 01:20:57] request.INFO: some stuff happened

[2019-03-16 01:21:17] request.INFO: some stuff happened
[2019-03-16 01:21:17] request.INFO: some stuff happened

I'd like to have this for a log handler of type fingers_crossed that only triggers on errors and then logs all debug info for that request.

Some searching yielded remarkably little information. Unfortunately Monolog has an unrelated "group" concept, which is cluttering up the search results.

Upvotes: 1

Views: 639

Answers (1)

chiborg
chiborg

Reputation: 28094

If I understand correctly, you want to have a visual marker in your log file that marks the end of log messages of a request, right? The most simple solution I can imagine would be to log additional messages at the end of the request cycle, e.g.

$logger->debug('----------------------------------------------------------');
$logger->debug('END OF REQUEST');
$logger->debug('----------------------------------------------------------');

When using Symfony, I'd add an event handler for kernel.finish_request or kernel.terminate that calls the logger.

If you want to keep the additional log calls out of your bootstrap/event handling code, you could write your own Monolog handler class that can wrap other handlers (see the BufferHandler for an example of a wrapping handler):

  • handle would pass on the messages to the wrapped handler.
  • handleBatch could attach your marker to the end of batch before passing them on
  • close could also send a last log message to the wrapped hadler before calling its close function. But close needs to be idempotent, so that might pose a problem for this case.

If your requests are long-running and their messages intermingle in the log file, add a BufferHandler to keep them apart.

If you want to remove the additional log information (timestamp, source, severity) in front of your marker, I'd recommend to write your own formatter (wrapping/subclassing LineFormatter) that gives different output depending on the log message being an "end of request" message or not. In this case I'd recommend not to send several messages as markers, but send one and define a marker format in the formatter.

Upvotes: 1

Related Questions