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