1 import traceback as _traceback
3 from syslog import (LOG_EMERG, LOG_ALERT, LOG_CRIT, LOG_ERR,
4 LOG_WARNING, LOG_NOTICE, LOG_INFO, LOG_DEBUG)
5 from ._journal import sendv, stream_fd
7 def _make_line(field, value):
8 if isinstance(value, bytes):
9 return field.encode('utf-8') + b'=' + value
11 return field + '=' + value
13 def send(MESSAGE, MESSAGE_ID=None,
14 CODE_FILE=None, CODE_LINE=None, CODE_FUNC=None,
16 r"""Send a message to journald.
18 >>> journal.send('Hello world')
19 >>> journal.send('Hello, again, world', FIELD2='Greetings!')
20 >>> journal.send('Binary message', BINARY=b'\xde\xad\xbe\xef')
22 Value of the MESSAGE argument will be used for the MESSAGE= field.
24 MESSAGE_ID can be given to uniquely identify the type of message.
26 Other parts of the message can be specified as keyword arguments.
28 Both MESSAGE and MESSAGE_ID, if present, must be strings, and will
29 be sent as UTF-8 to journal. Other arguments can be bytes, in
30 which case they will be sent as-is to journal.
32 CODE_LINE, CODE_FILE, and CODE_FUNC can be specified to identify
33 the caller. Unless at least on of the three is given, values are
34 extracted from the stack frame of the caller of send(). CODE_FILE
35 and CODE_FUNC must be strings, CODE_LINE must be an integer.
37 Other useful fields include PRIORITY, SYSLOG_FACILITY,
38 SYSLOG_IDENTIFIER, SYSLOG_PID.
41 args = ['MESSAGE=' + MESSAGE]
43 if MESSAGE_ID is not None:
44 args.append('MESSAGE_ID=' + MESSAGE_ID)
46 if CODE_LINE == CODE_FILE == CODE_FUNC == None:
47 CODE_FILE, CODE_LINE, CODE_FUNC = \
48 _traceback.extract_stack(limit=2)[0][:3]
49 if CODE_FILE is not None:
50 args.append('CODE_FILE=' + CODE_FILE)
51 if CODE_LINE is not None:
52 args.append('CODE_LINE={:d}'.format(CODE_LINE))
53 if CODE_FUNC is not None:
54 args.append('CODE_FUNC=' + CODE_FUNC)
56 args.extend(_make_line(key, val) for key, val in kwargs.items())
59 def stream(identifier, priority=LOG_DEBUG, level_prefix=False):
60 r"""Return a file object wrapping a stream to journal.
62 Log messages written to this file as simple newline sepearted
63 text strings are written to the journal.
65 The file will be line buffered, so messages are actually sent
66 after a newline character is written.
68 >>> stream = journal.stream('myapp')
70 <open file '<fdopen>', mode 'w' at 0x...>
71 >>> stream.write('message...\n')
73 will produce the following message in the journal:
76 SYSLOG_IDENTIFIER=myapp
79 Using the interface with print might be more convinient:
81 >>> from __future__ import print_function
82 >>> print('message...', file=stream)
84 priority is the syslog priority, one of LOG_EMERG, LOG_ALERT,
85 LOG_CRIT, LOG_ERR, LOG_WARNING, LOG_NOTICE, LOG_INFO, LOG_DEBUG.
87 level_prefix is a boolean. If true, kernel-style log priority
88 level prefixes (such as '<1>') are interpreted. See sd-daemon(3)
92 fd = stream_fd(identifier, priority, level_prefix)
93 return _os.fdopen(fd, 'w', 1)