Small log file writer with adjustable log level threshold settings.
Via Composer
$ composer require faslatam/log
$logger = new Forestry\Log\Log('/tmp/dummy.log');
//Just log notices and above.
$errorLog = new Forestry\Log\Log('./logs/error.log', Psr\Log\LogLevel::NOTICE);
Another way to create an instance is the use of one of the factories. There is one for each threshold level.
Here is an example for a logger with an error threshold:
$factory = new ErrorLogger();
$logger = $factory->create('/tmp/error.log');
Forestry\Log provides methods for the log levels defined by RFC 5424 (debug, info, notice, warning, error, critical, alert and emergency). There's a method for each of these levels:
$logger->emergency('This is an emergency message');
$logger->alert('This is an alert message');
$logger->critical('This is an critical message');
$logger->error('This is an error message');
$logger->warning('This is an warning message');
$logger->notice('This is a notice message');
$logger->info('This is an information');
$logger->debug('This is a debug message');
You can also use a generic log
method:
$logger->log(Psr\Log\LogLevel::DEBUG, 'this is a debug message');
You can use placeholders in the your message string and fill them using the associative context array. The array keys have to match the placeholders without the curly brackets:
$user = ['name' => 'John Doe', 'mail' => 'j.doe@example.org'];
$logger->info('Send mail to {name} ({mail})', $user); // Send mail to John Doe (j.doe@example.org)
The default date format is Y-m-d H:i:s
. You can change it by using the setDateFormat
method:
$logger->setDateFormat('r'); // e.g. Thu, 21 Dec 2000 16:01:07 +0200
This method accepts any string which is compatible with PHPs native date()
.
The default format for the log message is date level message
. To change it, you can re-arrange the placeholders with setLogFormat
:
$logger->setLogFormat('[{level}|{date}] {message}'); // [INF0|2013-04-25 13:37:42] This is an info message
There are the following placeholder available:
- {date}
- {level}
- {message}
These placeholders will be replaced with ones for sprintf()
, so you can also use the following:
%1$s
= date%2$s
= level%3$s
= message
To change the threshold level of an existing instance, use the setLogThreshold
method:
$logger->setLogThreshold(Psr\Log\LogLevel::DEBUG);
To get the current threshold level of an existing instance, use the getLogThreshold
method:
$level = $logger->getLogThreshold();
$logger->setLogThreshold(Psr\Log\LogLevel::INFO);
$logger->logInfo('my info');
$logger->setLogThreshold($level);
$ composer test
Please see CONTRIBUTING for details.
The MIT License (MIT). Please see License File for more information.