chiark / gitweb /
systemd-python: attach fields to JournalHandler, add SYSLOG_IDENTIFIER
[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 uuid as _uuid
27 import traceback as _traceback
28 import os as _os
29 import logging as _logging
30 if _sys.version_info >= (3,3):
31     from collections import ChainMap as _ChainMap
32 from syslog import (LOG_EMERG, LOG_ALERT, LOG_CRIT, LOG_ERR,
33                     LOG_WARNING, LOG_NOTICE, LOG_INFO, LOG_DEBUG)
34 from ._journal import sendv, stream_fd
35 from ._reader import (_Reader, NOP, APPEND, INVALIDATE,
36                       LOCAL_ONLY, RUNTIME_ONLY, SYSTEM_ONLY,
37                       _get_catalog)
38 from . import id128 as _id128
39
40 if _sys.version_info >= (3,):
41     from ._reader import Monotonic
42 else:
43     Monotonic = tuple
44
45 def _convert_monotonic(m):
46     return Monotonic((_datetime.timedelta(microseconds=m[0]),
47                       _uuid.UUID(bytes=m[1])))
48
49 def _convert_source_monotonic(s):
50     return _datetime.timedelta(microseconds=int(s))
51
52 def _convert_realtime(t):
53     return _datetime.datetime.fromtimestamp(t / 1000000)
54
55 def _convert_timestamp(s):
56     return _datetime.datetime.fromtimestamp(int(s) / 1000000)
57
58 if _sys.version_info >= (3,):
59     def _convert_uuid(s):
60         return _uuid.UUID(s.decode())
61 else:
62     _convert_uuid = _uuid.UUID
63
64 DEFAULT_CONVERTERS = {
65     'MESSAGE_ID': _convert_uuid,
66     '_MACHINE_ID': _convert_uuid,
67     '_BOOT_ID': _convert_uuid,
68     'PRIORITY': int,
69     'LEADER': int,
70     'SESSION_ID': int,
71     'USERSPACE_USEC': int,
72     'INITRD_USEC': int,
73     'KERNEL_USEC': int,
74     '_UID': int,
75     '_GID': int,
76     '_PID': int,
77     'SYSLOG_FACILITY': int,
78     'SYSLOG_PID': int,
79     '_AUDIT_SESSION': int,
80     '_AUDIT_LOGINUID': int,
81     '_SYSTEMD_SESSION': int,
82     '_SYSTEMD_OWNER_UID': int,
83     'CODE_LINE': int,
84     'ERRNO': int,
85     'EXIT_STATUS': int,
86     '_SOURCE_REALTIME_TIMESTAMP': _convert_timestamp,
87     '__REALTIME_TIMESTAMP': _convert_realtime,
88     '_SOURCE_MONOTONIC_TIMESTAMP': _convert_source_monotonic,
89     '__MONOTONIC_TIMESTAMP': _convert_monotonic,
90     'COREDUMP': bytes,
91     'COREDUMP_PID': int,
92     'COREDUMP_UID': int,
93     'COREDUMP_GID': int,
94     'COREDUMP_SESSION': int,
95     'COREDUMP_SIGNAL': int,
96     'COREDUMP_TIMESTAMP': _convert_timestamp,
97 }
98
99 _IDENT_LETTER = set('ABCDEFGHIJKLMNOPQRTSUVWXYZ_')
100
101 def _valid_field_name(s):
102     return not (set(s) - _IDENT_LETTER)
103
104 class Reader(_Reader):
105     """Reader allows the access and filtering of systemd journal
106     entries. Note that in order to access the system journal, a
107     non-root user must be in the `systemd-journal` group.
108
109     Example usage to print out all informational or higher level
110     messages for systemd-udevd for this boot:
111
112     >>> j = journal.Reader()
113     >>> j.this_boot()
114     >>> j.log_level(journal.LOG_INFO)
115     >>> j.add_match(_SYSTEMD_UNIT="systemd-udevd.service")
116     >>> for entry in j:
117     ...    print(entry['MESSAGE'])
118
119     See systemd.journal-fields(7) for more info on typical fields
120     found in the journal.
121     """
122     def __init__(self, flags=0, path=None, converters=None):
123         """Create an instance of Reader, which allows filtering and
124         return of journal entries.
125
126         Argument `flags` sets open flags of the journal, which can be one
127         of, or ORed combination of constants: LOCAL_ONLY (default) opens
128         journal on local machine only; RUNTIME_ONLY opens only
129         volatile journal files; and SYSTEM_ONLY opens only
130         journal files of system services and the kernel.
131
132         Argument `path` is the directory of journal files. Note that
133         `flags` and `path` are exclusive.
134
135         Argument `converters` is a dictionary which updates the
136         DEFAULT_CONVERTERS to convert journal field values. Field
137         names are used as keys into this dictionary. The values must
138         be single argument functions, which take a `bytes` object and
139         return a converted value. When there's no entry for a field
140         name, then the default UTF-8 decoding will be attempted. If
141         the conversion fails with a ValueError, unconverted bytes
142         object will be returned. (Note that ValueEror is a superclass
143         of UnicodeDecodeError).
144
145         Reader implements the context manager protocol: the journal
146         will be closed when exiting the block.
147         """
148         super(Reader, self).__init__(flags, path)
149         if _sys.version_info >= (3,3):
150             self.converters = _ChainMap()
151             if converters is not None:
152                 self.converters.maps.append(converters)
153             self.converters.maps.append(DEFAULT_CONVERTERS)
154         else:
155             self.converters = DEFAULT_CONVERTERS.copy()
156             if converters is not None:
157                 self.converters.update(converters)
158
159     def _convert_field(self, key, value):
160         """Convert value using self.converters[key]
161
162         If `key` is not present in self.converters, a standard unicode
163         decoding will be attempted.  If the conversion (either
164         key-specific or the default one) fails with a ValueError, the
165         original bytes object will be returned.
166         """
167         convert = self.converters.get(key, bytes.decode)
168         try:
169             return convert(value)
170         except ValueError:
171             # Leave in default bytes
172             return value
173
174     def _convert_entry(self, entry):
175         """Convert entire journal entry utilising _covert_field"""
176         result = {}
177         for key, value in entry.items():
178             if isinstance(value, list):
179                 result[key] = [self._convert_field(key, val) for val in value]
180             else:
181                 result[key] = self._convert_field(key, value)
182         return result
183
184     def __iter__(self):
185         """Part of iterator protocol.
186         Returns self.
187         """
188         return self
189
190     if _sys.version_info >= (3,):
191         def __next__(self):
192             """Part of iterator protocol.
193             Returns self.get_next().
194             """
195             return self.get_next()
196     else:
197         def next(self):
198             """Part of iterator protocol.
199             Returns self.get_next().
200             """
201             return self.get_next()
202
203     def add_match(self, *args, **kwargs):
204         """Add one or more matches to the filter journal log entries.
205         All matches of different field are combined in a logical AND,
206         and matches of the same field are automatically combined in a
207         logical OR.
208         Matches can be passed as strings of form "FIELD=value", or
209         keyword arguments FIELD="value".
210         """
211         args = list(args)
212         args.extend(_make_line(key, val) for key, val in kwargs.items())
213         for arg in args:
214             super(Reader, self).add_match(arg)
215
216     def get_next(self, skip=1):
217         """Return the next log entry as a mapping type, currently
218         a standard dictionary of fields.
219
220         Optional skip value will return the `skip`\-th log entry.
221
222         Entries will be processed with converters specified during
223         Reader creation.
224         """
225         if super(Reader, self)._next(skip):
226             entry = super(Reader, self)._get_all()
227             if entry:
228                 entry['__REALTIME_TIMESTAMP'] =  self._get_realtime()
229                 entry['__MONOTONIC_TIMESTAMP']  = self._get_monotonic()
230                 entry['__CURSOR']  = self._get_cursor()
231                 return self._convert_entry(entry)
232         return dict()
233
234     def get_previous(self, skip=1):
235         """Return the previous log entry as a mapping type,
236         currently a standard dictionary of fields.
237
238         Optional skip value will return the -`skip`\-th log entry.
239
240         Entries will be processed with converters specified during
241         Reader creation.
242
243         Equivilent to get_next(-skip).
244         """
245         return self.get_next(-skip)
246
247     def query_unique(self, field):
248         """Return unique values appearing in the journal for given `field`.
249
250         Note this does not respect any journal matches.
251
252         Entries will be processed with converters specified during
253         Reader creation.
254         """
255         return set(self._convert_field(field, value)
256             for value in super(Reader, self).query_unique(field))
257
258     def wait(self, timeout=None):
259         """Wait for a change in the journal. `timeout` is the maximum
260         time in seconds to wait, or None, to wait forever.
261
262         Returns one of NOP (no change), APPEND (new entries have been
263         added to the end of the journal), or INVALIDATE (journal files
264         have been added or removed).
265         """
266         us = -1 if timeout is None else int(timeout * 1000000)
267         return super(Reader, self).wait(us)
268
269     def seek_realtime(self, realtime):
270         """Seek to a matching journal entry nearest to `realtime` time.
271
272         Argument `realtime` must be either an integer unix timestamp
273         or datetime.datetime instance.
274         """
275         if isinstance(realtime, _datetime.datetime):
276             realtime = float(realtime.strftime("%s.%f")) * 1000000
277         return super(Reader, self).seek_realtime(int(realtime))
278
279     def seek_monotonic(self, monotonic, bootid=None):
280         """Seek to a matching journal entry nearest to `monotonic` time.
281
282         Argument `monotonic` is a timestamp from boot in either
283         seconds or a datetime.timedelta instance. Argument `bootid`
284         is a string or UUID representing which boot the monotonic time
285         is reference to. Defaults to current bootid.
286         """
287         if isinstance(monotonic, _datetime.timedelta):
288             monotonic = monotonic.totalseconds()
289         monotonic = int(monotonic * 1000000)
290         if isinstance(bootid, _uuid.UUID):
291             bootid = bootid.get_hex()
292         return super(Reader, self).seek_monotonic(monotonic, bootid)
293
294     def log_level(self, level):
295         """Set maximum log `level` by setting matches for PRIORITY.
296         """
297         if 0 <= level <= 7:
298             for i in range(level+1):
299                 self.add_match(PRIORITY="%d" % i)
300         else:
301             raise ValueError("Log level must be 0 <= level <= 7")
302
303     def messageid_match(self, messageid):
304         """Add match for log entries with specified `messageid`.
305
306         `messageid` can be string of hexadicimal digits or a UUID
307         instance. Standard message IDs can be found in systemd.id128.
308
309         Equivalent to add_match(MESSAGE_ID=`messageid`).
310         """
311         if isinstance(messageid, _uuid.UUID):
312             messageid = messageid.get_hex()
313         self.add_match(MESSAGE_ID=messageid)
314
315     def this_boot(self, bootid=None):
316         """Add match for _BOOT_ID equal to current boot ID or the specified boot ID.
317
318         If specified, bootid should be either a UUID or a 32 digit hex number.
319
320         Equivalent to add_match(_BOOT_ID='bootid').
321         """
322         if bootid is None:
323             bootid = _id128.get_boot().hex
324         else:
325             bootid = getattr(bootid, 'hex', bootid)
326         self.add_match(_BOOT_ID=bootid)
327
328     def this_machine(self, machineid=None):
329         """Add match for _MACHINE_ID equal to the ID of this machine.
330
331         If specified, machineid should be either a UUID or a 32 digit hex number.
332
333         Equivalent to add_match(_MACHINE_ID='machineid').
334         """
335         if machineid is None:
336             machineid = _id128.get_machine().hex
337         else:
338             machineid = getattr(machineid, 'hex', machineid)
339         self.add_match(_MACHINE_ID=machineid)
340
341
342 def get_catalog(mid):
343     if isinstance(mid, _uuid.UUID):
344         mid = mid.get_hex()
345     return _get_catalog(mid)
346
347 def _make_line(field, value):
348         if isinstance(value, bytes):
349                 return field.encode('utf-8') + b'=' + value
350         else:
351                 return field + '=' + value
352
353 def send(MESSAGE, MESSAGE_ID=None,
354          CODE_FILE=None, CODE_LINE=None, CODE_FUNC=None,
355          **kwargs):
356         r"""Send a message to the journal.
357
358         >>> journal.send('Hello world')
359         >>> journal.send('Hello, again, world', FIELD2='Greetings!')
360         >>> journal.send('Binary message', BINARY=b'\xde\xad\xbe\xef')
361
362         Value of the MESSAGE argument will be used for the MESSAGE=
363         field. MESSAGE must be a string and will be sent as UTF-8 to
364         the journal.
365
366         MESSAGE_ID can be given to uniquely identify the type of
367         message. It must be a string or a uuid.UUID object.
368
369         CODE_LINE, CODE_FILE, and CODE_FUNC can be specified to
370         identify the caller. Unless at least on of the three is given,
371         values are extracted from the stack frame of the caller of
372         send(). CODE_FILE and CODE_FUNC must be strings, CODE_LINE
373         must be an integer.
374
375         Additional fields for the journal entry can only be specified
376         as keyword arguments. The payload can be either a string or
377         bytes. A string will be sent as UTF-8, and bytes will be sent
378         as-is to the journal.
379
380         Other useful fields include PRIORITY, SYSLOG_FACILITY,
381         SYSLOG_IDENTIFIER, SYSLOG_PID.
382         """
383
384         args = ['MESSAGE=' + MESSAGE]
385
386         if MESSAGE_ID is not None:
387                 id = getattr(MESSAGE_ID, 'hex', MESSAGE_ID)
388                 args.append('MESSAGE_ID=' + id)
389
390         if CODE_LINE == CODE_FILE == CODE_FUNC == None:
391                 CODE_FILE, CODE_LINE, CODE_FUNC = \
392                         _traceback.extract_stack(limit=2)[0][:3]
393         if CODE_FILE is not None:
394                 args.append('CODE_FILE=' + CODE_FILE)
395         if CODE_LINE is not None:
396                 args.append('CODE_LINE={:d}'.format(CODE_LINE))
397         if CODE_FUNC is not None:
398                 args.append('CODE_FUNC=' + CODE_FUNC)
399
400         args.extend(_make_line(key, val) for key, val in kwargs.items())
401         return sendv(*args)
402
403 def stream(identifier, priority=LOG_DEBUG, level_prefix=False):
404         r"""Return a file object wrapping a stream to journal.
405
406         Log messages written to this file as simple newline sepearted
407         text strings are written to the journal.
408
409         The file will be line buffered, so messages are actually sent
410         after a newline character is written.
411
412         >>> stream = journal.stream('myapp')
413         >>> stream
414         <open file '<fdopen>', mode 'w' at 0x...>
415         >>> stream.write('message...\n')
416
417         will produce the following message in the journal::
418
419           PRIORITY=7
420           SYSLOG_IDENTIFIER=myapp
421           MESSAGE=message...
422
423         Using the interface with print might be more convinient:
424
425         >>> from __future__ import print_function
426         >>> print('message...', file=stream)
427
428         priority is the syslog priority, one of `LOG_EMERG`,
429         `LOG_ALERT`, `LOG_CRIT`, `LOG_ERR`, `LOG_WARNING`,
430         `LOG_NOTICE`, `LOG_INFO`, `LOG_DEBUG`.
431
432         level_prefix is a boolean. If true, kernel-style log priority
433         level prefixes (such as '<1>') are interpreted. See
434         sd-daemon(3) for more information.
435         """
436
437         fd = stream_fd(identifier, priority, level_prefix)
438         return _os.fdopen(fd, 'w', 1)
439
440 class JournalHandler(_logging.Handler):
441         """Journal handler class for the Python logging framework.
442
443         Please see the Python logging module documentation for an
444         overview: http://docs.python.org/library/logging.html.
445
446         To create a custom logger whose messages go only to journal:
447
448         >>> log = logging.getLogger('custom_logger_name')
449         >>> log.propagate = False
450         >>> log.addHandler(journal.JournalHandler())
451         >>> log.warn("Some message: %s", detail)
452
453         Note that by default, message levels `INFO` and `DEBUG` are
454         ignored by the logging framework. To enable those log levels:
455
456         >>> log.setLevel(logging.DEBUG)
457
458         To redirect all logging messages to journal regardless of where
459         they come from, attach it to the root logger:
460
461         >>> logging.root.addHandler(journal.JournalHandler())
462
463         For more complex configurations when using `dictConfig` or
464         `fileConfig`, specify `systemd.journal.JournalHandler` as the
465         handler class.  Only standard handler configuration options
466         are supported: `level`, `formatter`, `filters`.
467
468         To attach journal MESSAGE_ID, an extra field is supported:
469
470         >>> import uuid
471         >>> mid = uuid.UUID('0123456789ABCDEF0123456789ABCDEF')
472         >>> log.warn("Message with ID", extra={'MESSAGE_ID': mid})
473
474         Fields to be attached to all messages sent through this
475         handler can be specified as keyword arguments. This probably
476         makes sense only for SYSLOG_IDENTIFIER and similar fields
477         which are constant for the whole program:
478
479         >>> journal.JournalHandler(SYSLOG_IDENTIFIER='my-cool-app')
480
481         The following journal fields will be sent:
482         `MESSAGE`, `PRIORITY`, `THREAD_NAME`, `CODE_FILE`, `CODE_LINE`,
483         `CODE_FUNC`, `LOGGER` (name as supplied to getLogger call),
484         `MESSAGE_ID` (optional, see above), `SYSLOG_IDENTIFIER` (defaults
485         to sys.argv[0]).
486         """
487
488         def __init__(self, level=_logging.NOTSET, **kwargs):
489                 super(JournalHandler, self).__init__(level)
490
491                 for name in kwargs:
492                         if not _valid_field_name(name):
493                                 raise ValueError('Invalid field name: ' + name)
494                 if 'SYSLOG_IDENTIFIER' not in kwargs:
495                         kwargs['SYSLOG_IDENTIFIER'] = _sys.argv[0]
496                 self._extra = kwargs
497
498         def emit(self, record):
499                 """Write record as journal event.
500
501                 MESSAGE is taken from the message provided by the
502                 user, and PRIORITY, LOGGER, THREAD_NAME,
503                 CODE_{FILE,LINE,FUNC} fields are appended
504                 automatically. In addition, record.MESSAGE_ID will be
505                 used if present.
506                 """
507                 try:
508                         msg = self.format(record)
509                         pri = self.mapPriority(record.levelno)
510                         mid = getattr(record, 'MESSAGE_ID', None)
511                         send(msg,
512                              MESSAGE_ID=mid,
513                              PRIORITY=format(pri),
514                              LOGGER=record.name,
515                              THREAD_NAME=record.threadName,
516                              CODE_FILE=record.pathname,
517                              CODE_LINE=record.lineno,
518                              CODE_FUNC=record.funcName,
519                              **self._extra)
520                 except Exception:
521                         self.handleError(record)
522
523         @staticmethod
524         def mapPriority(levelno):
525                 """Map logging levels to journald priorities.
526
527                 Since Python log level numbers are "sparse", we have
528                 to map numbers in between the standard levels too.
529                 """
530                 if levelno <= _logging.DEBUG:
531                         return LOG_DEBUG
532                 elif levelno <= _logging.INFO:
533                         return LOG_INFO
534                 elif levelno <= _logging.WARNING:
535                         return LOG_WARNING
536                 elif levelno <= _logging.ERROR:
537                         return LOG_ERR
538                 elif levelno <= _logging.CRITICAL:
539                         return LOG_CRIT
540                 else:
541                         return LOG_ALERT