![](/img/trans.png)
[英]Why Symfony dies with a 500 error without Monolog writing anything to the log file?
[英]Writing in log file error message from class
如何从实体类中将错误或消息写入日志文件? 这个想法是这样的:我有一些带有某些属性的项目,还有一个带有某些属性的配置。 我需要检查项目是否具有配置属性中也存在的属性。 当我调试应用程序时,有时会在这里:
public function getProperty(idProperty $propertyId)
{
$properties = $this->ItemProperties();
if (isset($properties[$propertyId->getValue()])) {
return $properties[$propertyId->getValue()];
}else{
//here I want to write in the log file that the propertyId is not in the $properties.
}
return null;
}
那么我该如何实现呢? 谢谢。
您可以抛出Exception
并设置Exception Listener
,这将写入日志。 内部实体:
if (isset($properties[$propertyId->getValue()])) {
return $properties[$propertyId->getValue()];
} else {
throw new DomainException('Something is wrong.' . print_r($this, true));
}
在侦听器类中:
public function __construct(LoggerInterface $logger)
{
$this->logger = $logger;
}
public function onKernelException(GetResponseForExceptionEvent $event)
{
$e = $event->getException();
if ($e instanceof DomainException) {
$this->logger->warning('Exception ' . get_class($e) , ['message' => $e->getMessage()]);
$event->setResponse(
new JsonResponse(['error' => $e->getMessage()], 400)
);
services.yml
app.exception_listener:
class: Application\Listeners\ExceptionListener
arguments: ['@domain.logger']
tags:
- { name: kernel.event_listener, event: kernel.exception }
Symfony 事件 。
您也可以将Logger
注入到您的实体中并从那里写入日志,尽管它违反了单一职责原则。
UPDATE
DomainException
是一个简单的类,继承自\\Exception
。 在此示例中,仅用于区分您的自定义异常与PHP或其他库引发的异常。
它还可以包含其他功能,例如,在构造函数中接受两条消息,将其中一条写入日志文件,然后为用户输出另一条消息。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.