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