chiark / gitweb /
d94934cfa80e817f855235f08a2c471e57b586be
[elogind.git] / src / python-systemd / journal.py
1 #  -*- Mode: python; coding:utf-8; indent-tabs-mode: nil -*- */
2 #
3 #  This file is part of systemd.
4 #
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>
8 #
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.
13 #
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.
18 #
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/>.
21
22 from __future__ import division
23
24 import sys as _sys
25 import datetime as _datetime
26 import functools as _functools
27 import uuid as _uuid
28 import traceback as _traceback
29 import os as _os
30 from os import SEEK_SET, SEEK_CUR, SEEK_END
31 import logging as _logging
32 if _sys.version_info >= (3,):
33     from collections import ChainMap as _ChainMap
34 from syslog import (LOG_EMERG, LOG_ALERT, LOG_CRIT, LOG_ERR,
35                     LOG_WARNING, LOG_NOTICE, LOG_INFO, LOG_DEBUG)
36 from ._journal import sendv, stream_fd
37 from ._reader import (_Journal, NOP, APPEND, INVALIDATE,
38                       LOCAL_ONLY, RUNTIME_ONLY, SYSTEM_ONLY)
39 from . import id128 as _id128
40
41 _MONOTONIC_CONVERTER = lambda x: _datetime.timedelta(microseconds=x)
42 _REALTIME_CONVERTER = lambda x: _datetime.datetime.fromtimestamp(x / 1E6)
43 DEFAULT_CONVERTERS = {
44     'MESSAGE_ID': _uuid.UUID,
45     '_MACHINE_ID': _uuid.UUID,
46     '_BOOT_ID': _uuid.UUID,
47     'PRIORITY': int,
48     'LEADER': int,
49     'SESSION_ID': int,
50     'USERSPACE_USEC': int,
51     'INITRD_USEC': int,
52     'KERNEL_USEC': int,
53     '_UID': int,
54     '_GID': int,
55     '_PID': int,
56     'SYSLOG_FACILITY': int,
57     'SYSLOG_PID': int,
58     '_AUDIT_SESSION': int,
59     '_AUDIT_LOGINUID': int,
60     '_SYSTEMD_SESSION': int,
61     '_SYSTEMD_OWNER_UID': int,
62     'CODE_LINE': int,
63     'ERRNO': int,
64     'EXIT_STATUS': int,
65     '_SOURCE_REALTIME_TIMESTAMP': _REALTIME_CONVERTER,
66     '__REALTIME_TIMESTAMP': _REALTIME_CONVERTER,
67     '_SOURCE_MONOTONIC_TIMESTAMP': _MONOTONIC_CONVERTER,
68     '__MONOTONIC_TIMESTAMP': _MONOTONIC_CONVERTER,
69     'COREDUMP': bytes,
70     'COREDUMP_PID': int,
71     'COREDUMP_UID': int,
72     'COREDUMP_GID': int,
73     'COREDUMP_SESSION': int,
74     'COREDUMP_SIGNAL': int,
75     'COREDUMP_TIMESTAMP': _REALTIME_CONVERTER,
76 }
77
78 if _sys.version_info >= (3,):
79     _convert_unicode = _functools.partial(str, encoding='utf-8')
80 else:
81     _convert_unicode = _functools.partial(unicode, encoding='utf-8')
82
83 class Journal(_Journal):
84     """Journal allows the access and filtering of systemd journal
85     entries. Note that in order to access the system journal, a
86     non-root user must be in the `adm` group.
87
88     Example usage to print out all error or higher level messages
89     for systemd-udevd for the boot:
90
91     >>> myjournal = journal.Journal()
92     >>> myjournal.add_boot_match(journal.CURRENT_BOOT)
93     >>> myjournal.add_loglevel_matches(journal.LOG_ERR)
94     >>> myjournal.add_match(_SYSTEMD_UNIT="systemd-udevd.service")
95     >>> for entry in myjournal:
96     ...    print(entry['MESSAGE'])
97
98     See systemd.journal-fields(7) for more info on typical fields
99     found in the journal.
100     """
101     def __init__(self, converters=None, flags=LOCAL_ONLY, path=None):
102         """Creates instance of Journal, which allows filtering and
103         return of journal entries.
104         Argument `converters` is a dictionary which updates the
105         DEFAULT_CONVERTERS to convert journal field values.
106         Argument `flags` sets open flags of the journal, which can be one
107         of, or ORed combination of constants: LOCAL_ONLY (default) opens
108         journal on local machine only; RUNTIME_ONLY opens only
109         volatile journal files; and SYSTEM_ONLY opens only
110         journal files of system services and the kernel.
111         Argument `path` is the directory of journal files. Note that
112         currently flags are ignored when `path` is present as they are
113         currently not relevant.
114         """
115         super(Journal, self).__init__(flags, path)
116         if _sys.version_info >= (3,3):
117             self.converters = _ChainMap()
118             if converters is not None:
119                 self.converters.maps.append(converters)
120             self.converters.maps.append(DEFAULT_CONVERTERS)
121         else:
122             self.converters = DEFAULT_CONVERTERS.copy()
123             if converters is not None:
124                 self.converters.update(converters)
125
126     def _convert_field(self, key, value):
127         """Convert value based on callable from self.converters
128         based of field/key"""
129         try:
130             result = self.converters[key](value)
131         except:
132             # Default conversion in unicode
133             try:
134                 result = _convert_unicode(value)
135             except UnicodeDecodeError:
136                 # Leave in default bytes
137                 result = value
138         return result
139
140     def _convert_entry(self, entry):
141         """Convert entire journal entry utilising _covert_field"""
142         result = {}
143         for key, value in entry.items():
144             if isinstance(value, list):
145                 result[key] = [self._convert_field(key, val) for val in value]
146             else:
147                 result[key] = self._convert_field(key, value)
148         return result
149
150     def add_match(self, *args, **kwargs):
151         """Add one or more matches to the filter journal log entries.
152         All matches of different field are combined in a logical AND,
153         and matches of the same field are automatically combined in a
154         logical OR.
155         Matches can be passed as strings of form "FIELD=value", or
156         keyword arguments FIELD="value".
157         """
158         args = list(args)
159         args.extend(_make_line(key, val) for key, val in kwargs.items())
160         for arg in args:
161             super(Journal, self).add_match(arg)
162
163     def get_next(self, skip=1):
164         """Return the next log entry as a dictionary of fields.
165
166         Optional skip value will return the `skip`\-th log entry.
167
168         Entries will be processed with converters specified during
169         Journal creation.
170         """
171         return self._convert_entry(
172             super(Journal, self).get_next(skip))
173
174     def query_unique(self, field):
175         """Return unique values appearing in the Journal for given `field`.
176
177         Note this does not respect any journal matches.
178
179         Entries will be processed with converters specified during
180         Journal creation.
181         """
182         return set(self._convert_field(field, value)
183             for value in super(Journal, self).query_unique(field))
184
185     def seek_realtime(self, realtime):
186         """Seek to a matching journal entry nearest to `realtime` time.
187
188         Argument `realtime` must be either an integer unix timestamp
189         or datetime.datetime instance.
190         """
191         if isinstance(realtime, _datetime.datetime):
192             realtime = float(realtime.strftime("%s.%f"))
193         return super(Journal, self).seek_realtime(realtime)
194
195     def seek_monotonic(self, monotonic, bootid=None):
196         """Seek to a matching journal entry nearest to `monotonic` time.
197
198         Argument `monotonic` is a timestamp from boot in either
199         seconds or a datetime.timedelta instance. Argument `bootid`
200         is a string or UUID representing which boot the monotonic time
201         is reference to. Defaults to current bootid.
202         """
203         if isinstance(monotonic, _datetime.timedelta):
204             monotonic = monotonic.totalseconds()
205         if isinstance(bootid, _uuid.UUID):
206             bootid = bootid.get_hex()
207         return super(Journal, self).seek_monotonic(monotonic, bootid)
208
209     def log_level(self, level):
210         """Set maximum log `level` by setting matches for PRIORITY.
211         """
212         if 0 <= level <= 7:
213             for i in range(level+1):
214                 self.add_match(PRIORITY="%s" % i)
215         else:
216             raise ValueError("Log level must be 0 <= level <= 7")
217
218     def messageid_match(self, messageid):
219         """Add match for log entries with specified `messageid`.
220
221         `messageid` can be string of hexadicimal digits or a UUID
222         instance. Standard message IDs can be found in systemd.id128.
223
224         Equivalent to add_match(MESSAGE_ID=`messageid`).
225         """
226         if isinstance(messageid, _uuid.UUID):
227             messageid = messageid.get_hex()
228         self.add_match(MESSAGE_ID=messageid)
229
230     def this_boot(self, bootid=None):
231         """Add match for _BOOT_ID equal to current boot ID or the specified boot ID.
232
233         If specified, bootid should be either a UUID or a 32 digit hex number.
234
235         Equivalent to add_match(_BOOT_ID='bootid').
236         """
237         if bootid is None:
238             bootid = _id128.get_boot().hex
239         else:
240             bootid = getattr(bootid, 'hex', bootid)
241         self.add_match(_BOOT_ID=bootid)
242
243     def this_machine(self, machineid=None):
244         """Add match for _MACHINE_ID equal to the ID of this machine.
245
246         If specified, machineid should be either a UUID or a 32 digit hex number.
247
248         Equivalent to add_match(_MACHINE_ID='machineid').
249         """
250         if machineid is None:
251             machineid = _id128.get_machine().hex
252         else:
253             machineid = getattr(machineid, 'hex', machineid)
254         self.add_match(_MACHINE_ID=machineid)
255
256
257 def _make_line(field, value):
258         if isinstance(value, bytes):
259                 return field.encode('utf-8') + b'=' + value
260         else:
261                 return field + '=' + value
262
263 def send(MESSAGE, MESSAGE_ID=None,
264          CODE_FILE=None, CODE_LINE=None, CODE_FUNC=None,
265          **kwargs):
266         r"""Send a message to the journal.
267
268         >>> journal.send('Hello world')
269         >>> journal.send('Hello, again, world', FIELD2='Greetings!')
270         >>> journal.send('Binary message', BINARY=b'\xde\xad\xbe\xef')
271
272         Value of the MESSAGE argument will be used for the MESSAGE=
273         field. MESSAGE must be a string and will be sent as UTF-8 to
274         the journal.
275
276         MESSAGE_ID can be given to uniquely identify the type of
277         message. It must be a string or a uuid.UUID object.
278
279         CODE_LINE, CODE_FILE, and CODE_FUNC can be specified to
280         identify the caller. Unless at least on of the three is given,
281         values are extracted from the stack frame of the caller of
282         send(). CODE_FILE and CODE_FUNC must be strings, CODE_LINE
283         must be an integer.
284
285         Additional fields for the journal entry can only be specified
286         as keyword arguments. The payload can be either a string or
287         bytes. A string will be sent as UTF-8, and bytes will be sent
288         as-is to the journal.
289
290         Other useful fields include PRIORITY, SYSLOG_FACILITY,
291         SYSLOG_IDENTIFIER, SYSLOG_PID.
292         """
293
294         args = ['MESSAGE=' + MESSAGE]
295
296         if MESSAGE_ID is not None:
297                 id = getattr(MESSAGE_ID, 'hex', MESSAGE_ID)
298                 args.append('MESSAGE_ID=' + id)
299
300         if CODE_LINE == CODE_FILE == CODE_FUNC == None:
301                 CODE_FILE, CODE_LINE, CODE_FUNC = \
302                         _traceback.extract_stack(limit=2)[0][:3]
303         if CODE_FILE is not None:
304                 args.append('CODE_FILE=' + CODE_FILE)
305         if CODE_LINE is not None:
306                 args.append('CODE_LINE={:d}'.format(CODE_LINE))
307         if CODE_FUNC is not None:
308                 args.append('CODE_FUNC=' + CODE_FUNC)
309
310         args.extend(_make_line(key, val) for key, val in kwargs.items())
311         return sendv(*args)
312
313 def stream(identifier, priority=LOG_DEBUG, level_prefix=False):
314         r"""Return a file object wrapping a stream to journal.
315
316         Log messages written to this file as simple newline sepearted
317         text strings are written to the journal.
318
319         The file will be line buffered, so messages are actually sent
320         after a newline character is written.
321
322         >>> stream = journal.stream('myapp')
323         >>> stream
324         <open file '<fdopen>', mode 'w' at 0x...>
325         >>> stream.write('message...\n')
326
327         will produce the following message in the journal::
328
329           PRIORITY=7
330           SYSLOG_IDENTIFIER=myapp
331           MESSAGE=message...
332
333         Using the interface with print might be more convinient:
334
335         >>> from __future__ import print_function
336         >>> print('message...', file=stream)
337
338         priority is the syslog priority, one of `LOG_EMERG`,
339         `LOG_ALERT`, `LOG_CRIT`, `LOG_ERR`, `LOG_WARNING`,
340         `LOG_NOTICE`, `LOG_INFO`, `LOG_DEBUG`.
341
342         level_prefix is a boolean. If true, kernel-style log priority
343         level prefixes (such as '<1>') are interpreted. See
344         sd-daemon(3) for more information.
345         """
346
347         fd = stream_fd(identifier, priority, level_prefix)
348         return _os.fdopen(fd, 'w', 1)
349
350 class JournalHandler(_logging.Handler):
351         """Journal handler class for the Python logging framework.
352
353         Please see the Python logging module documentation for an
354         overview: http://docs.python.org/library/logging.html.
355
356         To create a custom logger whose messages go only to journal:
357
358         >>> log = logging.getLogger('custom_logger_name')
359         >>> log.propagate = False
360         >>> log.addHandler(journal.JournalHandler())
361         >>> log.warn("Some message: %s", detail)
362
363         Note that by default, message levels `INFO` and `DEBUG` are
364         ignored by the logging framework. To enable those log levels:
365
366         >>> log.setLevel(logging.DEBUG)
367
368         To attach journal MESSAGE_ID, an extra field is supported:
369
370         >>> import uuid
371         >>> mid = uuid.UUID('0123456789ABCDEF0123456789ABCDEF')
372         >>> log.warn("Message with ID", extra={'MESSAGE_ID': mid})
373
374         To redirect all logging messages to journal regardless of where
375         they come from, attach it to the root logger:
376
377         >>> logging.root.addHandler(journal.JournalHandler())
378
379         For more complex configurations when using `dictConfig` or
380         `fileConfig`, specify `systemd.journal.JournalHandler` as the
381         handler class.  Only standard handler configuration options
382         are supported: `level`, `formatter`, `filters`.
383
384         The following journal fields will be sent:
385         `MESSAGE`, `PRIORITY`, `THREAD_NAME`, `CODE_FILE`, `CODE_LINE`,
386         `CODE_FUNC`, `LOGGER` (name as supplied to getLogger call),
387         `MESSAGE_ID` (optional, see above).
388         """
389
390         def emit(self, record):
391                 """Write record as journal event.
392
393                 MESSAGE is taken from the message provided by the
394                 user, and PRIORITY, LOGGER, THREAD_NAME,
395                 CODE_{FILE,LINE,FUNC} fields are appended
396                 automatically. In addition, record.MESSAGE_ID will be
397                 used if present.
398                 """
399                 try:
400                         msg = self.format(record)
401                         pri = self.mapPriority(record.levelno)
402                         mid = getattr(record, 'MESSAGE_ID', None)
403                         send(msg,
404                              MESSAGE_ID=mid,
405                              PRIORITY=format(pri),
406                              LOGGER=record.name,
407                              THREAD_NAME=record.threadName,
408                              CODE_FILE=record.pathname,
409                              CODE_LINE=record.lineno,
410                              CODE_FUNC=record.funcName)
411                 except Exception:
412                         self.handleError(record)
413
414         @staticmethod
415         def mapPriority(levelno):
416                 """Map logging levels to journald priorities.
417
418                 Since Python log level numbers are "sparse", we have
419                 to map numbers in between the standard levels too.
420                 """
421                 if levelno <= _logging.DEBUG:
422                         return LOG_DEBUG
423                 elif levelno <= _logging.INFO:
424                         return LOG_INFO
425                 elif levelno <= _logging.WARNING:
426                         return LOG_WARNING
427                 elif levelno <= _logging.ERROR:
428                         return LOG_ERR
429                 elif levelno <= _logging.CRITICAL:
430                         return LOG_CRIT
431                 else:
432                         return LOG_ALERT