libc syslog

来源:互联网 发布:win7照相机软件下载 编辑:程序博客网 时间:2024/06/05 09:21

18 Syslog

This chapter describes facilities for issuing and logging messages ofsystem administration interest. This chapter has nothing to do withprograms issuing messages to their own users or keeping private logs(One would typically do that with the facilities described inI/O on Streams).

Most systems have a facility called “Syslog” that allows programs tosubmit messages of interest to system administrators and can beconfigured to pass these messages on in various ways, such as printingon the console, mailing to a particular person, or recording in a logfile for future reference.

A program uses the facilities in this chapter to submit such messages.


18.1 Overview of Syslog

System administrators have to deal with lots of different kinds ofmessages from a plethora of subsystems within each system, and usuallylots of systems as well. For example, an FTP server might report everyconnection it gets. The kernel might report hardware failures on a diskdrive. A DNS server might report usage statistics at regular intervals.

Some of these messages need to be brought to a system administrator'sattention immediately. And it may not be just any system administrator– there may be a particular system administrator who deals with aparticular kind of message. Other messages just need to be recorded forfuture reference if there is a problem. Still others may need to haveinformation extracted from them by an automated process that generatesmonthly reports.

To deal with these messages, most Unix systems have a facility called"Syslog." It is generally based on a daemon called “Syslogd”Syslogd listens for messages on a Unix domain socket named/dev/log. Based on classification information in the messagesand its configuration file (usually /etc/syslog.conf), Syslogdroutes them in various ways. Some of the popular routings are:

  • Write to the system console
  • Mail to a specific user
  • Write to a log file
  • Pass to another daemon
  • Discard

Syslogd can also handle messages from other systems. It listens on thesyslog UDP port as well as the local socket for messages.

Syslog can handle messages from the kernel itself. But the kerneldoesn't write to/dev/log; rather, another daemon (sometimescalled “Klogd”) extracts messages from the kernel and passes them on toSyslog as any other process would (and it properly identifies them asmessages from the kernel).

Syslog can even handle messages that the kernel issued before Syslogd orKlogd was running. A Linux kernel, for example, stores startup messagesin a kernel message ring and they are normally still there when Klogdlater starts up. Assuming Syslogd is running by the time Klogd starts,Klogd then passes everything in the message ring to it.

In order to classify messages for disposition, Syslog requires any processthat submits a message to it to provide two pieces of classificationinformation with it:

facility
This identifies who submitted the message. There are a small number offacilities defined. The kernel, the mail subsystem, and an FTP serverare examples of recognized facilities. For the complete list,Seesyslog; vsyslog. Keep in mind that these areessentially arbitrary classifications. "Mail subsystem" doesn't have anymore meaning than the system administrator gives to it.
priority
This tells how important the content of the message is. Examples ofdefined priority values are: debug, informational, warning, critical. For the complete list, seesyslog; vsyslog. Except forthe fact that the priorities have a defined order, the meaning of eachof these priorities is entirely determined by the system administrator.

A “facility/priority” is a number that indicates both the facilityand the priority.

Warning: This terminology is not universal. Some people use“level” to refer to the priority and “priority” to refer to thecombination of facility and priority. A Linux kernel has a concept of amessage “level,” which corresponds both to a Syslog priority and to aSyslog facility/priority (It can be both because the facility code forthe kernel is zero, and that makes priority and facility/priority thesame value).

The GNU C library provides functions to submit messages to Syslog. Theydo it by writing to the/dev/log socket. See Submitting Syslog Messages.

The GNU C library functions only work to submit messages to the Syslogfacility on the same system. To submit a message to the Syslog facilityon another system, use the socket I/O functions to write a UDP datagramto thesyslog UDP port on that system. See Sockets.

18.2 Submitting Syslog Messages

The GNU C library provides functions to submit messages to the Syslogfacility:

These functions only work to submit messages to the Syslog facility onthe same system. To submit a message to the Syslog facility on anothersystem, use the socket I/O functions to write a UDP datagram to thesyslog UDP port on that system. SeeSockets.


18.2.1 openlog

The symbols referred to in this section are declared in the filesyslog.h.

— Function: void openlog (const char *ident, int option, int facility)

openlog opens or reopens a connection to Syslog in preparationfor submitting messages.

ident is an arbitrary identification string which futuresyslog invocations will prefix to each message. This is intendedto identify the source of the message, and people conventionally set itto the name of the program that will submit the messages.

If ident is NULL, or if openlog is not called, the defaultidentification string used in Syslog messages will be the program name,taken from argv[0].

Please note that the string pointer ident will be retainedinternally by the Syslog routines. You must not free the memory thatident points to. It is also dangerous to pass a reference to anautomatic variable since leaving the scope would mean ending thelifetime of the variable. If you want to change the ident string,you must callopenlog again; overwriting the string pointed to byident is not thread-safe.

You can cause the Syslog routines to drop the reference to ident andgo back to the default string (the program name taken from argv[0]), bycallingcloselog: See closelog.

In particular, if you are writing code for a shared library that might getloaded and then unloaded (e.g. a PAM module), and you useopenlog,you must call closelog before any point where your library mightget unloaded, as in this example:

          #include <syslog.h>                    void          shared_library_function (void)          {            openlog ("mylibrary", option, priority);                      syslog (LOG_INFO, "shared library has been invoked");                      closelog ();          }

Without the call to closelog, future invocations of syslogby the program using the shared library may crash, if the library getsunloaded and the memory containing the string"mylibrary" becomesunmapped. This is a limitation of the BSD syslog interface.

openlog may or may not open the /dev/log socket, dependingonoption. If it does, it tries to open it and connect it as astream socket. If that doesn't work, it tries to open it and connect itas a datagram socket. The socket has the “Close on Exec” attribute,so the kernel will close it if the process performs an exec.

You don't have to use openlog. If you call syslog withouthaving calledopenlog, syslog just opens the connectionimplicitly and uses defaults for the information inident andoptions.

options is a bit string, with the bits as defined by the followingsingle bit masks:

LOG_PERROR
If on, openlog sets up the connection so that any syslogon this connection writes its message to the calling process' StandardError stream in addition to submitting it to Syslog. If off,syslogdoes not write the message to Standard Error.
LOG_CONS
If on, openlog sets up the connection so that a syslog onthis connection that fails to submit a message to Syslog writes themessage instead to system console. If off,syslog does not writeto the system console (but of course Syslog may write messages itreceives to the console).
LOG_PID
When on, openlog sets up the connection so that a syslogon this connection inserts the calling process' Process ID (PID) intothe message. When off,openlog does not insert the PID.
LOG_NDELAY
When on, openlog opens and connects the /dev/log socket. When off, a futuresyslog call must open and connect the socket.

Portability note: In early systems, the sense of this bit wasexactly the opposite.

LOG_ODELAY
This bit does nothing. It exists for backward compatibility.

If any other bit in options is on, the result is undefined.

facility is the default facility code for this connection. Asyslog on this connection that specifies default facility causesthis facility to be associated with the message. Seesyslog forpossible values. A value of zero means the default default, which isLOG_USER.

If a Syslog connection is already open when you call openlog,openlog “reopens” the connection. Reopening is like openingexcept that if you specify zero for the default facility code, thedefault facility code simply remains unchanged and if you specifyLOG_NDELAY and the socket is already open and connected, openlogjust leaves it that way. 

18.2.2 syslog, vsyslog

The symbols referred to in this section are declared in the filesyslog.h.

— Function: void syslog (int facility_priority, char *format, ...)

syslog submits a message to the Syslog facility. It does this bywriting to the Unix domain socket/dev/log.

syslog submits the message with the facility and priority indicatedbyfacility_priority. The macro LOG_MAKEPRI generates afacility/priority from a facility and a priority, as in the followingexample:

          LOG_MAKEPRI(LOG_USER, LOG_WARNING)

The possible values for the facility code are (macros):

LOG_USER
A miscellaneous user process
LOG_MAIL
Mail
LOG_DAEMON
A miscellaneous system daemon
LOG_AUTH
Security (authorization)
LOG_SYSLOG
Syslog
LOG_LPR
Central printer
LOG_NEWS
Network news (e.g. Usenet)
LOG_UUCP
UUCP
LOG_CRON
Cron and At
LOG_AUTHPRIV
Private security (authorization)
LOG_FTP
Ftp server
LOG_LOCAL0
Locally defined
LOG_LOCAL1
Locally defined
LOG_LOCAL2
Locally defined
LOG_LOCAL3
Locally defined
LOG_LOCAL4
Locally defined
LOG_LOCAL5
Locally defined
LOG_LOCAL6
Locally defined
LOG_LOCAL7
Locally defined

Results are undefined if the facility code is anything else.

NB: syslog recognizes one other facility code: that ofthe kernel. But you can't specify that facility code with thesefunctions. If you try, it looks the same tosyslog as if you arerequesting the default facility. But you wouldn't want to anyway,because any program that uses the GNU C library is not the kernel.

You can use just a priority code as facility_priority. In thatcase,syslog assumes the default facility established when theSyslog connection was opened. SeeSyslog Example.

The possible values for the priority code are (macros):

LOG_EMERG
The message says the system is unusable.
LOG_ALERT
Action on the message must be taken immediately.
LOG_CRIT
The message states a critical condition.
LOG_ERR
The message describes an error.
LOG_WARNING
The message is a warning.
LOG_NOTICE
The message describes a normal but important event.
LOG_INFO
The message is purely informational.
LOG_DEBUG
The message is only for debugging purposes.

Results are undefined if the priority code is anything else.

If the process does not presently have a Syslog connection open (i.e.,it did not callopenlog), syslog implicitly opens theconnection the same asopenlog would, with the following defaultsfor information that would otherwise be included in anopenlogcall: The default identification string is the program name. Thedefault default facility isLOG_USER. The default for all theconnection options in options is as if those bits were off.syslog leaves the Syslog connection open.

If the dev/log socket is not open and connected,syslogopens and connects it, the same as openlog with theLOG_NDELAY option would.

syslog leaves /dev/log open and connected unless its attemptto send the message failed, in which casesyslog closes it (with thehope that a future implicit open will restore the Syslog connection to ausable state).

Example:

                    #include <syslog.h>          syslog (LOG_MAKEPRI(LOG_LOCAL1, LOG_ERROR),                  "Unable to make network connection to %s.  Error=%m", host);          
— Function: void vsyslog (int facility_priority, char *format, va_list arglist)

This is functionally identical to syslog, with the BSD style variablelength argument.


18.2.3 closelog

The symbols referred to in this section are declared in the filesyslog.h.

— Function: void closelog (void)

closelog closes the current Syslog connection, if there is one. This includes closing thedev/log socket, if it is open. closelog also sets the identification string for Syslog messagesback to the default, ifopenlog was called with a non-NULL argumentto ident. The default identification string is the program nametaken from argv[0].

If you are writing shared library code that uses openlog togenerate custom syslog output, you should usecloselog to drop theGNU C library's internal reference to the ident pointer when you aredone. Please read the section onopenlog for more information:See openlog.

closelog does not flush any buffers. You do not have to callcloselog before re-opening a Syslog connection withinitlog. Syslog connections are automatically closed on exec or exit.

18.2.4 setlogmask

The symbols referred to in this section are declared in the filesyslog.h.

— Function: int setlogmask (int mask)

setlogmask sets a mask (the “logmask”) that determines whichfuturesyslog calls shall be ignored. If a program has notcalled setlogmask,syslog doesn't ignore any calls. Youcan use setlogmask to specify that messages of particularpriorities shall be ignored in the future.

A setlogmask call overrides any previous setlogmask call.

Note that the logmask exists entirely independently of opening andclosing of Syslog connections.

Setting the logmask has a similar effect to, but is not the same as,configuring Syslog. The Syslog configuration may cause Syslog todiscard certain messages it receives, but the logmask causes certainmessages never to get submitted to Syslog in the first place.

mask is a bit string with one bit corresponding to each of thepossible message priorities. If the bit is on,syslog handlesmessages of that priority normally. If it is off, syslogdiscards messages of that priority. Use the message priority macrosdescribed insyslog; vsyslog and the LOG_MASK to constructan appropriate mask value, as in this example:

          LOG_MASK(LOG_EMERG) | LOG_MASK(LOG_ERROR)

or

          ~(LOG_MASK(LOG_INFO))

There is also a LOG_UPTO macro, which generates a mask with the bitson for a certain priority and all priorities above it:

          LOG_UPTO(LOG_ERROR)

The unfortunate naming of the macro is due to the fact that internally,higher numbers are used for lower message priorities.

18.2.5 Syslog Example

Here is an example of openlog, syslog, and closelog:

This example sets the logmask so that debug and informational messagesget discarded without ever reaching Syslog. So the secondsyslogin the example does nothing.

     #include <syslog.h>          setlogmask (LOG_UPTO (LOG_NOTICE));          openlog ("exampleprog", LOG_CONS | LOG_PID | LOG_NDELAY, LOG_LOCAL1);          syslog (LOG_NOTICE, "Program started by User %d", getuid ());     syslog (LOG_INFO, "A tree falls in a forest");          closelog ();     



原创粉丝点击