1 # -*- Mode: python; coding:utf-8; indent-tabs-mode: nil -*- */
3 # This file is part of systemd.
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>
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.
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.
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/>.
22 import traceback as _traceback
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
29 def _make_line(field, value):
30 if isinstance(value, bytes):
31 return field.encode('utf-8') + b'=' + value
33 return field + '=' + value
35 def send(MESSAGE, MESSAGE_ID=None,
36 CODE_FILE=None, CODE_LINE=None, CODE_FUNC=None,
38 r"""Send a message to journald.
40 >>> journal.send('Hello world')
41 >>> journal.send('Hello, again, world', FIELD2='Greetings!')
42 >>> journal.send('Binary message', BINARY=b'\xde\xad\xbe\xef')
44 Value of the MESSAGE argument will be used for the MESSAGE=
47 MESSAGE_ID can be given to uniquely identify the type of
50 Other parts of the message can be specified as keyword
53 Both MESSAGE and MESSAGE_ID, if present, must be strings, and
54 will be sent as UTF-8 to journal. Other arguments can be
55 bytes, in which case they will be sent as-is to journal.
57 CODE_LINE, CODE_FILE, and CODE_FUNC can be specified to
58 identify the caller. Unless at least on of the three is given,
59 values are extracted from the stack frame of the caller of
60 send(). CODE_FILE and CODE_FUNC must be strings, CODE_LINE
63 Other useful fields include PRIORITY, SYSLOG_FACILITY,
64 SYSLOG_IDENTIFIER, SYSLOG_PID.
67 args = ['MESSAGE=' + MESSAGE]
69 if MESSAGE_ID is not None:
70 args.append('MESSAGE_ID=' + MESSAGE_ID)
72 if CODE_LINE == CODE_FILE == CODE_FUNC == None:
73 CODE_FILE, CODE_LINE, CODE_FUNC = \
74 _traceback.extract_stack(limit=2)[0][:3]
75 if CODE_FILE is not None:
76 args.append('CODE_FILE=' + CODE_FILE)
77 if CODE_LINE is not None:
78 args.append('CODE_LINE={:d}'.format(CODE_LINE))
79 if CODE_FUNC is not None:
80 args.append('CODE_FUNC=' + CODE_FUNC)
82 args.extend(_make_line(key, val) for key, val in kwargs.items())
85 def stream(identifier, priority=LOG_DEBUG, level_prefix=False):
86 r"""Return a file object wrapping a stream to journal.
88 Log messages written to this file as simple newline sepearted
89 text strings are written to the journal.
91 The file will be line buffered, so messages are actually sent
92 after a newline character is written.
94 >>> stream = journal.stream('myapp')
96 <open file '<fdopen>', mode 'w' at 0x...>
97 >>> stream.write('message...\n')
99 will produce the following message in the journal:
102 SYSLOG_IDENTIFIER=myapp
105 Using the interface with print might be more convinient:
107 >>> from __future__ import print_function
108 >>> print('message...', file=stream)
110 priority is the syslog priority, one of LOG_EMERG, LOG_ALERT,
111 LOG_CRIT, LOG_ERR, LOG_WARNING, LOG_NOTICE, LOG_INFO, LOG_DEBUG.
113 level_prefix is a boolean. If true, kernel-style log priority
114 level prefixes (such as '<1>') are interpreted. See
115 sd-daemon(3) for more information.
118 fd = stream_fd(identifier, priority, level_prefix)
119 return _os.fdopen(fd, 'w', 1)
121 class JournalHandler(_logging.Handler):
122 """Journal handler class for the Python logging framework.
124 Please see the Python logging module documentation for an
125 overview: http://docs.python.org/library/logging.html.
127 To create a custom logger whose messages go only to journal:
129 >>> log = logging.getLogger('custom_logger_name')
130 >>> log.propagate = False
131 >>> log.addHandler(journal.JournalHandler())
132 >>> log.warn("Some message: %s", detail)
134 Note that by default, message levels INFO and DEBUG are ignored
135 by the logging framework. To enable those log levels:
137 >>> log.setLevel(logging.DEBUG)
139 To attach journal MESSAGE_ID, an extra field is supported:
141 >>> log.warn("Message with ID",
142 >>> extra={'MESSAGE_ID': '22bb01335f724c959ac4799627d1cb61'})
144 To redirect all logging messages to journal regardless of where
145 they come from, attach it to the root logger:
147 >>> logging.root.addHandler(journal.JournalHandler())
149 For more complex configurations when using dictConfig or
150 fileConfig, specify 'systemd.journal.JournalHandler' as the
151 handler class. Only standard handler configuration options
152 are supported: level, formatter, filters.
154 The following journal fields will be sent:
156 MESSAGE, PRIORITY, THREAD_NAME, CODE_FILE, CODE_LINE,
157 CODE_FUNC, LOGGER (name as supplied to getLogger call),
158 MESSAGE_ID (optional, see above).
161 def emit(self, record):
162 """Write record as journal event.
164 MESSAGE is taken from the message provided by the
165 user, and PRIORITY, LOGGER, THREAD_NAME,
166 CODE_{FILE,LINE,FUNC} fields are appended
167 automatically. In addition, record.MESSAGE_ID will be
171 msg = self.format(record)
172 pri = self.mapPriority(record.levelno)
173 mid = getattr(record, 'MESSAGE_ID', None)
176 PRIORITY=format(pri),
178 THREAD_NAME=record.threadName,
179 CODE_FILE=record.pathname,
180 CODE_LINE=record.lineno,
181 CODE_FUNC=record.funcName)
183 self.handleError(record)
186 def mapPriority(levelno):
187 """Map logging levels to journald priorities.
189 Since Python log level numbers are "sparse", we have
190 to map numbers in between the standard levels too.
192 if levelno <= _logging.DEBUG:
194 elif levelno <= _logging.INFO:
196 elif levelno <= _logging.WARNING:
198 elif levelno <= _logging.ERROR:
200 elif levelno <= _logging.CRITICAL: