找不到添加调用日志函数的文件名和行号的方法。 我正在使用一个简单的 StreamHandler:
$this->log = new Logger('APP');
$this->log->pushHandler(new StreamHandler('/logs/app.log', Logger::DEBUG));
我想要类似的输出:
[2017-12-27 12:38:58 filename.php:1234] APP.DEBUG: test
或任何其他包含文件名和行号的格式。
谢谢并致以诚挚的问候
已经很晚了,但我知道怎么做了,我会发布给其他人。
首先,您需要创建自己的Processor,并使用要解析的新记录键(我将其命名为
file_info
):
class MyProcessor
{
/**
* @param array $record
* @return array
*/
public function __invoke(array $record)
{
$info = $this->findFile();
$record['file_info'] = $info['file'] . ':' . $info['line'];
return $record;
}
public function findFile() {
$debug = debug_backtrace();
return [
'file' => $debug[3] ? basename($debug[3]['file']) : '',
'line' => $debug[3] ? $debug[3]['line'] : ''
];
}
}
我使用 debug_backtrace 来获取第三个元素基本名称文件和行,但我不确定它是否每次都能工作。
然后,使用自定义的 LineFormatter 创建记录器(我从 here 获得这部分):
use Monolog\Logger;
use Monolog\Formatter\LineFormatter;
use Monolog\Handler\StreamHandler;
// the default date format is "Y-m-d\TH:i:sP"
$dateFormat = "Y n j, g:i a";
// the default output format is "[%datetime%] %channel%.%level_name%: %message% %context% %extra%\n"
$output = "[%datetime% %file_info%] %channel%.%level_name%: %message% %context% %extra%\n";
// finally, create a formatter
$formatter = new LineFormatter($output, $dateFormat);
// Create a handler
$stream = new StreamHandler(__DIR__.'/my_app.log', Logger::DEBUG);
$stream->setFormatter($formatter);
// bind it to a logger object
$myLogger = new Logger('mylogger');
$myLogger->pushHandler($stream);
现在,您可以使用
$myLogger->error('Foo');
,结果将是:
[2021 2 24, 6:19 pm ProductController.php:50] mylogger.ERROR: Foo [] []