【问题标题】:Laravel 5.4 - How to change the Laravel log file name?Laravel 5.4 - 如何更改 Laravel 日志文件名?
【发布时间】:2017-11-10 05:15:25
【问题描述】:

Laravel 版本:5.4.25 PHP版本:7.0

在以前的 laravel 版本中,有一个 ConfigureLogging 类来执行此操作。但是在最新版本的 laravel 中,该类已被删除,而是有一个新的 LogServiceProvider:

protected function configureDailyHandler(Application $app, Writer $log)
{

    $log->useDailyFiles(
        $app->storagePath() . '/logs/customLogName.log',
        $app->make('config')->get('app.log_max_files', 5)
    );
}

我想重写这个方法。

我该怎么做?

请帮忙。

谢谢。

【问题讨论】:

  • 尝试扩展 LogServiceProvider 并覆盖方法
  • 我已经试过了,但是没用

标签: laravel-5.4 php-7


【解决方案1】:

我终于明白了。

在返回 $app 实例后将其添加到您的 app/bootstrap/app.php 文件中:

$app->configureMonologUsing(function($monolog) use ($app) {
    $monolog->pushHandler(
        (new Monolog\Handler\RotatingFileHandler(
        // Set the log path
            $app->storagePath().'/logs/customLogName.log',
            // Set the number of daily files you want to keep
            $app->make('config')->get('app.log_max_files', 5)
        ))->setFormatter(new Monolog\Formatter\LineFormatter(null, null, true, true))
    );
});

return $app;

这样就可以了

【讨论】:

  • 非常好。谢谢你,先生!
【解决方案2】:

这可能已经改变了,但目前(2020 年使用 Laravel 7)配置它的方式较少,因为在 config/logging.php 中有日志通道,例如。通道 dailydaily 驱动程序:

每天 - 基于RotatingFileHandlerMonolog 驱动程序,每天轮换。

还可以更改其中的默认日志记录通道(如果需要):

'default' => env('LOG_CHANNEL', 'stack')

并且可以直接发布到频道,例如。使用 daily 驱动程序到一个自定义频道
(这个频道会产生大量垃圾邮件,我想将它们隔离在一个文件中):

Log::channel('webhook')->debug($message);

与此类似,它可以比仅更改输出文件名更好地组织日志记录。

【讨论】:

    【解决方案3】:

    对于 Laravel 5.5

    在路径vendor/laravel/framework/src/Illuminate/Log/LogServiceProvider.php

    更改函数configureDailyHandler

    线$this->app->storagePath().'/logs/laravel.log', $this->maxFiles(),

    到这里

    $this->app->storagePath().'/logs/laravel-'.get_current_user().'.log', $this->maxFiles(),
    

    或者只需将其添加到您的 bootstrap/app.php 中

    $app->configureMonologUsing(function (Monolog\Logger $monolog) {
        $filename = storage_path('logs/' . php_sapi_name() . '-' . posix_getpwuid(posix_geteuid())['name'] . '.log');
        $monolog->pushHandler($handler = new Monolog\Handler\RotatingFileHandler($filename, 30));
        $handler->setFilenameFormat('laravel-{date}-{filename}', 'Y-m-d');
        $formatter = new \Monolog\Formatter\LineFormatter(null, null, true, true);
        $formatter->includeStacktraces();
        $handler->setFormatter($formatter);
    });
    

    【讨论】:

    • 您不应该直接编辑供应商目录中的文件。
    • bootstrap/app.php中的修改是最好的选择。供应商文件夹采用 PSR 模式。如果您尝试更新您的作曲家包,您将有很大的机会遇到问题。
    猜你喜欢
    • 1970-01-01
    • 2018-04-22
    • 2017-10-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-12-07
    • 2018-11-13
    • 1970-01-01
    相关资源
    最近更新 更多