簡體   English   中英

從類寫入日志文件錯誤消息

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM