How to Add extra Data to Log Messages via a Processor ¶
Monolog allows you to process every record before logging it by adding some extra data. This is the role of a processor, which can be applied for the whole handler stack or only for a specific handler or channel.
A processor is a callable receiving the record as its first argument.
Processors are configured using the monolog.processor
DIC tag. See the
reference about it.
Adding a Session/Request Token ¶
Sometimes it is hard to tell which entries in the log belong to which session and/or request. The following example will add a unique token for each request using a processor:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 |
// src/Logger/SessionRequestProcessor.php
namespace App\Logger;
use Symfony\Component\HttpFoundation\Exception\SessionNotFoundException;
use Symfony\Component\HttpFoundation\RequestStack;
class SessionRequestProcessor
{
private $requestStack;
public function __construct(RequestStack $requestStack)
{
$this->requestStack = $requestStack;
}
// this method is called for each log record; optimize it to not hurt performance
public function __invoke(LogRecord $record): LogRecord
{
try {
$session = $this->requestStack->getSession();
} catch (SessionNotFoundException $e) {
return;
}
if (!$session->isStarted()) {
return $record;
}
$sessionId = substr($session->getId(), 0, 8) ?: '????????';
$record->extra['token'] = $sessionId.'-'.substr(uniqid('', true), -8);
return $record;
}
}
|
Next, register your class as a service, as well as a formatter that uses the extra information:
-
YAML
YAML
-
XML
XML
-
PHP
PHP
1 2 3 4 5 6 7 8 9 10 |
# config/services.yaml
services:
monolog.formatter.session_request:
class: Monolog\Formatter\LineFormatter
arguments:
- "[%%datetime%%] [%%extra.token%%] %%channel%%.%%level_name%%: %%message%% %%context%% %%extra%%\n"
App\Logger\SessionRequestProcessor:
tags:
- { name: monolog.processor }
|
Finally, set the formatter to be used on whatever handler you want:
-
YAML
YAML
-
XML
XML
-
PHP
PHP
1 2 3 4 5 6 7 8 |
# config/packages/prod/monolog.yaml
monolog:
handlers:
main:
type: stream
path: '%kernel.logs_dir%/%kernel.environment%.log'
level: debug
formatter: monolog.formatter.session_request
|
If you use several handlers, you can also register a processor at the handler level or at the channel level instead of registering it globally (see the following sections).
Symfony's MonologBridge provides processors that can be registered inside your application.
- DebugProcessor
-
Adds additional information useful for debugging like a timestamp or an
error message to the record.
タイムスタンプやエラー メッセージなどのデバッグに役立つ追加情報をレコードに追加します。
- TokenProcessor
-
Adds information from the current user's token to the record namely
username, roles and whether the user is authenticated.
現在のユーザーのトークンからの情報、つまりユーザー名、ロール、およびユーザーが認証されているかどうかをレコードに追加します。
- SwitchUserTokenProcessor
-
Adds information about the user who is impersonating the logged in user,
namely username, roles and whether the user is authenticated.
ログインしたユーザーを偽装しているユーザー、つまりユーザー名、役割、およびユーザーが認証されているかどうかに関する情報を追加します。
- WebProcessor
-
Overrides data from the request using the data inside Symfony's request
object.
Symfony の requestobject 内のデータを使用して、リクエストからのデータをオーバーライドします。
- RouteProcessor
-
Adds information about current route (controller, action, route parameters).
現在のルートに関する情報 (コントローラー、アクション、ルート パラメーター) を追加します。
- ConsoleCommandProcessor
-
Adds information about the current console command.
現在のコンソール コマンドに関する情報を追加します。
See also
Check out the built-in Monolog processors to learn more about how to create these processors.
Registering Processors per Handler ¶
You can register a processor per handler using the handler
option of
the monolog.processor
tag:
-
YAML
YAML
-
XML
XML
-
PHP
PHP
1 2 3 4 5 |
# config/services.yaml
services:
App\Logger\SessionRequestProcessor:
tags:
- { name: monolog.processor, handler: main }
|
Registering Processors per Channel ¶
You can register a processor per channel using the channel
option of
the monolog.processor
tag:
-
YAML
YAML
-
XML
XML
-
PHP
PHP
1 2 3 4 5 |
# config/services.yaml
services:
App\Logger\SessionRequestProcessor:
tags:
- { name: monolog.processor, channel: main }
|