2017-08-10 82 views
0

如何在日誌文件中寫入我想從實體類發出的錯誤或消息? 這個想法是這樣的:我有一些項目具有一些屬性,也有一些屬性的配置。我需要檢查該項目是否具有也存在於配置屬性中的屬性。當我調試我的應用程序,在某些時候我在這裏:在日誌文件中寫入類錯誤消息

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

那麼我該如何實現這一目標?謝謝。

回答

1

你可以扔Exception和設置Exception Listener,這將寫入日誌。 內部實體:

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

在Listener類:

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的Events

您也可以將Logger注入您的實體並寫入日誌中,但違反單一責任原則。

UPDATE

DomainException是一個簡單的類,從\Exception繼承。在這個例子中,它只存在區分你的自定義異常和PHP或其他庫引發的異常。

它還可以包含其他功能,例如,在構造函數中接受兩條消息,將其中一條寫入日誌文件併爲用戶輸出另一條消息。

+0

@svgrafox該DomainException類我在哪裏聲明beacuse在onKernelException它說它的未聲明? – IleNea

+0

@IleNea我用解釋更新了我的答案。 – svgrafov