HomePHP Page 5 - Error and Exception Handling in PHP
Initializing PHP’s Logging Facility - PHP
Mistakes are inevitable, in life, programming, and application submissions. You can prepare for errors by making sure your application is designed to respond to them. This two-part article explains how PHP handles errors. It is excerpted from chapter 8 of the book Beginning PHP and Oracle: From Novice to Professional, written by W. Jason Gilmore and Bob Bryla (Apress; ISBN: 1590597702).
Thedefine_syslog_variables()function initializes the constants necessary for using theopenlog(),closelog(), andsyslog()functions. Its prototype follows:
You need to execute this function before using any of the following logging functions.
Opening the Logging Connection
Theopenlog()function opens a connection to the platform’s system logger and sets the stage for the insertion of one or more messages into the system log by designating several parameters that will be used within the log context. Its prototype follows:
int openlog(string ident, int option, int facility)
Several parameters are supported, including the following:
ident: Identifies messages. It is added to the beginning of each entry. Typically this value is set to the name of the program. Therefore, you might want to identify PHP-related messages such as “PHP” or “PHP5.”
option: Determines which logging options are used when generating the message. A list of available options is offered in Table 8-2. If more than one option is required, separate each option with a vertical bar. For example, you could specify three of the options like so: LOG_ODELAY | LOG_PERROR| LOG_PID.
facility: Helps determine what category of program is logging the message. There are several categories, includingLOG_KERN,LOG_USER,LOG_MAIL,LOG_DAEMON,LOG_AUTH,LOG_LPR, andLOG_LOCALN,whereN is a value ranging between 0 and 7. Note that the designated facility determines the message destination. For example, designatingLOG_CRONresults in the submission of subsequent messages to thecronlog, whereas designatingLOG_USERresults in the transmission of messages to themessagesfile. Unless PHP is being used as a command-line interpreter, you’ll likely want to set this toLOG_USER. It’s common to useLOG_CRONwhen executing PHP scripts from acrontab.See the syslog documentation for more information about this matter.
Table 8-2. Logging Options
If an error occurs when writing to the syslog, send output to the system console.
Immediately open the connection to the syslog.
Do not open the connection until the first message has been submitted for logging. This is the default.
Output the logged message to both the syslog and standard error.
Accompany each message with the process ID (PID).
Closing the Logging Connection
Thecloselog()function closes the connection opened byopenlog(). Its prototype follows: