4

In D7 is used to log using Watchdog function. In D8, I see its gone and I should use something called the logging API.

What I a trying to do:

  1. I have created a menu/route, mysite.com/logmessage
  2. When user opens that url in browser, I want to log "hello" to the dblog.

Where should I register the service that D8 documentation says to do? Is it in the services.yml file in sites/default folder?

Can I just load the said class in my controller/module file and call the function for logging? Or should I explicitly extend the class first in my module before using the function?

2

2 Answers 2

8

Can I just load the said class in my controller/module file and call the function for logging?

Yes; well, by "load the said class" you actually mean "get or inject an instance of the service class" in this context, but yes.

should I explicitly extend the class first in my module before using the function?

Not unless you need functionality that the existing service doesn't provide.

In non DI code use:

\Drupal::logger('my_module')->info('Info');

In DI code, inject the service and use:

$this->logger->info('Info');
5
  • DI: you either inject it via service file OR using the ContainerInjectionInterface and listing the services in the class in the create method
    – ssibal
    Commented Jun 26, 2018 at 11:35
  • Yep @ssibal, or it's already available if you're in a controller
    – Clive
    Commented Jun 26, 2018 at 11:42
  • I don't really like the base drupal controller, but it's a different topic!: )
    – ssibal
    Commented Jun 26, 2018 at 12:01
  • You either extend ControllerBase or create your own from the ground up. For many people the first one will suffice most of the time.
    – Kevin
    Commented Jun 26, 2018 at 21:14
  • For different types for log message like 'info' or 'alert' refer this link tamildic.com/how-to-log-watchdog-message-in-drupal-8
    – Manikandan
    Commented Aug 16, 2019 at 11:32
4

There are many different types of logging, all called the same way as per the documentation:

\Drupal::logger('my_module')->alert($message);

\Drupal::logger('my_module')->info($message);

\Drupal::logger('my_module')->debug($message);

Just call this code anywhere in your module, if you want to register logmessage as a path you'll need to create my_module.routing.yml, etc.

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.