0

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.

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

@svgrafox that DomainException class where do i declared beacuse in onKernelException it says that its undeclared?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.