Reputation: 609
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.
Upvotes: 0
Views: 301
Reputation: 2024
You can throw Exception
and setup Exception Listener
, which will write into log.
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
app.exception_listener:
class: Application\Listeners\ExceptionListener
arguments: ['@domain.logger']
tags:
- { name: kernel.event_listener, event: kernel.exception }
Symfony Events.
You can also inject Logger
into your Entity and write to log from there, though it violates Single Responsibility Principle.
UPDATE
DomainException
is a simple class, inheriting from \Exception
. In this example it only exists to distinguish between your custom exceptions and those that are thrown by PHP or other libraries.
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.
Upvotes: 1