2016-12-30 122 views
1

我需要重寫格式的日誌上Laravel 5.3覆蓋格式的日誌

我爲導向,這post使用,但不工作做項目。

首先創建一個引導/ ConfigureLogging.php類

<?php 
namespace Bootstrap; 

use Monolog\Handler\RotatingFileHandler; 
use Monolog\Logger as Monolog; 
use Monolog\Formatter\LineFormatter; 
use Illuminate\Log\Writer; 
use Illuminate\Contracts\Foundation\Application; 
use Illuminate\Foundation\Bootstrap\ConfigureLogging as BaseConfigureLogging; 
use Monolog\Handler\StreamHandler; 
use Carbon\Carbon; 

class ConfigureLogging extends BaseConfigureLogging 
{ 
    /** 
    * Configure the Monolog handlers for the application. 
    * @param \Illuminate\Contracts\Foundation\Application $app 
    * @param \Illuminate\Log\Writer $log 
    * @return void 
    */ 
    protected function configureDailyHandler(Application $app, Writer $log) 
    { 
     $config = $app->make('config'); 
     $maxFiles = $config->get('app.log_max_files'); 

     // Formatting 
     // the default output format is "[%datetime%] %channel%.%level_name%: %message% %context% %extra%\n" 
     $logFormat = "[%datetime%] [%level_name%]: %message% %context% %extra%\n"; 
     $formatter = new LineFormatter($logFormat); 
     //$logStreamHandler->setFormatter($formatter); // Here I'm lost 


     $log->useDailyFiles(
      $app->storagePath().'/logs/cprsync.log', is_null($maxFiles) ? 5 : $maxFiles, $config->get('app.log_level', 'debug') 
     ); 
} 

這種變化(覆蓋)爲我的應用程序laravel日誌的名稱。 但是,當我嘗試添加代碼覆蓋格式,我迷路了,並且原始帖子上的代碼不起作用。

我看到了Monolog的代碼,我發現我需要發送我的格式,但我不知道。

回答

1

你所指的鏈接應該是我的知識。您缺少pushHandler

protected function configureDailyHandler(Application $app, Writer $log) { 
    $config = $app->make('config'); 
    $maxFiles = $config->get('app.log_max_files'); 
    $path  = $app->storagePath().'/logs/cprsync.log'; 

    // Daily handler 
    $handler = new RotatingFileHandler($path, is_null($maxFiles) ? 5 : $maxFiles, 
     $config->get('app.log_level', 'debug')); 

    // Formatting 
    $logFormat = "%datetime% [%level_name%] (%channel%): %message% %context% %extra%\n"; 
    $formatter = new LineFormatter($logFormat); 
    $handler->setFormatter($formatter); 

    // Push handler 
    $log->getMonolog()->pushHandler($handler); 
} 
+0

非常感謝。用你的例子很好地理解推送處理程序的機制。並且工作正常。 – abkrim

+1

那麼,我使用'$ formatter = new LineFormatter($ logFormat,null,true,true);'在日誌沒有特殊信息時刪除行尾的額外括號。 – abkrim