eClog

eClog 3.0
copyright (c) 2009-2012 Kjell-Inge Gustafsson, kigkonsult
kigkonsult.se eClog
kigkonsult.se contact

A PHP log class.

Description

eClog offer ability to log to file (default), console, database, mail, error_log and syslog. Multiple parallel handlers are supported. Also, when using a specific error handler function (attached), ability to trigger PHP errors.

To be used when a simple log class is sufficient and the output/collecting media is supported.

There are ongoing development on stomp, mqseries and snmp handlers.

The reason for the high version number, 3.0, is that eClog 3.0 origins from an internal file debug tool and is, as time goes by, extended, enhanced and, in the end, rewritten using a more (or less) object-oriented structure and a test-driven development approach.

[index] [top]

Support

Use the kigkonsult.se contact page for queries, improvement/development issues or professional support and development. Please note that paid support or consulting service has the highest priority.

Our services are available for support and designing and developing customizations, adaptations and other PHP/MySQL solutions with a special focus on software utility and reliability, supported through our iterative acquire/design/transition process modell.

[index] [top]

Donate

You can show your appreciation for our free software and can support future development by making a donation to the kigkonsult GPL/LGPL projects.

Make a donation of any size by clicking here. Thanks in advance!

[index] [top]

Index

Description
Support
Donate
Index
Files
Install
Functions
Create
log
flush
addHandler
Handlers
General configuration parameters
db
console
errorlog
file
mail
null
syslog
PHP error handler
eClog test
Copyright_and_Licence
Copyright
Licence

Files

Files included in the eClog Package:

eClog.class.php
PHP class file
eClog.db.sql
eClog MySQL database create log_table script
eClog.inc.php
PHP general error handler function file
eClog.test.php
eClog test PHP/HTML form
eClog.test.inc.php
eClog additional PHP test functions
eClog.README.html
this file
liro-1234.xml
xml template, used in eClog.test.php
LPGL.txt
Licence
[index] [top]

Install

Unpack to any folder within application include path.

Include eClog class in PHP script.

Example

<?php
require_once "[path/]eClog.class.php";
.. .
?>

Short PHP code snippet using default values:

Example
<?php
require_once "eClog.class.php";
.. .
$eClog = new eClog(); // default type="file", filename="log.log", prio=debug
..
$eClog->log( "debug message" ) // default prio=debug
.. .
$eClog->flush();
.. .
?>
[index] [top]

Functions

Create

eClog offer two create methods:

Create a new eClog object instance:
__construct
Using only one instance of a eClog and provide a global access point to that instance:
using singleton pattern

Both methods force a log (notice) start informative entry.

Create object instance

Create a new eClog object instance.

Format, description
eClog::_construct( [string $type [ ,mixed $file [ ,string $identity [ ,array $config [ ,int $priority ]]]]] )
Format, parameters
type
eClog handler type
default "file"
"db" - MySQL database (using PHP mysqli extension)
"console" - STDOUT/STDERR
"errorlog" - using the PHP ini error_log file
"file" - logging to file
"mail" - using the built in PHP mail function
"null"
"syslog" - using the system error file
file (facility)
Output specification
default "log.log"
Special facility directives for
console
file
syslog
 
identity
(short) log specification.
default "" (empty)
 
configuration
handler configuration array
default empty
vary depending on handler type:
db - database (using PHP "mysqli" extension)
console
errorlog
file (default handler)
mail - using PHP "mail" function
null
syslog
priority
default "7" (debug)
eClog uses PHP "syslog" priority level constants
LOG_EMERG
system is unusable
LOG_ALERT
Immediate action required
LOG_CRIT
critical conditions
LOG_ERR
error conditions
LOG_WARNING
warning conditions
LOG_NOTICE
normal, but significant, condition
LOG_INFO
informational message
LOG_DEBUG
debug-level message
Return value

Returns a new eClog object instance.

Example
<?php
.. .
$eClog = new eClog( "file", "log.log", "testidentity", FALSE, 7 );
.. .
?>

Create using singleton pattern

Create or reuse an eClog object instance using a singleton pattern.

Format, description
eClog::singleton([ string $type [,mixed $file [,string $ident [,array $config [,int $priority]]]]])
Format, parameters

See Create object instance above.

Return value

Returns an eClog (singleton) object instance.

Example
<?php
.. .
$eClog = eClog::singleton( "file", "log.log", "testidentity", FALSE, 7 );
.. .
?>
[index] [top] [up]

log

Add a new message with (opt) priority into eClog handler(-s) queue.

Format, description
eClog::log(     mixed $message [, int $priority])
eClog::emerg(   mixed $message )
eClog::alert(   mixed $message )
eClog::crit(    mixed $message )
eClog::err(     mixed $message )
eClog::warning( mixed $message )
eClog::notice(  mixed $message )
eClog::info(    mixed $message )
eClog::debug(   mixed $message )
Format, parameters
Message
log message (some characters escaped when using eClog db handler)
string or numeric
logged "AS IS"
array
exploded (into one logged "row") as *[" <key> => <value> "]
other
using PHP "var_export" function (into one logged "row")
priority
log priority, default "7"
Example
<?php
.. .
$eClog->log(     "debug message", 7 );
.. .
$eClog->emerg(   "emergency message" );
$eClog->alert(   "alert message" );
$eClog->crit(    "critical message" );
$eClog->err(     "error message" );
$eClog->warning( "warning message" );
$eClog->notice(  "notice message" );
$eClog->info(    "informational message" );
$eClog->debug(   "debug message" );
.. .
?>
[index] [top] [up]

flush

Flushes the eClog handler(-s) message gueues.

Force a log (info) ending entry with

At PHP script or eClog object instance termination, a flush is forced!

Format, description
eClog::flush([ string $message [, int $priority ]])
Format, parameters
message
opt. log message
 
priority
if message set, log priority, default "7" (debug)
Example
<?php
.. .
$eClog->flush();
.. .
?>
[index] [top] [up]

addHandler

Offer the ability to use multiple handlers.

Force a log (notice) start informative entry in the handler message queue.

Format, description
eClog::addHandler([ string $type [, mixed $file [, string $ident [, array $config [, int $priority ]]]]])
Format, parameters
See Create object instance, above.
Example

Adding an errorlog handler with default configuration but priority LOG_ERR.

<?php
.. .
$eClog = new eClog( "file",     "log.log", "ident 1", FALSE, LOG_DEBUG );
$eClog->addHandler( "errorlog", "",        "ident 2", FALSE, LOG_ERR );
.. .
?>
[index] [top] [up]

Handlers

eClog supports the following handlers:
db - MySQL database (using PHP mysqli extension)
console - STDOUT/STDERR
errorlog - using the "php.ini" file "error_log" directive
file - logging to file
mail - using the built in PHP "mail" function
null
syslog - using the system error file

General configuration parameters

"logItemRowOrder" (alias "liro")
denotes order and placeholders for log items
  1. time
  2. ident
  3. priority (severity) text, from "pt", below
  4. message text
default "%1$s %2$s %3$s %4$s" (or opt. "1 2 3 4", will be expanded by eClog)
offer support for a simple xml output, example (eol formatted):
<logentry>
<time>%1$s</time>
<ident>%2$s</ident>
<priority>%3$s</priority>
<text>%4$s</text>
</logentry>
"timeFormat"
supports
PHP strftime formating
default "%Y-%m-%d %T"
PHP date formating
ex."Y-m-d H:i:s"
suffix ".u" offers microseconds fraction (ex. "H:i:s.u")
make always sure the right "date_default_timezone" is set
If using a date-less timeformat, a date (YYYY-MM-DD) are always displayed at first log entry (or after a day shift).
 
"pt"
priority (severity) log level to text array
default ( "EMERGENCY","ALERT","CRITICAL","ERROR","WARNING","NOTICE","INFO","DEBUG" )
 
"onErrorError_log"
log "failover"
log handler errors to errorlog (make sure the "error_log" directive is set in "php.ini")
default TRUE

db

The "db" handler gives the ability to log to a MySQL database, using PHP mysqli extension and a table (engine InnoDB, character set "utf8"), as defined in the attached "eClog.db.sql" script.

The eClog create argument "file" may be empty, when using the "db" handler.

Log data are split up in the following items (database table columns).

keyMySQL value typecomment
datedate
timetime
fractionmediumintmilliseconds
identitychar20 characters
prioritysmallint
messagetext216 characters

The following characters are escaped before storing into database identity and message columns: NUL (ASCII 0), \n, \r, \, ' (single quotation mark), " (quotation mark), Control-Z, %, and _.

The PHP and MySQL character sets SHOULD match, to avoid character conversion errors, preferably "utf8".

Configuration

There are two options for the configurations array, depending on how to manage the database connection.

eClog manages the database connection

This is to recommend, a database connection is created (and terminated) at every (non-empty) flush.

keyvalue typecommentdefault/mandatory/optional
"host"stringdatabase hostmandatory
"username"stringdatabase usernamemandatory
"passwd"stringdatabase passwdmandatory
"dbname"stringdatabase dbnamemandatory
"port"stringdatabase portoptional
"socket"stringdatabase socketoptional
"dbcharset"stringdatabase default client character setoptional
"usetransaction"booluse database transactions or notdefault TRUE
 
"onErrorError_log"boolif to log handler errors to errorlogdefault TRUE **
"exitOnError"boolif to exit script when errordefault FALSE ***

** ) If "TRUE", make sure the "error_log" directive is set in "php.ini".
*** ) always set to FALSE at termination (i.e. last flush).

Example
<?php
.. .
$dbconfig = array( "host"     => "localhost"
                  ,"username" => "eClog"
                  ,"passwd"   => "eClog"
                  ,"dbname"   => "eClog" );
$eClog    = eClog::singleton( "db", "", "dbtest", $dbconfig, LOG_DEBUG );
.. .
?>
eClog are supplied with a mysqli connection object instance
keyvalue typecommentdefault/mandatory/optional
"dbconn"objectmysqli database connection object instancemandatory
"usetransaction"booluse database transactions or notdefault TRUE
 
"onErrorError_log"boolif to log handler errors to errorlogdefault TRUE **
"exitOnError"boolif to exit script when errordefault FALSE ***

** ) If "TRUE", make sure the "error_log" directive is set in "php.ini".
*** ) always set to FALSE at termination (i.e. last flush).

Example
<?php
.. .
$localhost = "host";
$username  = "username";
$password  = "passwd";
$database  = "eClog";
$mysqli    = new mysqli( $localhost, $username, $password, $database );
          // (From PHP.net) This is the "official" OO way to do it,
          // BUT $connect_error was broken until PHP 5.2.9 and 5.3.0.
if(( substr( phpversion(), 0, 5 ) >= "5.2.9" ) && $mysqli->connect_error ) {
  echo "Connect Error (" . $mysqli->connect_errno . ") ". $mysqli->connect_error;
  exit();
}
          // (From PHP.net) Use this instead of $connect_error if you need
          // to ensure compatibility with PHP versions prior to 5.2.9 and 5.3.0.
elseif( mysqli_connect_error()) {
  echo "Connect Error (" . mysqli_connect_errno() . ") ". mysqli_connect_error();
  exit();
}
$dbconfig  = array( "dbconn" => $mysqli );
$eClog     = new eClog:( "db", "", "dbtest", $dbconfig, LOG_DEBUG );
.. .
?>
[index] [top] [up]

console

The "console" handler gives the ability to execute PHP (and capture logging) in console mode.

The only valid options when creating an eClog object instance for argument "file" (facility) are "STDOUT" and "STDERR".

Configuration

Options for the configurations array.

keyvalue typecommentdefault/optional
"logItemRowOrder"stringlog item row order
1 - date(-time)
2 - ident
3 - prioritytext
4 - msg text
default "1 2 3 4"
"liro"logItemRowOrder alias
"timeFormat"stringPHP strftime formatingdefault "%Y-%m-%d %T" *
"timeFormat"stringPHP date formating
suffix ".u"=msec fraction
opt., ex."Y-m-d H:i:s"
"pt"arraypriority to text tabledefault
"EMERGENCY","ALERT","CRITICAL","ERROR",
"WARNING","NOTICE","INFO","DEBUG"

* ) If using a date-less timeformat, a date (YYYY-MM-DD) are always displayed at first log entry (or after a day shift).

Example
<?php
.. .
$config = array( "timeFormat" => "H:i:s", "logItemRowOrder" => "3 2 1 4" );
$eClog  = new eClog( "console", "STDOUT", "test console", $config, 7 );
.. .
?>

[index] [top] [up]

errorlog

The "errorlog" handler gives the ability to log to error_log, defined in "php.ini" file and "error_log" directive.

The eClog create argument "file" may be empty, when using the "errorlog" handler.

Configuration

Options for the configurations array.

keyvalue typecommentdefault/opt
"logItemRowOrder"stringlog item row order
1 - date(-time)
2 - ident
3 - prioritytext
4 - msg text
default "1 2 3 4"
"liro"logItemRowOrder alias
"timeFormat"stringPHP strftime formatingdefault "%Y-%m-%d %T" *
"timeFormat"stringPHP date formating
suffix ".u"=msec fraction
opt., ex. "Y-m-d H:i:s"
"pt"arraypriority to text tabledefault
"EMERGENCY","ALERT","CRITICAL","ERROR",
"WARNING","NOTICE","INFO","DEBUG"
 
"strlen"intsplit msgs at (multibyte safe)default 1024

* ) If using a date-less timeformat, a date (YYYY-MM-DD) are always displayed at first log entry (or after a day shift).

Example
<?php
.. .
$config = array( "logItemRowOrder" => "3 2 4" );
$eClog  = new eClog( "errorlog", "", "test errorlog", $config, 7 );
.. .
?>
[index] [top] [up]

file

The "file" handler gives the ability to log to file.

When using the "file" handler, PHP must have write access to the (log) directory, set or implied in the eClog create argument "file".

Configuration

Options for the configurations array.

keyvalue typecommentdefault/optional
"logItemRowOrder"stringlog item row order
1 - date(-time)
2 - ident
3 - prioritytext
4 - msg text
default "1 2 3 4"
"liro"logItemRowOrder alias
"timeFormat"stringPHP strftime formatingdefault "%Y-%m-%d %T" *
"timeFormat"stringPHP date formating
suffix ".u"=msec fraction
opt., ex. "Y-m-d H:i:s"
"pt"arraypriority to text tabledefault
"EMERGENCY","ALERT","CRITICAL","ERROR",
"WARNING","NOTICE","INFO","DEBUG"
 
"onErrorError_log"boolif to log handler errors to errorlogdefault TRUE **
"exitOnError"boolif to exit script when errordefault FALSE ***

* ) If using a date-less timeformat, a date (YYYY-MM-DD) are always displayed at first log entry (or after a day shift).
** ) If "TRUE", make sure the "error_log" directive is set in "php.ini".
*** ) always set to FALSE at termination (i.e. last flush).

Example
<?php
.. .
$file   = "eClog".date("Ymd").".log"
$config = array( "timeFormat" => "H:i:s", "logItemRowOrder" => "1 3 2 4" );
$eClog  = eClog::singleton( "file", $file, "test File", $config, 7 );
.. .
?>
[index] [top] [up]

mail

The "mail" handler gives the ability to send log (as plain text) to a mail receiver, using the built in PHP "mail" function. eClog invokes the mail send function at every flush.

When using the "mail" handler, PHP must have access to the system sendmail binary or an appropriate sendmail wrapper.

The eClog create argument "file" may be empty, when using the "mail" handler.

Configuration

Options for the configurations array.

keyvalue typecommentdefault/mandatory/optional
"logItemRowOrder"stringlog item row order
1 - date(-time)
2 - ident
3 - prioritytext
4 - msg text
default "1 2 3 4"
"liro"logItemRowOrder alias
"timeFormat"stringPHP strftime formatingdefault "%Y-%m-%d %T" *
"timeFormat"stringPHP date formating
suffix ".u"=msec fraction
opt., ex. "Y-m-d H:i:s"
"pt"arraypriority to text tabledefault
"EMERGENCY","ALERT","CRITICAL","ERROR",
"WARNING","NOTICE","INFO","DEBUG"
 
"mailTo"stringmail receiver(-s)
(comma separated list)
mandatory ****
"mailfrom"stringmail senderdefault (first) "mailTo" address ****
"mailSubject"stringmail subjectdefault "Log report ".date( "Y-m-d H:i:s" ) *****
"strlen"intsplit msgs at (multibyte safe)default 70 *****
 
"onErrorError_log"boolif to log handler errors to errorlogdefault TRUE **
"exitOnError"boolif to exit script when errordefault FALSE ***

* ) If using a date-less timeformat, a date (YYYY-MM-DD) are always displayed at first log entry (or after a day shift).
** ) If "TRUE", make sure the "error_log" directive is set in "php.ini".
*** ) always set to FALSE at termination (i.e. last flush).
**** ) The formatting of the "mailTo"/"mailfrom" value(-s) must comply with RFC 2822.
***** ) Subject must satisfy RFC 2047.
***** ) Each line separated with a CRLF (\r\n).

There are, however, no assurance that the mail ever will reach the intended destination, even if the mail was accepted for delivery.

Example
<?php
.. .
$config = array( "timeFormat"  => "H:i:s"
               , "mailTo"      => "servicedesk@somehost.se";   // ,servicedeskmanager@somehost.se";
               , "mailFrom"    => "app1@somehost.se";
               , "mailSubject" => "report" );
$eClog  = eClog::singleton( "mail", "", "test mail", $config, 7 );
.. .
?>
[index] [top] [up]

null

The "null" handler consumes log messages but has no output.

Configuration

None.

[index] [top] [up]

syslog

The "syslog" handler gives the ability to log to the system error file.

Configuration

When using the "syslog" handler, please review "http://www.php.net/manual/en/function.syslog.php" for settings and configuration details.

Options for the configurations array.

keyvaluecommentdefault/opt
"logItemRowOrder"stringlog item row order
1 - date(-time)
2 - ident
3 - prioritytext
4 - msg text
default "1 2 3 4"
"liro"logItemRowOrder alias
"timeFormat"stringPHP strftime formatingdefault "%Y-%m-%d %T" *
"timeFormat"stringPHP date formating
suffix ".u"=msec fraction
opt "Y-m-d H:i:s"
"pt"arraypriority to text tabledefault
"EMERGENCY","ALERT","CRITICAL","ERROR",
"WARNING","NOTICE","INFO","DEBUG"
 
"strlen"intsplit msgs at (multibyte safe)default 500

* ) If using a date-less timeformat, a date (YYYY-MM-DD) are always displayed at first log entry (or after a day shift).

Example
<?php
.. .
$config = array( "logItemRowOrder" => "3 2 4" );
$eClog  = new eClog( "syslog", LOG_LOCAL7, "test syslog", $config, 7 );
.. .
?>
[index] [top] [up]

PHP error handler

The error handler function gives the ability to trigger PHP errors.

Include the attached "eClog.inc.php" in PHP script, opt. update first the eClog object instance variable name in the function.

Example
<?php
require_once "[path/]eClog.class.php";
require_once "[path/]eClog.inc.php";
$eClog = new eClog( "file", "log.log", "testidentity", FALSE, 7 );
.. .
?>
[index] [top]

eClog test

You can test handlers using the test script "eClog.test.php". In a few cases, a handler is split up into two testcases, otherwise one by one. For each testcase, you can select test scope: functional, performance, error_handler and a (utf8) character test. Also eClog object instance/singleton, message item row order, time format, test priority are selectable. When testing the db handler, tests with or without db transactions are possible.

For the MySQL database test, create a db user, a database and invoke the table create SQL script "eClog.db.sql" in a Mysql database managent tool.

Review and update (test general and handler specific) configuration settings in top of the script.

The test script creates and executes "eClog.ScriptFile.php" in CLI environment and opt. logs to "eClog.testFile.log" in local directory, write access to the local directory is required for web server user!

Open "eClog.test.php" (installed within a folder within the web server "Dokument root") in a browser to start testing.

The "eClog.ScriptFile.php" (downloadable after execution) and, apart from the "null" and "mail" test cases, results ("eClog.testFile.log" etc.) are displayed in the test form.

[index] [top]

Copyright and License

Copyright

eClog 3.0
copyright (c) 2009-2012 Kjell-Inge Gustafsson, kigkonsult
kigkonsult.se eClog
kigkonsult.se contact

License

This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version.

This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details.

You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA or download it here.


[index] [top] [up]