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