~~NOTOC~~ ====== Syslog simple example ====== There are many reasons why you should use syslog to log debugging information when your unix program is running. This is an example that explains how to use syslog to log events in a dedicated log file. ===== What is syslog ===== see [[wp>syslog|wikipedia syslog entry]] and //man syslogd// ===== Preparing a syslog facility for our program ===== Syslog has 8 configurable 'facilities' (or logfiles) that are available for the programmer to use. These facilities are referred to as LOG_LOCALx where x is an integer from 0 to 7. Preparing a syslog facility means picking a facility (e.g. LOG_LOCAL0) and associating it with a log file (or logging action). This can be done by editing the file **/etc/syslog.conf** and adding a line like this : local0.* /var/log/mylog This tells syslog that any logs written to the facility //LOG_LOCAL0//, should go to the file '/var/log/mylog'.\\ After updating /etc/syslog.conf, restart the syslogd daemon /etc/init.d/syslog restart ===== Writing to the syslog facility ===== Now that we configured the //LOG_LOCAL0// facility. We can write debugging information to our log file through syslog. This is a program that does just that. #include int main() { openlog ("MyProgram", LOG_CONS | LOG_PID | LOG_NDELAY, LOG_LOCAL0); syslog (LOG_INFO, "Program started by User %d", getuid ()); syslog (LOG_ERR, "Ouch an ERROR!"); closelog (); } The //openlog// function initiates syslog for our program. We just need to use once during the initiation of our program. Several options can be used to control the logging behavior, below is the explanation of the options used in the example above. ^Option ^ Meaning^ |LOG_CONS | When syslog fails to submit a message, it writes the message to system console| |LOG_PID | Inserts the calling process' Process ID (PID) into the message| |LOG_NODELAY | Open and connect to syslog| |LOG_LOCAL0 | Where to write the logs| The //syslog// call writes messages to our syslog facility //LOG_LOCAL0//. The first argument (LOG_INFO, LOG_ERR) specifies the log level or priority. This allows more fine tuning for example by specifying different logging files (or actions) for each logging level. See //man -S3 syslog// for the full list of debugging levels. If you compile and run the example program, you should have the following logs in the file /var/log/mylog Nov 21 17:27:53 HANNIBAL MyProgram[13163]: Program started by User 1000 Nov 21 17:27:53 HANNIBAL MyProgram[13163]: Ouch an ERROR! The format of the log messages is DATE TIME MACHINE-NAME PROGRAM-NAME[PID]: MESSAGE {{tag>coding howto unix}}