Tuesday, November 10, 2020

Laravel and logging of errors

During the course of development, there are many tools and approaches to debug a programme. In Laravel there is a default logging that supports RFC 5424 and here is how to apply it in a Laravel 7 based application.

As a point of reference, this article is for default Laravel 7 on a Apache2 webserver. Which means, if PHP-FPM is used, check the webserver log files. Additionally, there are many more advanced logging by Laravel, for example use of Rollbar, if you have time to explore.

What is Laravel logging? 

Withing Laravel framework, its config/app.php determines classes that does logging. Monolog logging library is used to provide the classes that can be called from the framework. Its flexibility allows logging across different files and even disk. 

The default logging uses a channel known as stack and is configured as

 'default' => env('LOG_CHANNEL', 'stack'),

This provides logging in several levels of severity that range from in the following order;

  • info
  • debug
  • notice
  • warning
  • error
  • critical
  • emergency

Context data is provided for a more consistent format as described in PSR-3.

How to enable default logging? 

Edit the file .env and have this line to enable debug mode;

APP_DEBUG=true

Where is the default logging done? It all in the file laravel.log found in <project_folder>/storage/logs. Ensure the application have correct permission to write app/storage and all its subfolders. When using Selinux, also ensure its allowed to write.

When is logging done?

This can be done practically any where, such as within the controller, views and any other executable.

How to do the logging? 

Taking that you have by now enabled debug mode.

Lets look at how its done within a Controller.

  1. Ensure top of the controller file contains the line
    • use Illuminate\Support\Facades\Log;
  2. Write the code to log your message
    • Log::info('This is where the code runs');

Once when you run the application and the Log::info( ) gets triggered, have a look at the end of file storage/logs/laravel.log to find the message.

Will consider to write further on formatting of the log in order for logging tools to pull data and generate reports or monitoring

No comments:

Blog Archive