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
麻省理工学院