Symfony / Monolog:如何自定义404找不到异常的日志格式

时间:2016-12-12 10:43:23

标签: php symfony logging http-status-code-404 monolog

Monolog提供了exclude 404 errors from the log的方法,但如果我想自定义它们而不是完全抑制它们呢?

所以显示的不同于:

  

[2016-12-12 10:41:01] request.ERROR:未捕获的PHP异常Symfony \ Component \ HttpKernel \ Exception \ NotFoundHttpException:“在/ myproject找不到”GET / non-existing-route“的路由/vendor/symfony/symfony/src/Symfony/Component/HttpKernel/EventListener/RouterListener.php第125行{“exception”:“[object](Symfony \ Component \ HttpKernel \ Exception \ NotFoundHttpException(code:0):找不到路由for /“GET / non-existing-route \”at /myproject/vendor/symfony/symfony/src/Symfony/Component/HttpKernel/EventListener/RouterListener.php:125,symfony \ Component \ Routing \ Exception \ ResourceNotFoundException(code: 0):at /myproject/var/cache/dev/appDevDebugProjectContainerUrlMatcher.php:1181)"} []

2 个答案:

答案 0 :(得分:1)

假设您正在谈论app / logs目录中的日志生活。如果是这样,我会这样做,这是非常直接的。

  1. 创建自定义记录器和关联的日志格式化程序。示例:Creating a custom monolog logger and formatter in symfony

  2. 然后我会在自定义事件侦听器中捕获NotFoundHttpException异常(例如:Triggering redirect in event listener with onKernelException when 404 NotFoundHttpException occurs)并使用我在步骤1中创建的自定义记录器记录它。

  3. 注意:您的自定义记录器在上面的步骤1中注入控制器。在您的情况下,将其注入您的事件监听器。

答案 1 :(得分:1)

可能的解决方案是使用日志处理器。

详细文档位于How to Add extra Data to Log Messages via a Processor

然后在流程内部或检测NotFoundHttpException并将其替换为人类可读的消息。