Create Custom LOG in Laravel
Yasser Elgammal

Yasser Elgammal @yasserelgammal

About: Software engineer @ AAIT

Location:
Egypt, Damietta
Joined:
Feb 18, 2019

Create Custom LOG in Laravel

Publish Date: Jan 15 '24
5 1

Sometimes we need to track specific action or processes that happens at different times or according to some conditions,

But not all actions are tracked, also many different kinds of actions are tracked in the main Laravel log, how can we customize a log to track this?

Inside config/logging.php

'channels' => [
    // ...

    'custom_logger' => [
        'driver' => 'single',
        'path' => storage_path('logs/custom.log'),
        'level' => 'debug',
    ],

    // ...
],
Enter fullscreen mode Exit fullscreen mode

In this example, we're creating a channel named 'custom_logger' that will use the single log driver. The log entries will be stored in the storage/logs/custom.log file.

Also, the Log has a level of severity [emergency, alert, critical, error, warning, notice, info and debug]:

  • Emergency: The highest log level, indicating a system is unusable,
  • Alert: action must be taken immediately,
  • Critical: critical conditions,
  • Error: error conditions,
  • Warning: warning conditions,
  • Notice: normal but significant condition,
  • Informational: informational messages,
  • Debug: The lowest log level, used for detailed debug messages,

Per our needs, we can choose between daily or single

  • single: print log inside one file.
  • daily: create a new log file every day named by the current date.

Note that there are different types of drivers for Log, you can take a look at Laravel official Documentation, Click here

Now we can use this log inside anywhere in our Laravel Application:

        Log::channel('custom_logger')->info('Enter your log message here.');
Enter fullscreen mode Exit fullscreen mode

You can replace printed messages from info() with other severity levels like emergency(), alert(), critical(), error(), warning(), notice(), or debug() depending on the severity of the log message you want to record.

Thanks for reading ♥

Comments 1 total

Add comment