Code

Well, only one piece of code really...

Sqlite PDO handler for PEAR::Log

sqlite_pdo.phps (25 April 2009) Right click to download then rename the file to sqlite_pdo.php

The very first bit of code I have ever openly contributed apart from badly written snippets I cough up onto public forums from time to time. A big deal for me.

Why you should want this?
If you are trying to implement a PHP logging system, and you find the PEAR::Log package proffers the freedom you want, and you decide you may want to log to an sqlite database and you don't have the native sqlite_* functions installed or you just prefer to use PDO then this is what sqlite_pdo.php is for.
If you add value, correctly code or otherwise improve it, then do please let me know too.

Usage

1. You should already have PEAR installed, and have PEAR::Log working correctly.

2. Download sqlite_pdo.phps to /yourincludes/PEAR/Log folder, rename it sqlite_pdo.php

3. Calling PEAR::Log from your scripts. You can:

Either a) Pass in configuration and Log then instantiates and owns the PDO instance:


$filename = '/var/www/sqlite/logical_name.db' ;

$max_level = 7 ;  // change this at run time to supress logging levels

$conf = array (
'filename' => $filename ,
'persistent' => false ,
);

$logger = Log::singleton('sqlite_pdo', 'logical_table_name', 'Identifier for these logs', $conf, $max_level );

$logger->log('first event to be logged', PEAR_LOG_WARNING);

Or b) Pass in a ready made PDO instance:


$filename = '/var/www/sqlite/logical_name.db' ;

$max_level = 7 ;  // change this at run time to supress logging levels

$settings = array(
    PDO::ATTR_PERSISTENT => true,
    PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
);

$conf = new PDO( 'sqlite:'.$filename , NULL, NULL, $settings ) ;

$logger = Log::factory('sqlite_pdo', 'logical_table_name', 'Identifier for these logs', $conf, $max_level );

$logger->log('first event to be logged', PEAR_LOG_WARNING);

Those samples show just a couple of the Log settings you can make.

Read the Log documents carefully and you will see you can do use PEAR::Log as simply as this:


include("Log.php");

$db = new PDO( 'sqlite:/path/to/application_log.db') ;

$log = Log::singleton('sqlite_pdo', 'This_application', 'user_errors', $db );

//later on, deep in userland ...

if ( $user_subverted_my_filter )
        $log->info( $bad_IP . ' on line ' .  __LINE__ . '  in class ' . __CLASS__ );

Using the shortcut $log->info() as shown in that last line is the same as setting PEAR_LOG_INFO. You can tweak whether or not to log that level of logging using bitmasks. It automatically detects what setting you have made.