1 # -*- test-case-name: twisted.python.test.test_syslog -*-
2 # Copyright (c) Twisted Matrix Laboratories.
3 # See LICENSE for details.
6 Classes and utility functions for integrating Twisted and syslog.
8 You probably want to call L{startLogging}.
11 syslog = __import__('syslog')
13 from twisted.python import log
15 # These defaults come from the Python 2.3 syslog docs.
17 DEFAULT_FACILITY = syslog.LOG_USER
23 A log observer for logging to syslog.
25 See L{twisted.python.log} for context.
27 This logObserver will automatically use LOG_ALERT priority for logged
28 failures (such as from C{log.err()}), but you can use any priority and
29 facility by setting the 'C{syslogPriority}' and 'C{syslogFacility}' keys in
32 openlog = syslog.openlog
33 syslog = syslog.syslog
35 def __init__(self, prefix, options=DEFAULT_OPTIONS,
36 facility=DEFAULT_FACILITY):
39 @param prefix: The syslog prefix to use.
42 @param options: A bitvector represented as an integer of the syslog
45 @type facility: C{int}
46 @param facility: An indication to the syslog daemon of what sort of
47 program this is (essentially, an additional arbitrary metadata
48 classification for messages sent to syslog by this observer).
50 self.openlog(prefix, options, facility)
53 def emit(self, eventDict):
55 Send a message event to the I{syslog}.
57 @param eventDict: The event to send. If it has no C{'message'} key, it
58 will be ignored. Otherwise, if it has C{'syslogPriority'} and/or
59 C{'syslogFacility'} keys, these will be used as the syslog priority
60 and facility. If it has no C{'syslogPriority'} key but a true
61 value for the C{'isError'} key, the B{LOG_ALERT} priority will be
62 used; if it has a false value for C{'isError'}, B{LOG_INFO} will be
63 used. If the C{'message'} key is multiline, each line will be sent
64 to the syslog separately.
66 # Figure out what the message-text is.
67 text = log.textFromEventDict(eventDict)
71 # Figure out what syslog parameters we might need to use.
72 priority = syslog.LOG_INFO
74 if eventDict['isError']:
75 priority = syslog.LOG_ALERT
76 if 'syslogPriority' in eventDict:
77 priority = int(eventDict['syslogPriority'])
78 if 'syslogFacility' in eventDict:
79 facility = int(eventDict['syslogFacility'])
81 # Break the message up into lines and send them.
82 lines = text.split('\n')
83 while lines[-1:] == ['']:
92 self.syslog(priority | facility,
93 '[%s] %s' % (eventDict['system'], line))
97 def startLogging(prefix='Twisted', options=DEFAULT_OPTIONS,
98 facility=DEFAULT_FACILITY, setStdout=1):
100 Send all Twisted logging output to syslog from now on.
102 The prefix, options and facility arguments are passed to
103 C{syslog.openlog()}, see the Python syslog documentation for details. For
104 other parameters, see L{twisted.python.log.startLoggingWithObserver}.
106 obs = SyslogObserver(prefix, options, facility)
107 log.startLoggingWithObserver(obs.emit, setStdout=setStdout)