config/log.phpでログを設定するようになってからの設定方法についての小ネタ。
ドキュメントに明示されておらず、StackOverflow等でもなかなか出てこないので書いておく。
monolog driver以外でも、Formatterはconfig/log.phpで指定できる
Monolog Formatters
When using the monolog driver, the Monolog LineFormatter will be used as the default formatter. However, you may customize the type of formatter passed to the handler using the formatter and formatter_with configuration options:
'browser' => [
'driver' => 'monolog', // <= simpleドライバなどでもformatter指定できる
'handler' => Monolog\Handler\BrowserConsoleHandler::class,
'formatter' => Monolog\Formatter\HtmlFormatter::class,
'formatter_with' => [
'dateFormat' => 'Y-m-d',
],
],
- ドキュメントには
monolog
ドライバー用のオプションのように書かれているが、simple
やdaily
のdriverであっても同様に、formatterパラメータが有効- 同様にformatter_withも有効
tap()時、getHandlers()で全ハンドラを回さなくても直接$logger->pushProcessor()できる
ドキュメントの tap()
のサンプルが以下のように書かれているため、プロセッサの設定でも同様のループを書いていることが多い
// tapの処理サンプル
public function __invoke($logger)
{
foreach ($logger->getHandlers() as $handler) {
$handler->setFormatter(...);
}
}
public function __invoke($logger)
{
foreach ($logger->getHandlers() as $handler) {
// ならこうやろ!
$handler->pushProcessor(...);
}
}
※このサンプルに引っ張られて上記Formatterの設定を tap()
でやってしまう疑惑
-
__invoke($logger)
に渡される実体はMonolog\Logger
-
Loggerのスタック全体に対して適用するProcessorを
pushProcessor()
で突っ込める ⇒ソースpublic function __invoke($logger) { // 全部に適用したいならこれで十分 $logger->pushProcessor(...); }