Passed
Push — main ( aae69a...152cdf )
by Jochen
02:03
created

syslog2irc.formatting.format_message()   A

Complexity

Conditions 1

Size

Total Lines 27
Code Lines 13

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 12
CRAP Score 1

Importance

Changes 0
Metric Value
cc 1
eloc 13
nop 2
dl 0
loc 27
ccs 12
cts 12
cp 1
crap 1
rs 9.75
c 0
b 0
f 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 typing import Iterator, Tuple
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
24 1
    def _generate() -> Iterator[str]:
25 1
        yield f'{source_address[0]}:{source_address[1]:d} '
26
27 1
        timestamp_format = '%Y-%m-%d %H:%M:%S'
28 1
        formatted_timestamp = message.timestamp.strftime(timestamp_format)
29 1
        yield f'[{formatted_timestamp}] '
30
31 1
        yield f'({message.hostname}) '
32
33 1
        severity_name = message.severity.name
34
35
        # Important: The message text is a byte string.
36 1
        message_text = message.message.decode(MESSAGE_TEXT_ENCODING)
37
38
        # Remove leading and trailing newlines. Those would result in
39
        # additional lines on IRC with the usual metadata but with an
40
        # empty message text.
41 1
        message_text = message_text.strip('\n')
42
43 1
        yield f'[{severity_name}]: {message_text}'
44
45
    return ''.join(_generate())
46