Laravel 5: Accessing the Logging Features With logger

April 14, 2018 —John Koster

The logger helper function can be used to retrieve the logger instance from the Service Container or as a convenient way to log debug messages within your Laravel application without having to inject any dependencies or include the "Illuminate\Support\Facades\Log" facade.

#Signature

The signature of the logger function is:

1function logger(
2 $message = null,
3 array $context = []
4);

#Example Use

If the $message is null, which it is by default, the logger function will return an implementation of "Illuminate\Contracts\Logging\Log", which by default is an instance of the "\Illuminate\Log\Writer" class.

When the logger function is not being used to retrieve a Log instance, a $message can be set and it will be written to Laravel's log files. An optional $context can also be supplied. The $context must be an array, although the actual elements of the array do not have to be arrays themselves.

The following example shows the usage of the logger helper function when supplying a $message and $context. An example of what the function calls would produce in the log files follows the code examples.

1// An example message context.
2$context = ['name' => 'John Doe', 'email' => 'you@homestead'];
3 
4// A log message without context.
5logger('This is a log message without context');
6 
7// A log message where the context is an array.
8logger('This is a log message', $context);
9 
10// A log message where the context is an array of objects.
11logger('This is another log message', [(object) $context]);

The above code would produce results similar to the following (some lines have been indented to improve readability and prevent wrapping):

1...
2[2015-06-15 02:21:13] local.DEBUG: This is a log message without context
3[2015-06-15 02:21:13] local.DEBUG: This is a log message
4 {"name":"John Doe","email":"you@homestead"}
5[2015-06-15 02:21:13] local.DEBUG: This is another log message
6 [
7 "[object] (stdClass: {\"name\":\"John Doe\",\"email\":\"you@homestead\"})"
8 ]
9...

The following method calls are all equivalent:

1use Illuminate\Support\Facades\Log;
2 
3app('log')->debug('Log a debug message');
4 
5resolve('log')->debug('Log a debug message');
6 
7log('Log a debug message');
8 
9log()->debug('Log a debug message');
10 
11Log::debug('Log a debug message');

Some absolutely amazing
people

The following amazing people help support this site and my open source projects ♥️
If you're interesting in supporting my work and want to show up on this list, check out my GitHub Sponsors Profile.