2

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

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');
| improve this answer | |
  • DI: you either inject it via service file OR using the ContainerInjectionInterface and listing the services in the class in the create method – ssibal Jun 26 '18 at 11:35
  • Yep @ssibal, or it's already available if you're in a controller – Clive Jun 26 '18 at 11:42
  • I don't really like the base drupal controller, but it's a different topic!: ) – ssibal Jun 26 '18 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 Jun 26 '18 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 Aug 16 '19 at 11:32
3

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.

| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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