Total Complexity | 1 |
Total Lines | 41 |
Duplicated Lines | 0 % |
Coverage | 100% |
Changes | 0 |
1 | """ |
||
2 | syslog2irc.formatting |
||
3 | ~~~~~~~~~~~~~~~~~~~~~ |
||
4 | |||
5 | Message formatting |
||
6 | |||
7 | :Copyright: 2007-2021 Jochen Kupperschmidt |
||
8 | :License: MIT, see LICENSE for details. |
||
9 | """ |
||
10 | |||
11 | 1 | from __future__ import annotations |
|
12 | |||
13 | 1 | from syslogmp import Message as SyslogMessage |
|
14 | |||
15 | |||
16 | 1 | MESSAGE_TEXT_ENCODING = 'utf-8' |
|
17 | |||
18 | |||
19 | 1 | def format_message( |
|
20 | source_address: tuple[str, int], message: SyslogMessage |
||
21 | ) -> str: |
||
22 | """Format syslog message to be displayed on IRC.""" |
||
23 | 1 | source_host = source_address[0] |
|
24 | 1 | source_port = source_address[1] |
|
25 | |||
26 | 1 | timestamp_format = '%Y-%m-%d %H:%M:%S' |
|
27 | 1 | formatted_timestamp = message.timestamp.strftime(timestamp_format) |
|
28 | |||
29 | 1 | severity_name = message.severity.name |
|
30 | |||
31 | # Important: The message text is a byte string. |
||
32 | 1 | text = message.message.decode(MESSAGE_TEXT_ENCODING) |
|
33 | |||
34 | # Remove leading and trailing newlines. Those would result in |
||
35 | # additional lines on IRC with the usual metadata but with an |
||
36 | # empty message text. |
||
37 | 1 | text = text.strip('\n') |
|
38 | |||
39 | 1 | return ( |
|
40 | f'{source_host}:{source_port:d} ' |
||
41 | f'[{formatted_timestamp}] ' |
||
45 |