带有 laravel5.6 的自定义(动态)日志文件名

Custom (dynamic) log file names with laravel5.6

使用 laravel 5.5 我们可以访问 $app 中的 configureMonologUsing() 方法,这使得在 bootstrap/app.php:

中这样的事情成为可能
$app->configureMonologUsing(function (Monolog\Logger $monolog) {
    $processUser = posix_getpwuid(posix_geteuid());
    $processName= $processUser['name'];

    $filename = storage_path('logs/laravel-' . php_sapi_name() . '-' . $processName . '.log');
    $handler = new Monolog\Handler\RotatingFileHandler($filename);
    $monolog->pushHandler($handler);
});

当您的应用程序可能从不同的上下文(例如 CLI/HTTP)被不同的用户(这是可取的)和文件轮换调用时,这样做很有用。这样做可以防止写入错误,以防 HTTP 用户在 CLI 尝试向其中添加内容之前创建日志文件,反之亦然。

处理这个问题很棘手或不安全,因为它涉及能够对可能尚不存在的文件设置写权限。

此外,将日志按上下文分隔非常方便,因为它们通常没有什么共同点,这样更容易在它们之间进行搜索。

不幸的是,laravel 5.6 不再可能采用这种方式,而且我(还)无法找到一种方法来透明地对所有基于文件的日志记录执行此操作。

谢谢

现在通过为 Monolog 调用自定义格式化程序来完成自定义。

这是一个使用每日轮换文件名的示例(就像我一样)。

这可以在 config/logging.php 中设置,注意非默认 tap 参数:

'channels' => [

    'daily' => [
        'driver' => 'daily',
        'tap' => [App\Logging\CustomFilenames::class],
        'path' => storage_path('logs/laravel.log'),
        'level' => 'debug',
    ],

]

在您的自定义格式化程序中,您可以随意操作 Monolog 记录器,类似于 configureMonologUsing():

app\Logging\CustomFilenames.php

<?php

namespace App\Logging;

use Monolog\Handler\RotatingFileHandler;

class CustomFilenames
{
    /**
     * Customize the given logger instance.
     *
     * @param  \Illuminate\Log\Logger  $logger
     * @return void
     */
    public function __invoke($logger)
    {
        foreach ($logger->getHandlers() as $handler) {
            if ($handler instanceof RotatingFileHandler) {
                $sapi = php_sapi_name();
                $handler->setFilenameFormat("{filename}-$sapi-{date}", 'Y-m-d');
            }
        }
    }
}

恢复原始行为的一种方法是从处理程序的 filenameFormat 中删除 {date} 组件。更好的方法可能是为 single 驱动程序操纵适当的处理程序。

参见:https://laravel.com/docs/5.6/logging#advanced-monolog-channel-customization

解决方案:

第 1 步:在 config/logging.php 文件中创建一个频道

示例:

'channels' => [
    'single' => [
    'driver' => 'single', 
    'path' => storage_path('logs/laravel.log'),
    'level' => 'debug',
],

'web' => [
      'driver' => 'single',
      'path' => storage_path('logs/web/web.log'),
   ],

]

Step2: Now set dyanamic path from controller like this

config(['logging.channels.web.path' => storage_path('logs/web/'.time().'.log')]);

Step3 : now generate your log

  Log::channel('web')->info("your message goes here");

尽情享受吧:)