chiark / gitweb /
systemd-python: correct data_threshold error return value
[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 datetime
23 import functools
24 import sys
25 import uuid
26 import traceback as _traceback
27 import os as _os
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
37
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,
42     'PRIORITY': int,
43     'LEADER': int,
44     'SESSION_ID': int,
45     'USERSPACE_USEC': int,
46     'INITRD_USEC': int,
47     'KERNEL_USEC': int,
48     '_UID': int,
49     '_GID': int,
50     '_PID': int,
51     'SYSLOG_FACILITY': int,
52     'SYSLOG_PID': int,
53     '_AUDIT_SESSION': int,
54     '_AUDIT_LOGINUID': int,
55     '_SYSTEMD_SESSION': int,
56     '_SYSTEMD_OWNER_UID': int,
57     'CODE_LINE': int,
58     'ERRNO': int,
59     'EXIT_STATUS': int,
60     '_SOURCE_REALTIME_TIMESTAMP': _REALTIME_CONVERTER,
61     '__REALTIME_TIMESTAMP': _REALTIME_CONVERTER,
62     '_SOURCE_MONOTONIC_TIMESTAMP': _MONOTONIC_CONVERTER,
63     '__MONOTONIC_TIMESTAMP': _MONOTONIC_CONVERTER,
64     'COREDUMP': bytes,
65     'COREDUMP_PID': int,
66     'COREDUMP_UID': int,
67     'COREDUMP_GID': int,
68     'COREDUMP_SESSION': int,
69     'COREDUMP_SIGNAL': int,
70     'COREDUMP_TIMESTAMP': _REALTIME_CONVERTER,
71 }
72
73 if sys.version_info >= (3,):
74     _convert_unicode = functools.partial(str, encoding='utf-8')
75 else:
76     _convert_unicode = functools.partial(unicode, encoding='utf-8')
77
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)
86         else:
87             # suitable fallback, e.g.
88             self.converters = DEFAULT_CONVERTERS.copy()
89             if converters is not None:
90                 self.converters.update(converters)
91
92     def _convert_field(self, key, value):
93         try:
94             result = self.converters[key](value)
95         except:
96             # Default conversion in unicode
97             try:
98                 result = _convert_unicode(value)
99             except:
100                 # Leave in default bytes
101                 result = value
102         return result
103
104     def _convert_entry(self, entry):
105         result = {}
106         for key, value in entry.items():
107             if isinstance(value, list):
108                 result[key] = [self._convert_field(key, val) for val in value]
109             else:
110                 result[key] = self._convert_field(key, value)
111         return result
112
113     def add_match(self, *args, **kwargs):
114         args = list(args)
115         args.extend(_make_line(key, val) for key, val in kwargs.items())
116         super(Journal, self).add_match(*args)
117
118     def get_next(self, skip=1):
119         return self._convert_entry(
120             super(Journal, self).get_next(skip))
121
122     def query_unique(self, key):
123         return set(self._convert_field(key, value)
124             for value in super(Journal, self).query_unique(key))
125
126     def seek_realtime(self, timestamp):
127         if isinstance(timestamp, datetime.datetime):
128             timestamp = int(timestamp.strftime("%s%f"))
129         return super(Journal, self).seek_realtime(timestamp)
130
131     def seek_monotonic(self, timestamp, bootid=None):
132         if isinstance(timestamp, datetime.timedelta):
133             timestamp = timestamp.totalseconds()
134         return super(Journal, self).seek_monotonic(timestamp, bootid)
135
136     def log_level(self, level):
137         """Sets maximum log level by setting matches for PRIORITY."""
138         if 0 <= level <= 7:
139             for i in range(level+1):
140                 self.add_match(PRIORITY="%s" % i)
141         else:
142             raise ValueError("Log level must be 0 <= level <= 7")
143
144     def this_boot(self):
145         """Add match for _BOOT_ID equal to current boot ID."""
146         self.add_match(_BOOT_ID=_id128.get_boot().hex)
147
148     def this_machine(self):
149         """Add match for _MACHINE_ID equal to the ID of this machine."""
150         self.add_match(_MACHINE_ID=_id128.get_machine().hex)
151
152 def _make_line(field, value):
153         if isinstance(value, bytes):
154                 return field.encode('utf-8') + b'=' + value
155         else:
156                 return field + '=' + value
157
158 def send(MESSAGE, MESSAGE_ID=None,
159          CODE_FILE=None, CODE_LINE=None, CODE_FUNC=None,
160          **kwargs):
161         r"""Send a message to the journal.
162
163         >>> journal.send('Hello world')
164         >>> journal.send('Hello, again, world', FIELD2='Greetings!')
165         >>> journal.send('Binary message', BINARY=b'\xde\xad\xbe\xef')
166
167         Value of the MESSAGE argument will be used for the MESSAGE=
168         field. MESSAGE must be a string and will be sent as UTF-8 to
169         the journal.
170
171         MESSAGE_ID can be given to uniquely identify the type of
172         message. It must be a string or a uuid.UUID object.
173
174         CODE_LINE, CODE_FILE, and CODE_FUNC can be specified to
175         identify the caller. Unless at least on of the three is given,
176         values are extracted from the stack frame of the caller of
177         send(). CODE_FILE and CODE_FUNC must be strings, CODE_LINE
178         must be an integer.
179
180         Additional fields for the journal entry can only be specified
181         as keyword arguments. The payload can be either a string or
182         bytes. A string will be sent as UTF-8, and bytes will be sent
183         as-is to the journal.
184
185         Other useful fields include PRIORITY, SYSLOG_FACILITY,
186         SYSLOG_IDENTIFIER, SYSLOG_PID.
187         """
188
189         args = ['MESSAGE=' + MESSAGE]
190
191         if MESSAGE_ID is not None:
192                 id = getattr(MESSAGE_ID, 'hex', MESSAGE_ID)
193                 args.append('MESSAGE_ID=' + id)
194
195         if CODE_LINE == CODE_FILE == CODE_FUNC == None:
196                 CODE_FILE, CODE_LINE, CODE_FUNC = \
197                         _traceback.extract_stack(limit=2)[0][:3]
198         if CODE_FILE is not None:
199                 args.append('CODE_FILE=' + CODE_FILE)
200         if CODE_LINE is not None:
201                 args.append('CODE_LINE={:d}'.format(CODE_LINE))
202         if CODE_FUNC is not None:
203                 args.append('CODE_FUNC=' + CODE_FUNC)
204
205         args.extend(_make_line(key, val) for key, val in kwargs.items())
206         return sendv(*args)
207
208 def stream(identifier, priority=LOG_DEBUG, level_prefix=False):
209         r"""Return a file object wrapping a stream to journal.
210
211         Log messages written to this file as simple newline sepearted
212         text strings are written to the journal.
213
214         The file will be line buffered, so messages are actually sent
215         after a newline character is written.
216
217         >>> stream = journal.stream('myapp')
218         >>> stream
219         <open file '<fdopen>', mode 'w' at 0x...>
220         >>> stream.write('message...\n')
221
222         will produce the following message in the journal::
223
224           PRIORITY=7
225           SYSLOG_IDENTIFIER=myapp
226           MESSAGE=message...
227
228         Using the interface with print might be more convinient:
229
230         >>> from __future__ import print_function
231         >>> print('message...', file=stream)
232
233         priority is the syslog priority, one of `LOG_EMERG`,
234         `LOG_ALERT`, `LOG_CRIT`, `LOG_ERR`, `LOG_WARNING`,
235         `LOG_NOTICE`, `LOG_INFO`, `LOG_DEBUG`.
236
237         level_prefix is a boolean. If true, kernel-style log priority
238         level prefixes (such as '<1>') are interpreted. See
239         sd-daemon(3) for more information.
240         """
241
242         fd = stream_fd(identifier, priority, level_prefix)
243         return _os.fdopen(fd, 'w', 1)
244
245 class JournalHandler(_logging.Handler):
246         """Journal handler class for the Python logging framework.
247
248         Please see the Python logging module documentation for an
249         overview: http://docs.python.org/library/logging.html.
250
251         To create a custom logger whose messages go only to journal:
252
253         >>> log = logging.getLogger('custom_logger_name')
254         >>> log.propagate = False
255         >>> log.addHandler(journal.JournalHandler())
256         >>> log.warn("Some message: %s", detail)
257
258         Note that by default, message levels `INFO` and `DEBUG` are
259         ignored by the logging framework. To enable those log levels:
260
261         >>> log.setLevel(logging.DEBUG)
262
263         To attach journal MESSAGE_ID, an extra field is supported:
264
265         >>> import uuid
266         >>> mid = uuid.UUID('0123456789ABCDEF0123456789ABCDEF')
267         >>> log.warn("Message with ID", extra={'MESSAGE_ID': mid})
268
269         To redirect all logging messages to journal regardless of where
270         they come from, attach it to the root logger:
271
272         >>> logging.root.addHandler(journal.JournalHandler())
273
274         For more complex configurations when using `dictConfig` or
275         `fileConfig`, specify `systemd.journal.JournalHandler` as the
276         handler class.  Only standard handler configuration options
277         are supported: `level`, `formatter`, `filters`.
278
279         The following journal fields will be sent:
280         `MESSAGE`, `PRIORITY`, `THREAD_NAME`, `CODE_FILE`, `CODE_LINE`,
281         `CODE_FUNC`, `LOGGER` (name as supplied to getLogger call),
282         `MESSAGE_ID` (optional, see above).
283         """
284
285         def emit(self, record):
286                 """Write record as journal event.
287
288                 MESSAGE is taken from the message provided by the
289                 user, and PRIORITY, LOGGER, THREAD_NAME,
290                 CODE_{FILE,LINE,FUNC} fields are appended
291                 automatically. In addition, record.MESSAGE_ID will be
292                 used if present.
293                 """
294                 try:
295                         msg = self.format(record)
296                         pri = self.mapPriority(record.levelno)
297                         mid = getattr(record, 'MESSAGE_ID', None)
298                         send(msg,
299                              MESSAGE_ID=mid,
300                              PRIORITY=format(pri),
301                              LOGGER=record.name,
302                              THREAD_NAME=record.threadName,
303                              CODE_FILE=record.pathname,
304                              CODE_LINE=record.lineno,
305                              CODE_FUNC=record.funcName)
306                 except Exception:
307                         self.handleError(record)
308
309         @staticmethod
310         def mapPriority(levelno):
311                 """Map logging levels to journald priorities.
312
313                 Since Python log level numbers are "sparse", we have
314                 to map numbers in between the standard levels too.
315                 """
316                 if levelno <= _logging.DEBUG:
317                         return LOG_DEBUG
318                 elif levelno <= _logging.INFO:
319                         return LOG_INFO
320                 elif levelno <= _logging.WARNING:
321                         return LOG_WARNING
322                 elif levelno <= _logging.ERROR:
323                         return LOG_ERR
324                 elif levelno <= _logging.CRITICAL:
325                         return LOG_CRIT
326                 else:
327                         return LOG_ALERT