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