Monolog is a modern and light-weight, extensible logging platform implementing the PSR-3 Interface which is available via composer. It allows you to easily collect log messages, process them using various Formatters and finally allows a stack of different handlers, which allows for a fairly flexible configuration.
There are many database handlers, but at time of this writing there was no Monolog MySQL Handler, which allows to store log messages to database. Due to the extensibility of the framework, I decided to implement a Handler, which I present here.
Monolog supports the use of context attributes, which are passed among with the actual log message. This handler leverages this by storing a defined subset of these attributes as separate database column, which is useful for later searching and sorting. Examples for those attributes could be username, user-id or current URL of the user during the logged message.
During initialization of the handler, you can pass an array of attribute names, which are then used to create (or modify, using add and drop column statements) the database table. When logging a message, and those attributes are present in the context attributes, they get stored in the corresponding database field. it is set to NULL, if the attributes are not passed.
Further, it supports the main feature you would expect from a database handler – it stores the log messages in a database.
monolog-mysql is available via composer. Just add the following line to your required section in composer.json and update.
Just use it as any other Monolog Handler, push it to the stack of your Monolog Logger instance. The Handler however needs some parameters:
- $pdo PDO Instance of your database. Pass along the PDO instantiation of your database connection with your database selected.
- $table The table name where the logs should be stored
- $additionalFields simple array of additional database fields, which should be stored in the database. The columns are created automatically, and the fields can later be used in the extra context section of a record. See examples below. Defaults to an empty array()
- $level can be any of the standard Monolog logging levels. Use Monologs statically defined contexts. Defaults to Logger::DEBUG
- $bubble Defaults to true
$mySQLHandler = new MySQLHandler($pdo, "log", array('username', 'userid'), \Monolog\Logger::DEBUG);
$logger = new \Monolog\Logger($context);
//Now you can use the logger, and further attach additional information
$logger->addWarning("This is a great message, woohoo!", array('username' => 'John Doe', 'userid' => 245));
This tool is free software and is distributed under the MIT license