Symfony 从类写入日志文件错误消息
我应该如何在日志文件中写入要从实体类发送的错误或消息? 这个想法是这样的:我有一些带有一些属性的项目,还有一个带有一些属性的配置。我需要检查该项是否具有配置属性中也存在的属性。当我调试我的应用程序时,我在这里:Symfony 从类写入日志文件错误消息,symfony,logging,Symfony,Logging,我应该如何在日志文件中写入要从实体类发送的错误或消息? 这个想法是这样的:我有一些带有一些属性的项目,还有一个带有一些属性的配置。我需要检查该项是否具有配置属性中也存在的属性。当我调试我的应用程序时,我在这里: public function getProperty(idProperty $propertyId) { $properties = $this->ItemProperties(); if (isset($properties[$propertyId->g
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;
}
那么我如何才能做到这一点呢?谢谢。您可以抛出异常并设置异常侦听器,它将写入日志。
内部实体:
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)
);
服务.yml
app.exception_listener:
class: Application\Listeners\ExceptionListener
arguments: ['@domain.logger']
tags:
- { name: kernel.event_listener, event: kernel.exception }
西蒙尼
您还可以将记录器注入实体并从实体写入日志,尽管这违反了单一责任原则
更新
DomainException是一个简单的类,继承自\Exception。在本例中,它仅用于区分自定义异常和PHP或其他库引发的异常
它还可以包含额外的功能,例如,在构造函数中接受两条消息,将其中一条写入日志文件,然后为用户输出另一条。@svgrafox该DomainException类我在哪里声明了beacuse在OnKerneleException中它说它未声明?