PHP:如何使用 monolog 登录到控制台 (php://out)?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/25787258/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 17:59:51  来源:igfitidea点击:

PHP: How to use monolog to log to console (php://out)?

phpconsolestdoutmonolog

提问by Hirnhamster

I just switched to monolog and wanted to log my message to the PHP console instead of a file. This might seem obvious for some people, but it took me a little while to figure out how to do that and I couldn't find a similar question/answer on SO.

我刚刚切换到 monolog 并想将我的消息记录到 PHP 控制台而不是文件。对于某些人来说,这似乎很明显,但是我花了一些时间才弄清楚如何做到这一点,而且我在 SO 上找不到类似的问题/答案。

The example on Monolog's Github readmeonly shows how to use a file:

Monolog 的 Github 自述文件中的示例仅展示了如何使用文件:

<?php

use Monolog\Logger;
use Monolog\Handler\StreamHandler;

// create a log channel
$log = new Logger('name');
$log->pushHandler(new StreamHandler('path/to/your.log', Logger::WARNING)); // <<< uses a file

// add records to the log
$log->addWarning('Foo');
$log->addError('Bar');

But it doesn't state anywhere how messages can be logged to the console. After searching on Google, I landed either on a help page for Symfony or questions of people looking for a way to log to the browser console.

但它没有说明如何将消息记录到控制台。在 Google 上搜索后,我登陆了 Symfony 的帮助页面,或者登陆浏览器控制台的人们的问题。

回答by Hirnhamster

The solution is rather simple. Since the example shows a StreamHandlerit's possible to pass in a stream (instead of the path to a file). By default, everything that is echo'ed in PHP is written to php://stdout / php://outputso we can simple use one of those as stream for the StreamHandler:

解决方法相当简单。由于示例显示了 aStreamHandler可以传入流(而不是文件的路径)。默认情况下,在 PHP 中回显的所有内容都会写入php://stdout / php://output,因此我们可以简单地使用其中之一作为以下内容的流StreamHandler

<?php

use Monolog\Logger;
use Monolog\Handler\StreamHandler;

// create a log channel
$log = new Logger('name');
$log->pushHandler(new StreamHandler('php://stdout', Logger::WARNING)); // <<< uses a stream

// add records to the log
$log->warning('Foo');
$log->error('Bar');

Hope this saves somebody some time :)

希望这可以节省一些时间:)

回答by Justin Tilson

Some extra details if you want to tweak the default message formatting at the same time:

如果您想同时调整默认消息格式,请提供一些额外的详细信息:

use Monolog\Logger;
use Monolog\Formatter\LineFormatter;
use Monolog\Handler\StreamHandler;

$output = "[%datetime%] %channel%.%level_name%: %message%\n";
$formatter = new LineFormatter($output);

$streamHandler = new StreamHandler('php://stdout', Logger::DEBUG);
$streamHandler->setFormatter($formatter);

$logger = new Logger('LoggerName');
$logger->pushHandler($streamHandler);