配置

配置文件 config/logging.php

默认状况下,Laravel 应用 stack 通道来记录日志信息,stack 通道被用于聚合多个日志通道到单个通道。

例:single通道默认写入larave.log文件,daily通道默认写入larave-*.log文件,若配置stack如下

'stack' => [  'driver' => 'stack',  'channels' => ['single','daily'],]

则日志会同时写入larave.log和larave-*.log文件

日志级别

LOG_LEVEL=debug 日志信息被通道记录所必须达到的最低「级别」

emergencyalertcriticalerrorwarningnoticeinfodebug

假如LOG_LEVEL=error,则Log::debug('An informational message.');不会记录日志

写入日志信息

Log::emergency($error);Log::alert($error);Log::critical($error);Log::error($error);Log::warning($error);Log::notice($error);Log::info($error);Log::debug($error);

写入上下文信息

Log::info('User failed to login.', ['id' => 123]);//local.INFO: User failed to login. {"id":123} 

写入指定通道

'test' => [  'driver' => 'single',  'path' => storage_path('logs/laravel.log'),],Log::channel('test')->info('Something happened!');

通道自定义

'single' => [    'driver' => 'single',    'tap' => [App\Logging\CustomizeFormatter::class],    'path' => storage_path('logs/laravel.log'),    'level' => 'debug',],
注:所有「tap」类都通过服务容器解析,所以他们须要的所有构造函数依赖都会被主动注入。
<?phpnamespace App\Logging;use Monolog\Formatter\LineFormatter;class CustomizeFormatter{    /**     * Customize the given logger instance.     *     * @param  \Illuminate\Log\Logger  $logger     * @return void     */    public function __invoke($logger)    {        foreach ($logger->getHandlers() as $handler) {            $handler->setFormatter(new LineFormatter(                '[%datetime%] %channel%.%level_name%: %message% %context% %extra%'            ));        }    }}