The Log Core Library writes the application logs.
The Log Core Library has the following drivers:
The StdOut prints the log output directly into the console output. This is the default driver used by the Log instance (See: Bootstrap.php for more details).
The class for this driver is: Log_StdOut.
Instantiation example:
Log::instance()->attach(new Log_StdOut());
The StdErr driver prints the log output directly into the stderr. It is recommended to use this driver only when errors are reported.
The class for this driver is: Log_StdErr.
Instantiation example:
Log::instance()->attach(new Log_StdErr());
The Syslog driver sends the logs to the Syslog.
The class for this driver is: Log_Syslog
Instantiation example:
Log::instance()->attach(new Log_Syslog());
The Syslog driver accepts the following two optional parameters:
Instantiation example:
// Logs are sent using the "myapp" as identifier and debug facility
Log::instance()->attach(new Log_Syslog('myapp', LOG_DEBUG));
The File driver write the logs into different files.
The class for this driver is: Log_File
Instantiation example:
Log::instance()->attach(new Log_File('/tmp/logs'));
The File driver requires one parameter:
Log files are going to be structured by date, so years and months subdirectories are going to be created. The logs file names are represented by day number.
In the previous section about the drivers we learned how to instantiate our Log class using different drivers, however there are some aspects about the class instantiation and driver attachment that you should know:
It is possible to create different Log instances using singleton passing one unique identifier to the instance method. Example:
Log::instance('mysecondlog')->attach(new Log_StdOut());
It is possible to attach more than one driver to each instance. Example:
// Attach two drivers, so messages are sent to StdOut and Syslog at same time
Log::instance()
->attach(new Log_StdOut())
->attach(new Log_Syslog());
The following log levels are available:
Logs are written using the add method.
The parameters for the add method are the following ones:
Example:
// Send message with log level "Error".
// The ":file" and ":error" parameters are going to be replaced
Log::instance()->add(Log::ERROR, 'Error in :file because :error', [':file' => '/etc/hosts', ':error' => 'file is missing']);
// Send message with log level "Debug"
Log::instance()->add(Log::DEBUG, 'Passed test');
Example:
try
{
throw new Exception('Hey Hey Hey, something was wrong');
}
catch (Exception $e)
{
// Send exception error as "critical" error level and pass the exception as additional values
// so the debug backtrace is going automatically added to the log message
Log::instance()->add(Log::CRITICAL, $e->getMessage, null, ['exception' => $e]);
}
It is possible to detach and attach new drivers at runtime. Example:
// Attach a new driver
Log::instance()->attach(new Log_Syslog('myapp'));
// Detach driver
Log::instance()->detach(new Log_StdOut());