First, open syslog.conf (normally at /etc/syslog.conf) and see which local log facility is available. A log ‘facility’ is a mechanism syslog provides to specify what type of program is logging a message. Local log facilities are for user defined programs. Here’s what the relevant portion of my syslog.conf file looks like:
Note the lines that start with localN.*. I’ve opted to use local2 to log my messages to /var/log/myapp.log. syslog allows you to select the type of message to log per facility, for example, local2.info instead of all message types like local2.*, but simply logging all message types to local2 using local2.* was the easiest way to go for me.
Add a localN.* line like my local2.* line to the syslog.conf file and then save and quit. Restart the syslog daemon to make the changes take effect. I ended up rebooting my macbook. Under linux, you can just use /etc/init.d/syslog restart.
Create the file you told syslog to write to if it doesn’t already exist:
Now, in your PHP script, use openlog() to open a connection to syslog:
openlog("myapp", LOG_NDELAY, LOG_LOCAL2);
openlog() takes three parameters, an ‘ident’, or message title, that is added to each message, logging options (LOG_NDELAY means open the connection to the logger immediately) and the logging facility you want to use in the form of LOG_LOCALN where N represents 0-7. For this example, I’m using LOG_LOCAL2.
Next, use syslog() to write a message to your log file:
syslog(LOG_ERR, "Testing php and syslog");
The first argument to syslog() is a predefined PHP constant that indicates the priority of the message. The second argument is the message you want to log.
Lastly, call closelog() when you’re done to close the connection to syslog.
Here’s an example of what a message will look like in your log file:
Jul 16 02:05:59 Troys-MacBook-Pro myapp: Testing php and syslog
I’ve listed the three commands I used in my PHP script below in case you want to copy them:
openlog("myapp", LOG_NDELAY, LOG_LOCAL2); syslog(LOG_ERR, "Testing php and syslog"); closelog();