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

syslog2irc.formatting   A

Complexity

Total Complexity 1

Size/Duplication

Total Lines 46
Duplicated Lines 0 %

Test Coverage

Coverage 100%

Importance

Changes 0
Metric Value
eloc 17
dl 0
loc 46
ccs 15
cts 15
cp 1
rs 10
c 0
b 0
f 0
wmc 1

1 Function

Rating   Name   Duplication   Size   Complexity  
A format_message() 0 27 1
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