使用 Monolog 记录整个数组

Logs an entire array using Monolog

有什么方法可以使用 Monolog 记录整个数组吗?我一直在阅读几个文档,但没有找到以可读格式记录整个数组的方法,有什么建议吗?

我读过的文档:

如果您检查记录器界面 (https://github.com/php-fig/log/blob/master/Psr/Log/LoggerInterface.php),您将看到所有记录方法都将消息作为字符串获取,因此当您尝试使用字符串以外的变量类型进行记录时会收到警告。

我尝试使用处理器以自定义方式格式化数组,但正如预期的那样,处理器在您将变量发送到记录器接口后被触发。

记录数组的最脏方法可能是您选择的任何一种方法;

$logger->info(json_encode($array));
$logger->info(print_r($array, true));
$logger->info(var_export($array, true));

另一方面,您可能希望在单个处理器中格式化数组,以使用 DRY 原则集中格式化逻辑。

Json encode array -> Send as Json String -> json decode to array -> format -> json encode again

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 中注册请求处理器,请参阅标签节点以注册自定义频道的处理器。

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

现在您可以在中央请求处理器中根据需要格式化和记录您的阵列,而无需在每个控制器的阵列上 sorting/formating/walking。