Creating a Custom Log in Laravel
Logging to custom log files could be really helpful in certain scenarios. Some of them being:
- Parsing logs for sending data to the analytics systems or to the customer servicing systems.
- Feeding failure data for reprocessing by the CRON based Jobs.
- Logging test mails into a custom log file. (see below)
Creating a custom log is straightforward.
Add the following to the config/logging.php
file
'custom' => [
'driver' => 'single',
'path' => storage_path('logs/custom.log'),
'level' => 'alert',
],
Any logging that you’d now do on alert
level would be visible in the custom.log
file.
Logging test mails into a custom log file
It can be quite helpful if you are testing email and don’t want to subscribe or sign up to an email service.
However Laravel documentation is not really helpful in this case. They just say…
Instead of sending your emails, the log mail driver will write all email messages to your log files for inspection.
Although if are feeling invedtigative enough you’d look inside config/mail.php
for mailer/driver, you’d find the below
'log' => [
'transport' => 'log',
'channel' => env('MAIL_LOG_CHANNEL'),
],
Once you change the value of MAIL_MAILER
in your .env
to log
MAIL_MAILER=log
your emails would starting landing in the default laravel.log
. This is okay for basic email testing scenario, but that is not what you would love. You would probably want all the emails landing in a custom log file other than the laravel.log
.
Just add the following in your .env
MAIL_LOG_CHANNEL=mail
Add the following to the config/logging.php
file (note the log level)
'mail' => [
'driver' => 'single',
'path' => storage_path('logs/mail.log'),
'level' => 'debug',
],
You have a dedicated mail logger now.