1 # -*- Mode: python; coding:utf-8; indent-tabs-mode: nil -*- */
3 # This file is part of systemd.
5 # Copyright 2012 David Strauss <david@davidstrauss.net>
6 # Copyright 2012 Zbigniew Jędrzejewski-Szmek <zbyszek@in.waw.pl>
7 # Copyright 2012 Marti Raudsepp <marti@juffo.org>
9 # systemd is free software; you can redistribute it and/or modify it
10 # under the terms of the GNU Lesser General Public License as published by
11 # the Free Software Foundation; either version 2.1 of the License, or
12 # (at your option) any later version.
14 # systemd is distributed in the hope that it will be useful, but
15 # WITHOUT ANY WARRANTY; without even the implied warranty of
16 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
17 # Lesser General Public License for more details.
19 # You should have received a copy of the GNU Lesser General Public License
20 # along with systemd; If not, see <http://www.gnu.org/licenses/>.
26 import traceback as _traceback
28 import logging as _logging
29 if sys.version_info >= (3,):
30 from collections import ChainMap
31 from syslog import (LOG_EMERG, LOG_ALERT, LOG_CRIT, LOG_ERR,
32 LOG_WARNING, LOG_NOTICE, LOG_INFO, LOG_DEBUG)
33 from ._journal import sendv, stream_fd
34 from ._reader import (_Journal, NOP, APPEND, INVALIDATE,
35 LOCAL_ONLY, RUNTIME_ONLY, SYSTEM_ONLY)
36 from . import id128 as _id128
38 _MONOTONIC_CONVERTER = lambda x: datetime.timedelta(microseconds=float(x))
39 _REALTIME_CONVERTER = lambda x: datetime.datetime.fromtimestamp(float(x)/1E6)
40 DEFAULT_CONVERTERS = {
41 'MESSAGE_ID': uuid.UUID,
45 'USERSPACE_USEC': int,
51 'SYSLOG_FACILITY': int,
53 '_AUDIT_SESSION': int,
54 '_AUDIT_LOGINUID': int,
55 '_SYSTEMD_SESSION': int,
56 '_SYSTEMD_OWNER_UID': int,
60 '_SOURCE_REALTIME_TIMESTAMP': _REALTIME_CONVERTER,
61 '__REALTIME_TIMESTAMP': _REALTIME_CONVERTER,
62 '_SOURCE_MONOTONIC_TIMESTAMP': _MONOTONIC_CONVERTER,
63 '__MONOTONIC_TIMESTAMP': _MONOTONIC_CONVERTER,
68 'COREDUMP_SESSION': int,
69 'COREDUMP_SIGNAL': int,
70 'COREDUMP_TIMESTAMP': _REALTIME_CONVERTER,
73 if sys.version_info >= (3,):
74 _convert_unicode = functools.partial(str, encoding='utf-8')
76 _convert_unicode = functools.partial(unicode, encoding='utf-8')
78 class Journal(_Journal):
79 def __init__(self, converters=None, *args, **kwargs):
80 super(Journal, self).__init__(*args, **kwargs)
81 if sys.version_info >= (3,3):
82 self.converters = ChainMap()
83 if converters is not None:
84 self.converters.maps.append(converters)
85 self.converters.maps.append(DEFAULT_CONVERTERS)
87 # suitable fallback, e.g.
88 self.converters = DEFAULT_CONVERTERS.copy()
89 if converters is not None:
90 self.converters.update(converters)
92 def _convert_field(self, key, value):
94 result = self.converters[key](value)
96 # Default conversion in unicode
98 result = _convert_unicode(value)
100 # Leave in default bytes
104 def _convert_entry(self, entry):
106 for key, value in entry.items():
107 if isinstance(value, list):
108 result[key] = [self._convert_field(key, val) for val in value]
110 result[key] = self._convert_field(key, value)
113 def add_match(self, *args, **kwargs):
115 args.extend(_make_line(key, val) for key, val in kwargs.items())
117 super(Journal, self).add_match(arg)
119 def get_next(self, skip=1):
120 return self._convert_entry(
121 super(Journal, self).get_next(skip))
123 def query_unique(self, key):
124 return set(self._convert_field(key, value)
125 for value in super(Journal, self).query_unique(key))
127 def seek_realtime(self, timestamp):
128 if isinstance(timestamp, datetime.datetime):
129 timestamp = float(timestamp.strftime("%s.%f"))
130 return super(Journal, self).seek_realtime(timestamp)
132 def seek_monotonic(self, timestamp, bootid=None):
133 if isinstance(timestamp, datetime.timedelta):
134 timestamp = timestamp.totalseconds()
135 return super(Journal, self).seek_monotonic(timestamp, bootid)
137 def log_level(self, level):
138 """Sets maximum log level by setting matches for PRIORITY."""
140 for i in range(level+1):
141 self.add_match(PRIORITY="%s" % i)
143 raise ValueError("Log level must be 0 <= level <= 7")
145 def this_boot(self, bootid=None):
146 """Add match for _BOOT_ID equal to current boot ID or the specified boot ID.
148 bootid should be either a UUID or a 32 digit hex number.
151 bootid = _id128.get_boot().hex
153 bootid = getattr(bootid, 'hex', bootid)
154 self.add_match(_BOOT_ID=bootid)
156 def this_machine(self, machineid=None):
157 """Add match for _MACHINE_ID equal to the ID of this machine.
159 bootid should be either a UUID or a 32 digit hex number.
161 if machineid is None:
162 machineid = _id128.get_machine().hex
164 machineid = getattr(machineid, 'hex', machineid)
165 self.add_match(_MACHINE_ID=machineid)
168 def _make_line(field, value):
169 if isinstance(value, bytes):
170 return field.encode('utf-8') + b'=' + value
172 return field + '=' + value
174 def send(MESSAGE, MESSAGE_ID=None,
175 CODE_FILE=None, CODE_LINE=None, CODE_FUNC=None,
177 r"""Send a message to the journal.
179 >>> journal.send('Hello world')
180 >>> journal.send('Hello, again, world', FIELD2='Greetings!')
181 >>> journal.send('Binary message', BINARY=b'\xde\xad\xbe\xef')
183 Value of the MESSAGE argument will be used for the MESSAGE=
184 field. MESSAGE must be a string and will be sent as UTF-8 to
187 MESSAGE_ID can be given to uniquely identify the type of
188 message. It must be a string or a uuid.UUID object.
190 CODE_LINE, CODE_FILE, and CODE_FUNC can be specified to
191 identify the caller. Unless at least on of the three is given,
192 values are extracted from the stack frame of the caller of
193 send(). CODE_FILE and CODE_FUNC must be strings, CODE_LINE
196 Additional fields for the journal entry can only be specified
197 as keyword arguments. The payload can be either a string or
198 bytes. A string will be sent as UTF-8, and bytes will be sent
199 as-is to the journal.
201 Other useful fields include PRIORITY, SYSLOG_FACILITY,
202 SYSLOG_IDENTIFIER, SYSLOG_PID.
205 args = ['MESSAGE=' + MESSAGE]
207 if MESSAGE_ID is not None:
208 id = getattr(MESSAGE_ID, 'hex', MESSAGE_ID)
209 args.append('MESSAGE_ID=' + id)
211 if CODE_LINE == CODE_FILE == CODE_FUNC == None:
212 CODE_FILE, CODE_LINE, CODE_FUNC = \
213 _traceback.extract_stack(limit=2)[0][:3]
214 if CODE_FILE is not None:
215 args.append('CODE_FILE=' + CODE_FILE)
216 if CODE_LINE is not None:
217 args.append('CODE_LINE={:d}'.format(CODE_LINE))
218 if CODE_FUNC is not None:
219 args.append('CODE_FUNC=' + CODE_FUNC)
221 args.extend(_make_line(key, val) for key, val in kwargs.items())
224 def stream(identifier, priority=LOG_DEBUG, level_prefix=False):
225 r"""Return a file object wrapping a stream to journal.
227 Log messages written to this file as simple newline sepearted
228 text strings are written to the journal.
230 The file will be line buffered, so messages are actually sent
231 after a newline character is written.
233 >>> stream = journal.stream('myapp')
235 <open file '<fdopen>', mode 'w' at 0x...>
236 >>> stream.write('message...\n')
238 will produce the following message in the journal::
241 SYSLOG_IDENTIFIER=myapp
244 Using the interface with print might be more convinient:
246 >>> from __future__ import print_function
247 >>> print('message...', file=stream)
249 priority is the syslog priority, one of `LOG_EMERG`,
250 `LOG_ALERT`, `LOG_CRIT`, `LOG_ERR`, `LOG_WARNING`,
251 `LOG_NOTICE`, `LOG_INFO`, `LOG_DEBUG`.
253 level_prefix is a boolean. If true, kernel-style log priority
254 level prefixes (such as '<1>') are interpreted. See
255 sd-daemon(3) for more information.
258 fd = stream_fd(identifier, priority, level_prefix)
259 return _os.fdopen(fd, 'w', 1)
261 class JournalHandler(_logging.Handler):
262 """Journal handler class for the Python logging framework.
264 Please see the Python logging module documentation for an
265 overview: http://docs.python.org/library/logging.html.
267 To create a custom logger whose messages go only to journal:
269 >>> log = logging.getLogger('custom_logger_name')
270 >>> log.propagate = False
271 >>> log.addHandler(journal.JournalHandler())
272 >>> log.warn("Some message: %s", detail)
274 Note that by default, message levels `INFO` and `DEBUG` are
275 ignored by the logging framework. To enable those log levels:
277 >>> log.setLevel(logging.DEBUG)
279 To attach journal MESSAGE_ID, an extra field is supported:
282 >>> mid = uuid.UUID('0123456789ABCDEF0123456789ABCDEF')
283 >>> log.warn("Message with ID", extra={'MESSAGE_ID': mid})
285 To redirect all logging messages to journal regardless of where
286 they come from, attach it to the root logger:
288 >>> logging.root.addHandler(journal.JournalHandler())
290 For more complex configurations when using `dictConfig` or
291 `fileConfig`, specify `systemd.journal.JournalHandler` as the
292 handler class. Only standard handler configuration options
293 are supported: `level`, `formatter`, `filters`.
295 The following journal fields will be sent:
296 `MESSAGE`, `PRIORITY`, `THREAD_NAME`, `CODE_FILE`, `CODE_LINE`,
297 `CODE_FUNC`, `LOGGER` (name as supplied to getLogger call),
298 `MESSAGE_ID` (optional, see above).
301 def emit(self, record):
302 """Write record as journal event.
304 MESSAGE is taken from the message provided by the
305 user, and PRIORITY, LOGGER, THREAD_NAME,
306 CODE_{FILE,LINE,FUNC} fields are appended
307 automatically. In addition, record.MESSAGE_ID will be
311 msg = self.format(record)
312 pri = self.mapPriority(record.levelno)
313 mid = getattr(record, 'MESSAGE_ID', None)
316 PRIORITY=format(pri),
318 THREAD_NAME=record.threadName,
319 CODE_FILE=record.pathname,
320 CODE_LINE=record.lineno,
321 CODE_FUNC=record.funcName)
323 self.handleError(record)
326 def mapPriority(levelno):
327 """Map logging levels to journald priorities.
329 Since Python log level numbers are "sparse", we have
330 to map numbers in between the standard levels too.
332 if levelno <= _logging.DEBUG:
334 elif levelno <= _logging.INFO:
336 elif levelno <= _logging.WARNING:
338 elif levelno <= _logging.ERROR:
340 elif levelno <= _logging.CRITICAL: