Laravel. Log::build doesn’t take into account the value from the ‘tap’ parameter in the passed configuration

  Kiến thức lập trình

Laravel Version

10.48.14 but the problem persists for the newest version as well

PHP Version

8.1.2

Description

When creating a logger using the build method, like this:

$logger = Log::build([
    'driver' => 'daily',
    'tap' => [ AppLoggingCustomizeFormatter::class ],
    'path' => storage_path('logs/test.log'),
    'level' => env('LOG_LEVEL', 'debug'),
    'replace_placeholders' => true,
    'days' => 14,
]);

classes that are specified in the ‘tap’ parameter are not called.

The reason is that in this case, the channel name for the log becomes ondemand and the method LogManager::configurationFor tries to find this channel in the site configuration (through $this->app['config']["logging.channels.ondemand"]) and does not find it there. Although it would be logical to use the configuration passed to the method Log Manager::build.

Steps To Reproduce

Create a class:

<?php

namespace AppLogging;

use MonologFormatterLineFormatter;
use IlluminateLogLogger;

class CustomizeFormatter
{
    /**
     * @param  IlluminateLogLogger  $logger
     * @return void
     */
    public function __invoke(Logger $logger): void
    {
        foreach ($logger->getHandlers() as $handler) {
            $handler->setFormatter(new LineFormatter(
                'TEST: [%datetime%] %channel%.%level_name%: %message% %context% %extra%' . PHP_EOL
            ));
        }
    }
}

Create a logger in any location that will be called, for example in php artisan tinker

$logger = Log::build([
    'driver' => 'single',
    'tap' => [ AppLoggingCustomizeFormatter::class ],
    'path' => storage_path('logs/test.log'),
    'level' => env('LOG_LEVEL', 'debug'),
    'replace_placeholders' => true,
    'days' => 14,
]);

After that, call $logger->info('Something here');
In the test.log file, the string should start with ‘TEST:’, but this will not happen.

Workaround

You need to add to the file /config/logging.php the following code for includes in the channel definition:

...
'channels' => [
    ...
    'ondemand' => [
            'tap' => [ AppLoggingCustomizeFormatter::class ],
        ],
    ...
]

Note

I am writing here because on my issue ( https://github.com/laravel/framework/issues/52354 ) on github, I was recommended to write here and then, if this is a real problem, then write a new issue. And this is a real problem – Laravel does not function as described in the documentation.

The above describes how to reproduce it in “Steps To Reproduce” section.

I expect the framework to work as described here. https://laravel.com/docs/11.x/logging#customizing-monolog-for-channels

New contributor

Константин Тарасов is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.

Theme wordpress giá rẻ Theme wordpress giá rẻ Thiết kế website

LEAVE A COMMENT