Creating custom log file in Laravel

HouseOfCoder
1 min readJun 14, 2021

Often times we come across requirement where we want to create custom log file based on functionality, So rather than logging everything in default log file we could have functionality specific log files.

How?

It’s simple, Create new logging channel. Laravel logging is based on channels. Each channel represents a specific way of writing log information.

Where do I configure new channel?

You could specify new channel inside config/logging.php configuration file.

# Create this new array index inside 'channels' => [..] ‘user_activity_log’ => [
‘driver’ => ‘daily’,
‘path’ => storage_path(‘logs/user_activity.log’),
‘level’ => ‘debug’,
],

I’ve created new log channel named user_activity_log. Did you noticed, I’ve used daily driver so instead of writing log in single log file there will be new file generated on each day.

How do I use newly created channel?

It’s easy. Just use the channel method on the Log facade to retrieve and log to above created channel. (**Do not forget to include Log facade)

# Include Log facade
use Illuminate\Support\Facades\Log;
# Example One
Log::channel('user_activity_log')->info('New user logged in');
#Example Two
$user_name = auth()->check() ? auth()->user()->name : '';
$user_email = auth()->check() ? auth()->user()->email : '';
$user = ['name'=>$user_name, 'email'=>$user_email];
Log::channel('user_activity_log')->info('User details',$user]);

Mission accomplished

I hope you guys got everything that I “tried” to explain in brief. For more details and advance logging customization please do visit Laravel Documentation.

Thanks for taking the time to read my article🙂 If you enjoyed it and would like to see more content like this, please consider following me on Medium.

--

--

HouseOfCoder

Web developer by profession. Crafting code and contemplative thoughts. Join me on a journey of tech, life, and mindfulness.