## Apache Zeta Components Manual :: Docs For Class ezcLog

### EventLog::ezcLog

### Class ezcLog

The ezcLog class records log messages and audit trails to one or multiple writers.

Available writers are:

- Unix File writer
- Database writer

Extra writers can be added by implementing the ezcLogWriter interface.

Use the getMapper() method to get an instance of the ezcLogMapper. The ezcLogMapper classes specifies incoming log messages with the ezcLogFilter. Log messages that are accepted, match with the filter, are sent to the ezcLogWriter.

The following example demonstrates how all log messages, except for the audit trailing and debug messages, are written to a file.

1. $filter=new ezcLogFilter ();
2. $filter->severity=ezcLog ::INFO|ezcLog ::NOTICE|ezcLog ::WARNING|ezcLog ::ERROR|ezcLog ::FATAL;
4. $log=ezcLog :: getInstance ();
5. $log-> getMapper ()->appendRule(new ezcLogFilterRule ($filter,new ezcLogUnixFileWriter ("/tmp/logs/","error.log"),true) );

The log messages with the severity: INFO, NOTICE, WARNING, ERROR, and FATAL will be written to the file: "/tmp/logs/error.log". See ezcLogUnixFileWriter for the description of the file format.

The following example will write the audit trails to the database:

1. $filter=new ezcLogFilter ();
2. $filter->severity=ezcLog ::SUCCESS_AUDIT|ezcLog ::FAILED_AUDIT;
4. $log=ezcLog :: getInstance ();
5. $log-> getMapper ()->appendRule(new ezcLogFilterRule ($filter,new ezcLogDatabaseWriter ("audits"),true) );

The audit trails will be stored in the table "audits". See ezcLogDatabaseWriter for creating the appropriate tables and setting up the database. See the ezcLogFilter for more details.

Use the log() method to log messages at the specified writers. This method expects a:

- Message, contains a single log message.
- Severity, indicates the level of importance.
- Extra attributes (optional).

Although the interpretation of the severity levels are up to the programmer, the most common interpretations are:

- DEBUG: Records information about the progress in the program and references source code functions. Knowledge of the source code is needed to interpret this log message.
- INFO: Informative logging at a detailed level. This logging method produces a high level of logging, which is unmanageable on a production environment. Usually INFO logging is only enabled to help by analysing a problem.
- NOTICE: Informative logging at a lower detail level than INFO logging. Only major stages are recorded and is useful to monitor a low volume system.
- WARNING: Something unexpected happened, but did not cause any loss of service.
- ERROR: An error occured, which may cause partial loss of service. Usually the system can recover.
- FATAL: An serious error occured and the system is unlikely to recover.
- SUCCESS_AUDIT: Informative logging about a successful completion of work by a module completed. Useful to trace system changes directly or indirectly done by a user.
- FAILED_AUDIT: Informative logging about an action from a module with a negative result. A failed login will most likely added to this severity.

The next example logs a fatal error and has no extra attributes:

1. ezcLog :: getInstance ()-> log ("Cannot open ini file: <$file>", ezcLog ::FATAL);

The log message will get by default the category and source: "default". The default values can be modified by changing, respectively, the properties $category and $source.

An example of a Payment checker is as follows:

1. // The start of the Payment module.
2. $log=ezcLog :: getInstance ();
3. $log->source="Payment checker";// Change the default source.
5. $log-> log ("Checking the received amount", ezcLog ::INFO,array("shop") );
7. if(!$eZPay->receivedAmount()!=$requiredAmount)
8. {
9. $log-> log ("Received amount: <".$eZPay->receivedAmount()."> expected: <$requiredAmount>.",
10. ezcLog ::DEBUG,
11. array("category"=>"shop","file"=> __FILE__,"line"=>__LINE)
12. );
14. $log-> log ("Insufficient amount.",
15. ezcLog ::FAILED_AUDIT,
16. array("UserName"=>getCurrentUser(),category=>"Payment")
17. )
19. $log-> log ("Rollback amount not implemented, cannot recover, ezcLog::FATAL );
20. exit();

Sometimes information repeats for specific severities or categories. For example that for the audit trails an username is required. Convenience methods like: setSeverityAttributes() and setSourceAttributes() exist to append information automatically to the log message.

The ezcLog class provides a http://www.php.net/trigger_error log handler: ezcLog::logHandler(). Using the trigger_error method makes your code less Log package dependent and produces less overhead when logging is disabled.

See the ezcLog::logHandler() method for more information about how to set up the trigger_error functionality.

See the ezcDebug package for more detailed information about writing DEBUG messages.

Source for this file: /EventLog/src/log.php

Version: | //autogentag//

### Constants

`DEBUG = 1` | Debug severity constant.
`ERROR = 64` | Error severity constant.
`FAILED_AUDIT = 4` | Failed audit severity constant.
`FATAL = 128` | Fatal severity constant.
`INFO = 8` | Info severity constant.
`NOTICE = 16` | Notice severity constant.
`SUCCESS_AUDIT = 2` | Success audit severity constant.
`WARNING = 32` | Warning severity constant.

### Properties

string | read/write | `$category` Definition of the message group. Again the category is related to the severity. The non audit trails can group the log messages like: Database (or even the database types), Templates, etc. For audit trails it makes much sense to categorize the actions. For example: security, modified content, published content, shop, etc.
string | read/write | `$source` Definition of the global location where the log message comes from. Some examples are: module, source file, extension, etc. The source depends also on the severity of the message. For DEBUG messages is the source file more important whereas for a FATAL error the module is sufficient.

### Member Variables

protected mixed | `$context` Stores the attributes from the eventTypes and eventSources. $var ezcLogContext
protected ezcLogFilterSet | `$writers` Contains the logic of mapping an incoming log message to the writer.

### Method Summary

public static ezcLog | `getInstance( )` Returns the instance of the class.
public static void | `logHandler( $errno , $errstr , $errfile , $errline )` This method can be set as error_handler to log using http://www.php.net/trigger_error.
public static string | `translateSeverityName( $severity )` Translates the severity constant to a string and returns this.
public ezcLogMapper | `getMapper( )` Returns an instance of the current ezcLogMapper.
public void | `log( $message , $severity , [ $attributes = array()] )` Write the message $message with additional information to one or multiple log writers.
public void | `reset( )` Resets the log instance to its initial state.
protected void | `setDefaults( )` Sets the source and category defaults to "default".
public void | `setMapper( $mapper )` Sets the given ezcLogMapper $mapper as the log message to writer map.
public void | `setSeverityAttributes( $severityMask , $attributes )` Sets the attributes $attributes for a group of severities $severityMask.
public void | `setSourceAttributes( $sources , $attributes )` Sets the attributes $attributes for a group of sources $sources.
public void | `throwWriterExceptions( $enable )` Enables or disables writer exceptions with the boolean $enable.

### Methods

#### getInstance

static ezcLog getInstance( )

Returns the instance of the class.

#### logHandler

static void logHandler( int $errno , int $errstr , string $errfile , int $errline )

This method can be set as error_handler to log using http://www.php.net/trigger_error.

This method can be assigned with the http://www.php.net/set_error_handler to handle the trigger_error calls. This method will get the log instance and forward the message. But includes the following information:

- The file and linenumber are automatically added.
- Source and category can be 'encoded' in the message.

The message format is as follows:

     [ source, category ] Message

When one name is given between the brackets, the category will be set and the message has a default source:

     [ category ] Message

Without any names between the brackets, the default category and source are used:

     Message

The following example creates manually an error handler and forwards the ERROR, WARNING and NOTICE severities.

1. functionmyLogHandler($errno,$errstr,$errfile,$errline)
2. {
3. switch($errno)
4. {
5. caseE_USER_ERROR:
6. caseE_USER_WARNING:
7. caseE_USER_NOTICE:
8. if($loggingEnabled)
9. {// Forward the message to the log handler.
10. ezcLog ::LogHandler($errno,$errstr,$errfile,$errline);
11. }
12. break;
14. default:
15. print("$errstrin$errfileon line$errline\n");
16. break;
17. }
18. }
20. // Register myLogHandler
21. set_error_handler ("myLogHandler");
23. // Write an warning to the log.
24. trigger_error ("[paynet, transaction] Didn't get a callback from the Paynet service",E_USER_WARNING);
26. // Add a notice.
27. trigger_error ("Getting paynet status information",E_USER_NOTICE);

Notice that the ezcLog component is not loaded at all when the logging is disabled.

##### Parameters:

Name | Type | Description
--- | --- | ---
`$errno` | int |
`$errstr` | int |
`$errfile` | string |
`$errline` | int |

#### translateSeverityName

static string translateSeverityName( int $severity )

Translates the severity constant to a string and returns this.

Null is returned when the severity constant is invalid.

##### Parameters:

Name | Type | Description
--- | --- | ---
`$severity` | int |

#### getMapper

ezcLogMapper getMapper( )

Returns an instance of the current ezcLogMapper.

#### log

void log( string $message , int $severity , [ $attributes = array()] )

Write the message $message with additional information to one or multiple log writers.

The log message $message, severity $severity, and extra attributes $attributes are sent to the writers that matches with the ezcLogFilter. The following parameters are taken in the comparation with the ezcLogFilter:

- $severity: the severity of the log message.
- $attributes[ "source" ]: the source from where the log message comes.
- $attributes[ "category" ]: the category of the log message.

See for more information about filter matching the classes ezcLog and ezcLogFilter.

The message $message describes what happened. The severity $severity is one of the ezcLog constants:

- DEBUG: Records information about the progress in the program and references source code functions. Knowledge of the source code is needed to interpret this log message.
- INFO: Informative logging at a detailed level. This logging method produces a high level of logging, which is unmanageable on a production environment. Usually INFO logging is only enabled to help by analysing a problem.
- NOTICE: Informative logging at a lower detail level than INFO logging. Only major stages are recorded and is useful to monitor a low volume system.
- WARNING: Something unexpected happened, but did not cause any loss of service.
- ERROR: An error occured, which may cause partial loss of service. Usually the system can recover.
- FATAL: An serious error occured and the system is unlikely to recover.
- SUCCESS_AUDIT: Informative logging about a successful completion of work by a module completed. Useful to trace system changes directly or indirectly done by a user.
- FAILED_AUDIT: Informative logging about an action from a module with a negative result. A failed login will most likely added to this severity.

The attributes array $attributes can have one or multiple attributes that will be added to the log. If source and category are given, they will override the default source or category given as property to this object. Further more it is up to the application what to include in the log. It may be useful to add the file and linenumber to the attributes array. Use the magic PHP constants: __FILE__ and __LINE__ for this purpose. The next example adds an warning to the log.

1. ezcLog :: getInstance ()->source="templateEngine";// Set the default source.
2. ezcLog :: getInstance ()-> log ("ezcPersistentObject <$obj> does not exist.",
3. ezcLog ::WARNING,
4. array("category"=>"Database","line"=> __LINE__,"file"=> __FILE__,"code"=>123)
5. );

The methods setSeverityAttributes() and setSourceAttributes() can automatically add attributes to log messages based on, respectively, the severity and source.

See also logHandler() on how to use http://www.php.net/trigger_error to write log messages.

##### Parameters:

Name | Type | Description
--- | --- | ---
`$message` | string |
`$severity` | int | One of the following severity constants: DEBUG, SUCCES_AUDIT, FAIL_AUDIT, INFO, NOTICE, WARNING, ERROR, or FATAL.
`$attributes` | array(string=>string) |

##### Exceptions:

Type | Description
--- | ---
`ezcLogWriterException` | if throwWriterExceptions are enabled and a log entry could not be written.

#### reset

void reset( )

Resets the log instance to its initial state.

All sourceAttributes, severityAttributes, and writers will be removed. The default source and category are also reset.

#### setDefaults

void setDefaults( )

Sets the source and category defaults to "default".

#### setMapper

void setMapper( ezcLogMapper $mapper )

Sets the given ezcLogMapper $mapper as the log message to writer map.

By default the ezcLogFilterSet is the default writer map. The default ezcLogMapper can be replaced with this method.

##### Parameters:

Name | Type | Description
--- | --- | ---
`$mapper` | ezcLogMapper |

#### setSeverityAttributes

void setSeverityAttributes( integer $severityMask , array(string=>string) $attributes )

Sets the attributes $attributes for a group of severities $severityMask.

The severities are specified with a bit mask. These attributes will be added to the log message when the log severity is the same as specified here.

Example:

1. ezcLog :: getInstance ()-> setSeverityAttributes (
2. ezcLog ::SUCCESS_AUDIT|ezcLog ::FAILED_AUDIT
3. array("username"=>"Jan K. Doodle")
4. );

Every log message that has the severity SUCCESS_AUDIT or FAILED_AUDIT includes the user name: "Jan K. Doodle".

##### Parameters:

Name | Type | Description
--- | --- | ---
`$severityMask` | integer | Multiple severities are specified with a logic-or.
`$attributes` | array(string=>string) |

#### setSourceAttributes

void setSourceAttributes( array(string) $sources , array(string=>string) $attributes )

Sets the attributes $attributes for a group of sources $sources.

The sources are specified in an array. These attributes will be added to the log message when it matches with the given $sources.

Example:

1. ezcLog :: getInstance ()-> setSourceAttributes (
2. array("Paynet","Bibit","Paypal"),
3. array("MerchantID"=>$merchantID)
4. );

Every log message that comes from the payment module: Paynet, Bibit, or Paypal includes the Merchant ID.

##### Parameters:

Name | Type | Description
--- | --- | ---
`$sources` | array(string) |
`$attributes` | array(string=>string) |

#### throwWriterExceptions

void throwWriterExceptions( bool $enable )

Enables or disables writer exceptions with the boolean $enable.

Typically you want to have exceptions enabled while developing your application in order to catch potential problems. A live server however, should not throw a deadly exception when a relatively unimportant debug message could not be written to the log file. For these setups you can disable writer exceptions.

##### Parameters:

Name | Type | Description
--- | --- | ---
`$enable` | bool |

Documentation generated by phpDocumentor 1.4.3