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