自定义Laravel (monolog)日志位置,并增加请求ID的实现

修改 bootstrap/app.php 文件

$app->configureMonologUsing(function($monolog) use ($app) {
 $monolog->pushHandler(
  (new Monolog\Handler\RotatingFileHandler(
   '/var/logs/app/laravel',
   $app->make('config')->get('app.log_max_files', 5)
  ))->setFormatter(new Monolog\Formatter\LineFormatter(null, null, true, true))
 );
});

添加以后写入日志文件为:

-rw-r--r-- 1 web web 93 Dec 18 15:52 laravel-2017-12-17
-rw-r--r-- 1 web web 279 Dec 18 16:10 laravel-2017-12-18

参考:Laravel 的错误和日志记录

或者

创建app\Providers\LogServiceProvider.php 文件

修改 config\app.php providers 增加

App\Providers\LogServiceProvider::class

然后 App\Providers\LogServiceProvider.php 内容如下

<?php

namespace App\Providers;

use Illuminate\Log\LogServiceProvider as SysServiceProvider;
use Illuminate\Log\Writer;

class LogServiceProvider extends SysServiceProvider
{
 protected function configureSingleHandler(Writer $log)
 {
  $log->useFiles(
   '/var/logs/app/laravel.log',
   $this->logLevel()
  );
 }

 protected function configureDailyHandler(Writer $log)
 {
  $log->useDailyFiles(
   '/var/logs/app/laravel.log', $this->maxFiles(),
   $this->logLevel()
  );
 }
}

增加请求ID request id

namespace App\Providers;

use Illuminate\Support\ServiceProvider;
use Carbon\Carbon;

class LogServiceProvider extends ServiceProvider
{
 protected $log_file;

 /**
  * Bootstrap any application services.
  * @return void
  */
 public function boot()
 {
  //
 }

 /**
  * Register any application services.
  * @return void
  */
 public function register()
 {
  $this->load_request_id();

  $this->log_configure();
 }

 /**
  * 生成 request_id
  * @return void
  */
 protected function load_request_id()
 {
  define( 'REQUEST_ID' , config('app.log_prefix').Carbon::now()->timestamp );
 }
 
 /**
  * 注册 monolog pushHandler
  * @return void
  */
 protected function log_configure()
 {
  $log_file = $this->getLogFile();
  $log_max_files = $this->getLogMaxFiles();

  /**
   * @doc https://d.laravel-china.org/docs/5.4/errors#自定义-Monolog-设置
   */
  $this->app->configureMonologUsing(function($monolog) use ($log_file , $log_max_files) {
   $monolog->pushHandler(
    (new \Monolog\Handler\RotatingFileHandler(
     $log_file ,
     $log_max_files
    ))->setFormatter(new \Monolog\Formatter\LineFormatter( "[%datetime%] [".REQUEST_ID."] %channel%.%level_name%: %message% %context% %extra%\n", null, true, true))
   );
  });
 }

 protected function getLogMaxFiles()
 {
  return config('app.log_max_files' , 5);
 }

 /**
  * @return mixed
  */
 protected function getLogFile()
 {
  if( is_null( $this->log_file) )
  {
   $this->log_file = rtrim(config('app.log_path') , DIRECTORY_SEPARATOR )."/laravel.log";
  }
  return $this->log_file;
 }
}

      

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:http://www.heiqu.com/4036.html