Package logilab-common-0 ::
Package 39 ::
Package 0 ::
Module logger
|
|
1 """Define a logger interface and two concrete loggers: one which prints
2 everything on stdout, the other using syslog.
3
4 :copyright: 2000-2008 LOGILAB S.A. (Paris, FRANCE), all rights reserved.
5 :contact: http://www.logilab.fr/ -- mailto:contact@logilab.fr
6 :license: General Public License version 2 - http://www.gnu.org/licenses
7
8 # FIXME use logging from stdlib instead.
9 """
10 __docformat__ = "restructuredtext en"
11
12 from warnings import warn
13 warn('logilab.common.logger module is deprecated and will disappear in a future release. \
14 use logging module instead.',
15 DeprecationWarning, stacklevel=2)
16
17 import sys
18 import traceback
19 import time
20
21
22 LOG_EMERG = 0
23 LOG_ALERT = 1
24 LOG_CRIT = 2
25 LOG_ERR = 3
26 LOG_WARN = 4
27 LOG_NOTICE = 5
28 LOG_INFO = 6
29 LOG_DEBUG = 7
30
31 INDICATORS = ['emergency', 'alert', 'critical', 'error',
32 'warning', 'notice', 'info', 'debug']
33
34
36 """return a logger for the given method
37
38 known methods are 'print', 'eprint' and syslog'
39 """
40 if method == 'print':
41 if output is None:
42 output = sys.stdout
43 return PrintLogger(threshold, output, sid=sid)
44 elif method == 'eprint':
45 return PrintLogger(threshold, sys.stderr, sid=sid)
46 elif method == 'syslog':
47 return SysLogger(threshold, sid)
48 elif method == 'file':
49 if not output:
50 raise ValueError('No logfile specified')
51 else:
52 logfile = open(output, 'a')
53 return PrintLogger(threshold, logfile, sid=sid)
54 else:
55 raise ValueError('Unknown logger method: %r' % method)
56
57
59 """logger interface.
60 Priorities allow to filter on the importance of events
61 An event gets logged if it's priority is lower than the threshold"""
62
64 self.threshold = threshold
65 self.priority_indicator = priority_indicator
66
68 """log a message with priority <priority>
69 substs are optional substrings
70 """
71
72 if priority <= self.threshold :
73 if substs is not None:
74 message = message % substs
75 if self.priority_indicator:
76 message = '[%s] %s' % (INDICATORS[priority], message)
77 self._writelog(priority, message)
78
80 """Override this method in concrete class """
81 raise NotImplementedError()
82
84 """log traceback information with priority <priority>
85 """
86 assert tb_info is not None
87 e_type, value, tbck = tb_info
88 stacktb = traceback.extract_tb(tbck)
89 l = ['Traceback (most recent call last):']
90 for stackentry in stacktb :
91 if stackentry[3]:
92 plus = '\n %s' % stackentry[3]
93 else:
94 plus = ''
95 l.append('filename="%s" line_number="%s" function_name="%s"%s' %
96 (stackentry[0], stackentry[1], stackentry[2], plus))
97 try:
98 l.append(str(e_type) + ': ' + value.__str__())
99 except UnicodeError:
100 l.append(str(e_type) + ' (message can\'t be displayed)')
101
102 self.log(priority, '\n'.join(l))
103
104
106 """logger implementation
107
108 log everything to a file, using the standard output by default
109 """
110
111 - def __init__(self, threshold, output=sys.stdout, sid=None,
112 encoding='UTF-8'):
113 AbstractLogger.__init__(self, threshold)
114 self.output = output
115 self.sid = sid
116 self.encoding = encoding
117
119 """overridden from AbstractLogger"""
120 if isinstance(message, unicode):
121 message = message.encode(self.encoding, 'replace')
122 if self.sid is not None:
123 self.output.write('[%s] [%s] %s\n' % (time.asctime(), self.sid,
124 message))
125 else:
126 self.output.write('[%s] %s\n' % (time.asctime(), message))
127 self.output.flush()
128
130 """ logger implementation
131
132 log everything to syslog daemon
133 use the LOCAL_7 facility
134 """
135
136 - def __init__(self, threshold, sid=None, encoding='UTF-8'):
137 import syslog
138 AbstractLogger.__init__(self, threshold)
139 if sid is None:
140 sid = 'syslog'
141 self.encoding = encoding
142 syslog.openlog(sid, syslog.LOG_PID)
143
145 """overridden from AbstractLogger"""
146 import syslog
147 if isinstance(message, unicode):
148 message = message.encode(self.encoding, 'replace')
149 syslog.syslog(priority | syslog.LOG_LOCAL7, message)
150