简体   繁体   English

从类写入日志文件错误消息

[英]Writing in log file error message from class

How should I write in log file the error or the message I want to from an Entity class? 如何从实体类中将错误或消息写入日志文件? The idea is like this: I have some items with some properties and also a configuration with some properties. 这个想法是这样的:我有一些带有某些属性的项目,还有一个带有某些属性的配置。 I need to check if the item has the property that also exists in the configuration properties. 我需要检查项目是否具有配置属性中也存在的属性。 When I debug my application, at some point I am here: 当我调试应用程序时,有时会在这里:

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

So how can I achieve that? 那么我该如何实现呢? Thank you. 谢谢。

You can throw Exception and setup Exception Listener , which will write into log. 您可以抛出Exception并设置Exception Listener ,这将写入日志。 Inside Entity: 内部实体:

if (isset($properties[$propertyId->getValue()])) {
    return $properties[$propertyId->getValue()];
} else {
   throw new DomainException('Something is wrong.' . print_r($this, true));
}

In Listener class: 在侦听器类中:

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 services.yml

  app.exception_listener:
    class: Application\Listeners\ExceptionListener
    arguments: ['@domain.logger']
    tags:
      - { name: kernel.event_listener, event: kernel.exception }

Symfony Events . Symfony 事件

You can also inject Logger into your Entity and write to log from there, though it violates Single Responsibility Principle. 您也可以将Logger注入到您的实体中并从那里写入日志,尽管它违反了单一职责原则。

UPDATE UPDATE

DomainException is a simple class, inheriting from \\Exception . DomainException是一个简单的类,继承自\\Exception In this example it only exists to distinguish between your custom exceptions and those that are thrown by PHP or other libraries. 在此示例中,仅用于区分您的自定义异常与PHP或其他库引发的异常。

It can also contain additional functionality, for example, accepting two messages in constructor, writing one of them into log file and outputting another for your user. 它还可以包含其他功能,例如,在构造函数中接受两条消息,将其中一条写入日志文件,然后为用户输出另一条消息。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM