Completed
Pull Request — master (#2409)
by
unknown
01:51
created

LogPrinter.__getstate__()   A

Complexity

Conditions 1

Size

Total Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 1
dl 0
loc 5
rs 9.4285
c 1
b 0
f 0
1
import traceback
2
import logging
3
4
from pyprint.ColorPrinter import ColorPrinter
5
6
from coalib.output.printers.LOG_LEVEL import LOG_LEVEL
7
from coalib.processes.communication.LogMessage import LogMessage
8
9
10
class LogPrinter:
11
    """
12
    This class is deprecated and will be soon removed. To get logger use
13
    logging.getLogger('coala.colored') for colored logger and
14
    logging.getLogger('coala.raw') for not colored logger.
15
16
    The LogPrinter class allows to print log messages to an underlying Printer.
17
18
    This class is an adapter, means you can create a LogPrinter from every
19
    existing Printer instance.
20
    """
21
22
    def __init__(self,
23
                 printer=None,
24
                 log_level=LOG_LEVEL.INFO,
25
                 timestamp_format="%X"):
26
        """
27
        Creates a new log printer from an existing Printer.
28
29
        :param printer:          The underlying Printer where log messages
30
                                 shall be written to. If you inherit from
31
                                 LogPrinter, set it to self.
32
        :param log_level:        The minimum log level, everything below will
33
                                 not be logged.
34
        :param timestamp_format: The format string for the
35
                                 datetime.today().strftime(format) method.
36
        """
37
        if isinstance(printer, ColorPrinter):
38
            self.logger_name = 'coala.colored'
39
        else:
40
            self.logger_name = 'coala.raw'
41
        self.logger = logging.getLogger(self.logger_name)
42
43
        self._printer = printer
44
        self.log_level = log_level
45
        self.timestamp_format = timestamp_format
46
47
    @property
48
    def log_level(self):
49
        """
50
        Returns current log_level used is logger.
51
        """
52
        return self._log_level
53
54
    @log_level.setter
55
    def log_level(self, log_level):
56
        """
57
        Sets log_level for logger.
58
        """
59
        self._log_level = log_level
60
        self.logger.setLevel(log_level)
61
62
    @property
63
    def printer(self):
64
        """
65
        Returns the underlying printer where logs are printed to.
66
        """
67
        return self._printer
68
69
    def debug(self, *messages, delimiter=" ", timestamp=None, **kwargs):
70
        self.log_message(LogMessage(LOG_LEVEL.DEBUG,
71
                                    *messages,
72
                                    delimiter=delimiter,
73
                                    timestamp=timestamp),
74
                         **kwargs)
75
76
    def info(self, *messages, delimiter=" ", timestamp=None, **kwargs):
77
        self.log_message(LogMessage(LOG_LEVEL.INFO,
78
                                    *messages,
79
                                    delimiter=delimiter,
80
                                    timestamp=timestamp),
81
                         **kwargs)
82
83
    def warn(self, *messages, delimiter=" ", timestamp=None, **kwargs):
84
        self.log_message(LogMessage(LOG_LEVEL.WARNING,
85
                                    *messages,
86
                                    delimiter=delimiter,
87
                                    timestamp=timestamp),
88
                         **kwargs)
89
90
    def err(self, *messages, delimiter=" ", timestamp=None, **kwargs):
91
        self.log_message(LogMessage(LOG_LEVEL.ERROR,
92
                                    *messages,
93
                                    delimiter=delimiter,
94
                                    timestamp=timestamp),
95
                         **kwargs)
96
97
    def log(self, log_level, message, timestamp=None, **kwargs):
98
        self.log_message(LogMessage(log_level,
99
                                    message,
100
                                    timestamp=timestamp),
101
                         **kwargs)
102
103
    def log_exception(self,
104
                      message,
105
                      exception,
106
                      log_level=LOG_LEVEL.ERROR,
107
                      timestamp=None,
108
                      **kwargs):
109
        """
110
        If the log_level of the printer is greater than DEBUG, it prints
111
        only the message. If it is DEBUG or lower, it shows the message
112
        along with the traceback of the exception.
113
114
        :param message:   The message to print.
115
        :param exception: The exception to print.
116
        :param log_level: The log_level of this message (not used when
117
                          logging the traceback. Tracebacks always have
118
                          a level of DEBUG).
119
        :param timestamp: The time at which this log occured. Defaults to
120
                          the current time.
121
        :param kwargs:    Keyword arguments to be passed when logging the
122
                          message (not used when logging the traceback).
123
        """
124
        if not isinstance(exception, BaseException):
125
            raise TypeError("log_exception can only log derivatives of "
126
                            "BaseException.")
127
128
        traceback_str = "\n".join(
129
            traceback.format_exception(type(exception),
130
                                       exception,
131
                                       exception.__traceback__))
132
133
        self.log(log_level, message, timestamp=timestamp, **kwargs)
134
        self.log_message(
135
            LogMessage(LOG_LEVEL.DEBUG,
136
                       "Exception was:" + "\n" + traceback_str,
137
                       timestamp=timestamp),
138
            **kwargs)
139
140
    def log_message(self, log_message, **kwargs):
141
        if not isinstance(log_message, LogMessage):
142
            raise TypeError("log_message should be of type LogMessage.")
143
        self.logger.log(log_message.log_level, log_message.message)
144
145
    def __getstate__(self):
146
        # on Windows there are problems with serializing loggers, so omit it
147
        oldict = self.__dict__.copy()
148
        del oldict['logger']
149
        return oldict
150
151
    def __setstate__(self, newdict):
152
        self.__dict__.update(newdict)
153
        # restore logger by name
154
        self.logger = logging.getLogger(self.logger_name)
155