有没有办法使用Monolog记录整个数组?我一直在阅读几个文档,但没有找到以可读格式记录整个数组的方法,任何建议?
我读过的文件:
> Monolog,how to log PHP array into console?
> http://symfony.com/doc/current/cookbook/logging/monolog.html
> https://www.webfactory.de/blog/logging-with-monolog-in-symfony2
如果检查记录器接口(
https://github.com/php-fig/log/blob/master/Psr/Log/LoggerInterface.php),您将看到所有记录方法都以字符串形式显示消息,因此当您尝试使用字符串以外的变量类型进行记录时会收到警告.
原文链接:https://www.f2er.com/php/130628.html我尝试使用处理器以自定义方式格式化阵列,但正如预期的那样,在将变量发送到logger接口后会触发处理器.
$logger->info(json_encode($array)); $logger->info(print_r($array,true)); $logger->info(var_export($array,true));
另一方面,您可能希望在单个proccessor中格式化数组,以使用DRY原则集中格式化逻辑.
Json编码数组 – >发送为Json字符串 – > json解码为数组 – >格式 – > json再次编码
CustomRequestProcessor.PHP
<?PHP namespace Acme\WebBundle; class CustomRequestProcessor { public function __construct() { } public function processRecord(array $record) { try { //parse json as object and cast to array $array = (array)json_decode($record['message']); if(!is_null($array)) { //format your message with your desired logic ksort($array); $record['message'] = json_encode($array); } } catch(\Exception $e) { echo $e->getMessage(); } return $record; } }
在config.yml或services.yml中注册请求处理器,请参阅tags节点以注册自定义通道的处理器.
services: monolog.formatter.session_request: class: Monolog\Formatter\LineFormatter arguments: - "[%%datetime%%] %%channel%%.%%level_name%%: %%message%%\n" monolog.processor.session_request: class: Acme\WebBundle\CustomRequestProcessor arguments: [] tags: - { name: monolog.processor,method: processRecord,channel: testchannel }
并在控制器中将您的数组记录为json字符串,
<?PHP namespace Acme\WebBundle\Controller; use Symfony\Bundle\FrameworkBundle\Controller\Controller; class DefaultController extends Controller { public function indexAction() { $logger = $this->get('monolog.logger.testchannel'); $array = array(3=>"hello",1=>"world",2=>"sf2"); $logger->info(json_encode($array)); return $this->render('AcmeWebBundle:Default:index.html.twig'); } }
现在,您可以根据需要在中央请求处理器中格式化和记录阵列,而无需在每个控制器中对阵列进行排序/格式化/行走.