Failed Conditions
Pull Request — master (#1152)
by Lasse
03:36
created

coalib.processes.communication.LogMessage   A

Complexity

Total Complexity 9

Size/Duplication

Total Lines 44
Duplicated Lines 0 %
Metric Value
dl 0
loc 44
rs 10
wmc 9
1
from datetime import datetime
2
3
from coalib.output.printers.LOG_LEVEL import LOG_LEVEL
4
5
6
class LogMessage:
7
    def __init__(self,
8
                 log_level,
9
                 *messages,
10
                 delimiter=" ",
11
                 timestamp=None):
12
        if log_level not in LOG_LEVEL.reverse:
13
            raise ValueError("log_level has to be a valid LOG_LEVEL.")
14
15
        str_messages = [str(message) for message in messages]
16
        self.message = str(delimiter).join(str_messages).rstrip()
17
        if self.message == "":
18
            raise ValueError("Empty log messages are not allowed.")
19
20
        self.log_level = log_level
21
        self.timestamp = timestamp or datetime.today()
22
23
    def __str__(self):
24
        log_level = LOG_LEVEL.reverse.get(self.log_level, "ERROR")
25
        return '[{}] {}'.format(log_level, self.message)
26
27
    def __eq__(self, other):
28
        return (isinstance(other, LogMessage) and
29
                other.log_level == self.log_level and
30
                other.message == self.message)
31
32
    def __ne__(self, other):
33
        return not self.__eq__(other)
34
35
    def to_string_dict(self):
36
        """
37
        Makes a dictionary which has all keys and values as strings and
38
        contains all the data that the LogMessage has.
39
40
        :return: Dictionary with keys and values as string.
41
        """
42
        retval = {}
43
44
        retval["message"] = str(self.message)
45
        retval["timestamp"] = ("" if self.timestamp == None
46
                               else self.timestamp.isoformat())
47
        retval["log_level"] = str(LOG_LEVEL.reverse.get(self.log_level, ""))
48
49
        return retval
50