Categories
symfony

The Simplest Log!

Hi,

are you working on any serious system which perform financial transactions or maybe that’s the system with multi-user permissions level? This or that way you should take care of logging information about actions which were performed by system users. There are a couple of ways you may use to implement system log. And of course there is available Symfony log which you may use for your own purposes or customize anyhow.

Well, I’d like to stop here on the one really simple way you may try out. So first of all we would need database table to keep logs into, and here is what I’d propose:

[php]
CREATE TABLE `log`
(
`id` INTEGER NOT NULL AUTO_INCREMENT,
`user_id` INTEGER,
`type_id` INTEGER, # reference to message types table
`message` TEXT,
`created_at` DATETIME,
`updated_at` DATETIME,
PRIMARY KEY (`id`),
);
[/php]

It only depends on your fantasy what exactly you would like to keep as type_id, for instance there might be 3 levels of log messages: message / warning / error.

The next piece of code you should put into your lib folder and this way it will be accessible from any part of your symfony code:

[php]
getUser()->isAuthenticated()) {
$l = new Log();
$l->setUserId(sfContext::getInstance()->getUser()->getId());
$l->setTypeId($type_id);
$l->setMessage($msg);
$l->save();
}
}

static public function writeMessage($msg) {
$this->writeLog($msg, LOG_TYPE_ID_MESSAGE);
}

static public function writeWarning($msg) {
$this->writeLog($msg, LOG_TYPE_ID_WARNING);
}

static public function writeError($msg) {
$this->writeLog($msg, LOG_TYPE_ID_ERROR);
}

}
?>
[/php]

Don’t forget to specify your constants somewhere and somehow, e.g.

[php]
define(‘LOG_TYPE_ID_MESSAGE’, 1);
define(‘LOG_TYPE_ID_WARNING’, 2);
define(‘LOG_TYPE_ID_ERROR’, 3);
[/php]

This approach is absolutely simple and quite flexible. For instance if you’ll decide to add more log types – you should not change table structure or so.

And of course the final step – you’d like to observe your logs from backend. We use for quick backend creating – admin generator tool with the following genearator.yml content:

[php]
generator:
class: sfPropelAdminGenerator
param:
model_class: Log
theme: default
list:
title: System Log
display: [user_id, message, created_at]
filters: [user_id, message, created_at]
[/php]

Don’t forget to let me know if that was helpfull!
Thanks

2 replies on “The Simplest Log!”

Eskatos, first of all thanks for your comment and interest!

Even if initially I’m not going to update logs – that may be helpfull to have the way to update the log from admin interface (and keep an information when it was done). But of course you are right and this field may be simply skipped.

Leave a Reply

Your email address will not be published. Required fields are marked *