PHP 的日誌庫。 JSON格式輸出
該庫主要用於 Web 應用程式。
composer require nekonomokochan/php-json-logger
<?php
use Nekonomokochan PhpJsonLogger LoggerBuilder ;
$ context = [
' title ' => ' Test ' ,
' price ' => 4000 ,
' list ' => [ 1 , 2 , 3 ],
' user ' => [
' id ' => 100 ,
' name ' => ' keitakn ' ,
],
];
$ loggerBuilder = new LoggerBuilder ();
$ logger = $ loggerBuilder -> build ();
$ logger -> info ( ' ? ' , $ context );
其輸出如下。
{
"log_level" : " INFO " ,
"message" : " ? " ,
"channel" : " PhpJsonLogger " ,
"trace_id" : " 35b627ce-55e0-4729-9da0-fbda2a7d817d " ,
"file" : " / home / vagrant / php-json-logger / tests / LoggerTest.php " ,
"line" : 42 ,
"context" : {
"title" : " Test " ,
"price" : 4000 ,
"list" : [
1 ,
2 ,
3
],
"user" : {
"id" : 100 ,
"name" : " keitakn "
}
},
"remote_ip_address" : " 127.0.0.1 " ,
"server_ip_address" : " 127.0.0.1 " ,
"user_agent" : " unknown " ,
"datetime" : " 2018-06-04 17:21:03.631409 " ,
"timezone" : " Asia / Tokyo " ,
"process_time" : 631.50811195373535
}
process_time
的單位是ms(毫秒)。
預設輸出檔案路徑是/tmp/php-json-logger-yyyy-mm-dd.log
。
如果要變更輸出檔案路徑,請將輸出檔案路徑設定為建構器類別。
<?php
use Nekonomokochan PhpJsonLogger LoggerBuilder ;
$ fileName = ' /tmp/test-php-json-logger.log ' ;
$ context = [
' cat ' => ' ? ' ,
' dog ' => ' ? ' ,
' rabbit ' => ' ? ' ,
];
$ loggerBuilder = new LoggerBuilder ();
$ loggerBuilder -> setFileName ( $ fileName );
$ logger = $ loggerBuilder -> build ();
$ logger -> info ( ' testSetLogFileName ' , $ context );
輸出檔案路徑為/tmp/test-php-json-logger-yyyy-mm-dd.log
。
其輸出如下。
{
"log_level" : " INFO " ,
"message" : " testSetLogFileName " ,
"channel" : " PhpJsonLogger " ,
"trace_id" : " 20f39cdb-dbd8-470c-babd-093a2974d169 " ,
"file" : " / home / vagrant / php-json-logger / tests / LoggerTest.php " ,
"line" : 263 ,
"context" : {
"cat" : " ? " ,
"dog" : " ? " ,
"rabbit" : " ? "
},
"remote_ip_address" : " 127.0.0.1 " ,
"server_ip_address" : " 127.0.0.1 " ,
"user_agent" : " unknown " ,
"datetime" : " 2018-06-05 11:28:03.214995 " ,
"timezone" : " Asia / Tokyo " ,
"process_time" : 215.09790420532227
}
trace_id
可以為trace_id
設定任何值。
這將有助於您找到所需的日誌。
<?php
use Nekonomokochan PhpJsonLogger LoggerBuilder ;
$ context = [
' name ' => ' keitakn ' ,
];
$ loggerBuilder = new LoggerBuilder ();
$ loggerBuilder -> setTraceId ( ' MyTraceID ' );
$ logger = $ loggerBuilder -> build ();
$ logger -> info ( ' testSetTraceIdIsOutput ' , $ context );
其輸出如下。
{
"log_level" : " INFO " ,
"message" : " testSetTraceIdIsOutput " ,
"channel" : " PhpJsonLogger " ,
"trace_id" : " MyTraceID " ,
"file" : " / home / vagrant / php-json-logger / tests / LoggerTest.php " ,
"line" : 214 ,
"context" : {
"name" : " keitakn "
},
"remote_ip_address" : " 127.0.0.1 " ,
"server_ip_address" : " 127.0.0.1 " ,
"user_agent" : " unknown " ,
"datetime" : " 2018-06-05 11:36:02.394269 " ,
"timezone" : " Asia / Tokyo " ,
"process_time" : 394.35911178588867
}
請使用NekonomokochanPhpJsonLoggerLoggerBuilder::setLogLevel()
。
例如,以下程式碼不會輸出日誌。
因為等級設定為CRITICAL
。
<?php
use Nekonomokochan PhpJsonLogger LoggerBuilder ;
$ context = [
' cat ' => ' ? ' ,
' dog ' => ' ? ' ,
' rabbit ' => ' ? ' ,
];
$ loggerBuilder = new LoggerBuilder ();
$ loggerBuilder -> setLogLevel (LoggerBuilder:: CRITICAL );
$ logger = $ loggerBuilder -> build ();
$ logger -> info ( ' testSetLogLevel ' , $ context );
您可以為logLevel
設定以下值。
這些與 Monolog 中定義的logLevel
相同。
預設通道是PhpJsonLogger
。
如果你想改變頻道,可以用下面的程式碼來改變。
$ loggerBuilder = new LoggerBuilder ();
$ loggerBuilder -> setChannel ( ' My Favorite Animals ' );
例如,輸出如下。
{
"log_level" : " INFO " ,
"message" : " testCanSetChannel " ,
"channel" : " My Favorite Animals " ,
"trace_id" : " 4b8aa070-a533-4376-9bf5-270c8fcc6d87 " ,
"file" : " / home / vagrant / php-json-logger / tests / Logger / LoggerTest.php " ,
"line" : 347 ,
"context" : {
"animals" : " ????? "
},
"remote_ip_address" : " 127.0.0.1 " ,
"server_ip_address" : " 127.0.0.1 " ,
"user_agent" : " unknown " ,
"datetime" : " 2018-06-07 17:56:48.538117 " ,
"timezone" : " Asia / Tokyo " ,
"process_time" : 538.48695755004883
}
這是保存日誌 7 天的預設值。
如果要變更日誌旋轉日期,可以使用下列程式碼進行變更。
以下代碼將日誌保留期限設定為 2 天。
$ loggerBuilder = new LoggerBuilder ();
$ loggerBuilder -> setMaxFiles ( 2 );
NekonomokochanPhpJsonLoggerJsonFormatter
您可以只使用NekonomokochanPhpJsonLoggerJsonFormatter
製作自己的MonologLogger
。
當您在 Web 應用程式框架(例如 Laravel)中需要MonologLogger
時,此方法非常有用。
以下是範例程式碼。
<?php
use Monolog Logger ;
use Monolog Handler RotatingFileHandler ;
use Monolog Processor IntrospectionProcessor ;
use Nekonomokochan PhpJsonLogger JsonFormatter ;
$ logFileName = ' /tmp/extended-monolog-test.log ' ;
// create extendedMonolog Instance
$ formatter = new JsonFormatter ();
$ rotating = new RotatingFileHandler (
$ logFileName ,
7 ,
Logger:: INFO
);
$ rotating -> setFormatter ( $ formatter );
$ introspection = new IntrospectionProcessor (
Logger:: INFO ,
[ ' Nekonomokochan \ PhpJsonLogger \' ],
0
);
$ extraRecords = function ( $ record ) {
$ record [ ' extra ' ][ ' trace_id ' ] = ' ExtendedMonologTestTraceId ' ;
$ record [ ' extra ' ][ ' created_time ' ] = microtime ( true );
return $ record ;
};
$ extendedMonolog = new Logger (
' ExtendedMonolog ' ,
[ $ rotating ],
[ $ introspection , $ extraRecords ]
);
// output info log
$ context = [
' cat ' => ' ? ' ,
' dog ' => ' ? ' ,
' rabbit ' => ' ? ' ,
];
$ extendedMonolog -> info ( ' outputInfoLogTest ' , $ context );
輸出到extended-monolog-test-yyyy-mm-dd.log
如下
{
"log_level" : " INFO " ,
"message" : " outputInfoLogTest " ,
"channel" : " ExtendedMonolog " ,
"trace_id" : " ExtendedMonologTestTraceId " ,
"file" : " / home / vagrant / php-json-logger / tests / ExtendedMonologTest.php " ,
"line" : 85 ,
"context" : {
"cat" : " ? " ,
"dog" : " ? " ,
"rabbit" : " ? "
},
"remote_ip_address" : " 127.0.0.1 " ,
"server_ip_address" : " 127.0.0.1 " ,
"user_agent" : " unknown " ,
"datetime" : " 2018-06-06 17:14:26.042013 " ,
"timezone" : " Asia / Tokyo " ,
"process_time" : 0.1678466796875
}
以下程式碼對於輸出trace_id
和process_time
是必要的。
<?php
$ extraRecords = function ( $ record ) {
$ record [ ' extra ' ][ ' trace_id ' ] = ' ExtendedMonologTestTraceId ' ;
$ record [ ' extra ' ][ ' created_time ' ] = microtime ( true );
return $ record ;
};
下面的程式碼是正常使用 JSON 顯示堆疊追蹤所需的程式碼。
<?php
$ introspection = new IntrospectionProcessor (
Logger:: INFO ,
[ ' Nekonomokochan \ PhpJsonLogger \' ],
0
);
若要將堆疊追蹤輸出到日誌,請執行下列程式碼。
<?php
$ exception = new Exception ( ' ExtendedMonologTest.outputErrorLog ' , 500 );
$ context = [
' cat ' => ' ?(=^・^=)? ' ,
' dog ' => ' ?Uo・ェ・oU? ' ,
' rabbit ' => ' ??? ' ,
];
$ extendedMonolog -> error (
get_class ( $ exception ),
$ this -> formatPhpJsonLoggerErrorsContext ( $ exception , $ context )
);
請注意$this->formatPhpJsonLoggerErrorsContext($exception, $context)
部分。
這是將錯誤日誌格式化為 JSON 並輸出的必要處理。
這是NekonomokochanPhpJsonLoggerErrorsContextFormat
中實作的方法。
它輸出到extended-monolog-test-yyyy-mm-dd.log
如下所示。
如果你想了解更詳細的用法,請查看php-json-logger/tests/ExtendedMonologTest.php
。
{
"log_level" : " ERROR " ,
"message" : " Exception " ,
"channel" : " PhpJsonLogger " ,
"trace_id" : " ExtendedMonologTestTraceId " ,
"file" : " / home / vagrant / php-json-logger / tests / ExtendedMonologTest.php " ,
"line" : 126 ,
"context" : {
"cat" : " ?(=^・^=)? " ,
"dog" : " ?Uo・ェ・oU? " ,
"rabbit" : " ??? "
},
"remote_ip_address" : " 127.0.0.1 " ,
"server_ip_address" : " 127.0.0.1 " ,
"user_agent" : " unknown " ,
"datetime" : " 2018-06-06 17:37:57.440757 " ,
"timezone" : " Asia / Tokyo " ,
"process_time" : 0.16093254089355469 ,
"errors" : {
"message" : " ExtendedMonologTest.outputErrorLog " ,
"code" : 500 ,
"file" : " / home / vagrant / php-json-logger / tests / ExtendedMonologTest.php " ,
"line" : 117 ,
"trace" : [
" #0 / home / vagrant / php-json-logger / vendor / phpunit / phpunit / src / Framework / TestCase.php(1145): Nekonomokochan \ Tests \ ExtendedMonologTest->outputErrorLog() " ,
" #1 / home / vagrant / php-json-logger / vendor / phpunit / phpunit / src / Framework / TestCase.php(840): PHPUnit \ Framework \ TestCase->runTest() " ,
" #2 / home / vagrant / php-json-logger / vendor / phpunit / phpunit / src / Framework / TestResult.php(645): PHPUnit \ Framework \ TestCase->runBare() " ,
" #3 / home / vagrant / php-json-logger / vendor / phpunit / phpunit / src / Framework / TestCase.php(798): PHPUnit \ Framework \ TestResult->run() " ,
" #4 / home / vagrant / php-json-logger / vendor / phpunit / phpunit / src / Framework / TestSuite.php(776): PHPUnit \ Framework \ TestCase->run() " ,
" #5 / home / vagrant / php-json-logger / vendor / phpunit / phpunit / src / TextUI / TestRunner.php(529): PHPUnit \ Framework \ TestSuite->run() " ,
" #6 / home / vagrant / php-json-logger / vendor / phpunit / phpunit / src / TextUI / Command.php(198): PHPUnit \ TextUI \ TestRunner->doRun() " ,
" #7 / home / vagrant / php-json-logger / vendor / phpunit / phpunit / src / TextUI / Command.php(151): PHPUnit \ TextUI \ Command->run() " ,
" #8 / home / vagrant / php-json-logger / vendor / phpunit / phpunit / phpunit(53): PHPUnit \ TextUI \ Command::main() "
]
}
}
若要將日誌傳送到 Slack,請執行下列程式碼。
如果日誌等級為CRITICAL
或更高,則此程式碼將被傳送到 slack。
<?php
use Nekonomokochan PhpJsonLogger LoggerBuilder ;
use Nekonomokochan PhpJsonLogger SlackHandlerBuilder ;
$ exception = new Exception ( ' TestException ' , 500 );
$ context = [
' name ' => ' keitakn ' ,
' email ' => ' [email protected] ' ,
];
$ slackToken = ' YOUR_SLACK_TOKEN ' ;
$ slackChannel = ' YOUR_SLACK_CHANNEL ' ;
$ slackHandlerBuilder = new SlackHandlerBuilder ( $ slackToken , $ slackChannel );
$ slackHandlerBuilder -> setLevel (LoggerBuilder:: CRITICAL );
$ loggerBuilder = new LoggerBuilder ();
$ loggerBuilder -> setFileName ( $ this -> outputFileBaseName );
$ loggerBuilder -> setSlackHandler ( $ slackHandlerBuilder -> build ());
$ logger = $ loggerBuilder -> build ();
$ logger -> critical ( $ exception , $ context );
請使用LoggerBuilder.setUseInDocker
以便在 Docker 上使用它。
當 setUseInDocker 設定為 true 時,不進行檔案輸出,日誌輸出為stdout
。
<?php
use Nekonomokochan PhpJsonLogger LoggerBuilder ;
$ exception = new Exception ( ' TestException ' , 500 );
$ context = [
' name ' => ' keitakn ' ,
' email ' => ' [email protected] ' ,
];
$ loggerBuilder = new LoggerBuilder ();
$ loggerBuilder -> setFileName ( $ this -> outputFileBaseName );
$ loggerBuilder -> setUseInDocker ( true );
$ logger = $ loggerBuilder -> build ();
$ logger -> critical ( $ exception , $ context );
NekonomokochanPhpJsonLoggerLogger
是擴充MonologLogger
的子類
您可以像MonologLogger
一樣使用它。
但是,對於下列方法,您只能傳遞擴充Exception
或Error
類別作為參數。
NekonomokochanPhpJsonLoggerLogger::error()
NekonomokochanPhpJsonLoggerLogger::critical()
NekonomokochanPhpJsonLoggerLogger::alert()
NekonomokochanPhpJsonLoggerLogger::emergency()
如果違反, NekonomokochanPhpJsonLoggerLogger
將拋出NekonomokochanPhpJsonLoggerInvalidArgumentException
麻省理工學院