php – 使用Monolog记录整个数组
有没有办法使用Monolog记录整个数组?我一直在阅读几个文档,但没有找到以可读格式记录整个数组的方法,任何建议?
我读过的文件: > Monolog,how to log PHP array into console?
如果检查记录器接口(
https://github.com/php-fig/log/blob/master/Psr/Log/LoggerInterface.php),您将看到所有记录方法都以字符串形式显示消息,因此当您尝试使用字符串以外的变量类型进行记录时会收到警告.
我尝试使用处理器以自定义方式格式化阵列,但正如预期的那样,在将变量发送到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 AcmeWebBundle; 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: MonologFormatterLineFormatter arguments: - "[%%datetime%%] %%channel%%.%%level_name%%: %%message%%n" monolog.processor.session_request: class: AcmeWebBundleCustomRequestProcessor arguments: [] tags: - { name: monolog.processor,method: processRecord,channel: testchannel } 并在控制器中将您的数组记录为json字符串, <?php namespace AcmeWebBundleController; use SymfonyBundleFrameworkBundleControllerController; 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'); } } 现在,您可以根据需要在中央请求处理器中格式化和记录阵列,而无需在每个控制器中对阵列进行排序/格式化/行走. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |