简体   繁体   English

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

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

I just switched to monolog and wanted to log my message to the PHP console instead of a file.我刚刚切换到 monolog 并想将我的消息记录到 PHP 控制台而不是文件。 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.对于某些人来说,这似乎很明显,但是我花了一些时间才弄清楚如何做到这一点,而且我在 SO 上找不到类似的问题/答案。

The example on Monolog's Github readme only 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 的帮助页面或寻找登录浏览器控制台方法的人们的问题。

The solution is rather simple.解决方法相当简单。 Since the example shows a StreamHandler it's possible to pass in a stream (instead of the path to a file).由于示例显示了StreamHandler因此可以传入流(而不是文件的路径)。 By default, everything that is echo'ed in PHP is written to php://stdout / php://output so we can simple use one of those as stream for the StreamHandler :默认情况下,在 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 :)希望这可以节省一些时间:)

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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM