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