Product SiteDocumentation Site

2.2.4. Logging to the database

The "database" logger allows you to log message to a database table. The create syntax for the default table is as follows:
Example 2.13. Example schema for a database logger
CREATE TABLE `jos_log_entries` (
  `priority` int(11) DEFAULT NULL,
  `message` varchar(512) DEFAULT NULL,
  `date` datetime DEFAULT NULL,
  `category` varchar(255) DEFAULT NULL,
  KEY `idx_category_date_priority` (`category`,`date`,`priority`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

To log messages using the "database" logger, you the following code as a guide.
Example 2.14. Using a database logger
// Add the logger.
JLog::addLogger(
    array(
        'logger' => 'database'
    ),
    JLog::ALL,
    'dblog'
);

// Add the message.
JLog::add('Database log', JLog::INFO, 'dblog');

Notice that the example binds the logger to all message priorities, but only those with a category of "dblog".
If you are wanting to store additional information in the message, you can do so using a JSON encoded string. For example:
Example 2.15. Storing variable information in a log message
// Assemble the log message.
$user = JFactory::getUser();
$log = array(
    'userId' => $user->get('id'),
    'userName' => $user->get('name'),
    'stockId' => 'SKU123',
    'price' => '7.49',
    'quantity' => 10
);

// Add the message.
JLog::add(json_encode($log), JLog::INFO, 'dblog');

This makes it possible to retrieve detailed information for display.