Michael T. Smith
Michael T. Smith

Reputation: 578

Set custom event items dynamically for each log call using Zend Framework

We're using the Zend_Log class to update a few different "watchdog" database tables (that log different events: Batch scripts running, new data being processed, files generated, etc.).

Here is my current code (before the issue I'm looking into fixing.)

$writer = new Zend_Log_Writer_Db($db, 'watchdog', array(
    'priority'  => 'priority',
    'message'   => 'message',
    'owner'     => 'owner',
));

$logger = new Zend_Log($writer);
$logger->setEventItem('owner', 'MODULE_NAME');

This works perfectly fine. But, I want to add a database column called datetime that is a call to time() at the time of the event. So, in theory, it would be something like this:

$writer = new Zend_Log_Writer_Db($db, 'watchdog', array(
    'priority'  => 'priority',
    'message'   => 'message',
    'owner'     => 'owner',
    'datetime'  => 'datetime',
));

$logger = new Zend_Log($writer);
$logger->setEventItem('owner', 'MODULE_NAME');
$logger->setEventItem('datetime', time());

The problem I'm running into is that, obviously, the call to time() runs at the first time Zend_Log::setEventItem is called and not when Zend_Log::info() is called. So, the question is, how do I get the time() to be called and stored in my DB when Zend_Log::info() is called? Will I need to extend Zend_Log_Writer_Db with a more custom class?

Upvotes: 1

Views: 899

Answers (2)

Lee
Lee

Reputation: 351

Another solution I wanted to put out there is to use Zend_Db_Expr with a MySQL function like NOW() or TIMESTAMP().

$dblog->setEventItem('datetime', new Zend_Db_Expr('NOW()'));

Upvotes: 2

takeshin
takeshin

Reputation: 50698

Extending seems the best idea.

I would create a timestampable event, with default columns created_at and updated_at, and change it automatically on each log write.

(this is a Timestampable behaviour from Doctrine)

My_Log_Writer_Db_Timebstampable extends Zend_Log_Writer_Db

Upvotes: 1

Related Questions