File size: 9,593 Bytes
2f85de4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
# python3.7
"""Contains the base class for logging.

Basically, this is an interface bridging the program and the local file system.
A logger is able to log wrapped message onto the screen and a log file.
"""

import logging

__all__ = ['BaseLogger']


class BaseLogger(object):
    """Defines the base logger.

    A logger should have the following members:

    (1) logger: The logger to record message.
    (2) pbar: The progressive bar (shown on the screen only).
    (3) pbar_kwargs: The arguments for the progressive bar.
    (4) file_stream: The stream to log messages into if needed.

    A logger should have the following functions:

    (1) log(): The base function to log message.
    (2) debug(): The function to log message with `DEBUG` level.
    (3) info(): The function to log message with `INFO` level.
    (4) warning(): The function to log message with `WARNING` level.
    (5) warn(): Same as function `warning()`.
    (6) error(): The function to log message with `ERROR` level.
    (7) exception(): The function to log message with exception information.
    (8) critical(): The function to log message with `CRITICAL` level.
    (9) fatal(): Same as function `critical()`.
    (10) print(): The function to print the message without any decoration.
    (11) init_pbar(): The function to initialize the progressive bar.
    (12) add_pbar_task(): The function to add a task to the progressive bar.
    (13) update_pbar(): The function to update the progressive bar.
    (14) close_pbar(): The function to close the progressive bar.

    The logger will record log message both on screen and to file.

    Args:
        logger_name: Unique name for the logger. (default: `logger`)
        logfile: Path to the log file. If set as `None`, the file stream
            will be skipped. (default: `None`)
        screen_level: Minimum level of message to log onto screen.
            (default: `logging.INFO`)
        file_level: Minimum level of message to log into file.
            (default: `logging.DEBUG`)
        indent_space: Number of spaces between two adjacent indent levels.
            (default: 4)
        verbose_log: Whether to log verbose message. (default: False)
    """

    def __init__(self,
                 logger_name='logger',
                 logfile=None,
                 screen_level=logging.INFO,
                 file_level=logging.DEBUG,
                 indent_space=4,
                 verbose_log=False):
        self.logger_name = logger_name
        self.logfile = logfile
        self.screen_level = screen_level
        self.file_level = file_level
        self.indent_space = indent_space
        self.verbose_log = verbose_log

        self.logger = None
        self.pbar = None
        self.pbar_kwargs = None
        self.file_stream = None

        self.warn = self.warning
        self.fatal = self.critical

    def __del__(self):
        self.close()

    def close(self):
        """Closes the logger."""
        if self.file_stream is not None:
            self.file_stream.close()

    @property
    def name(self):
        """Returns the class name of the logger."""
        return self.__class__.__name__

    # Log message.
    def wrap_message(self, message, indent_level=0):
        """Wraps the message with indent."""
        if message is None:
            message = ''
        assert isinstance(message, str)
        assert isinstance(indent_level, int) and indent_level >= 0
        if message == '':
            return ''
        return ' ' * (indent_level * self.indent_space) + message

    def _log(self, message, **kwargs):
        """Logs wrapped message."""
        raise NotImplementedError('Should be implemented in derived class!')

    def _debug(self, message, **kwargs):
        """Logs wrapped message with `DEBUG` level."""
        raise NotImplementedError('Should be implemented in derived class!')

    def _info(self, message, **kwargs):
        """Logs wrapped message with `INFO` level."""
        raise NotImplementedError('Should be implemented in derived class!')

    def _warning(self, message, **kwargs):
        """Logs wrapped message with `WARNING` level."""
        raise NotImplementedError('Should be implemented in derived class!')

    def _error(self, message, **kwargs):
        """Logs wrapped message with `ERROR` level."""
        raise NotImplementedError('Should be implemented in derived class!')

    def _exception(self, message, **kwargs):
        """Logs wrapped message with exception information."""
        raise NotImplementedError('Should be implemented in derived class!')

    def _critical(self, message, **kwargs):
        """Logs wrapped message with `CRITICAL` level."""
        raise NotImplementedError('Should be implemented in derived class!')

    def _print(self, *messages, **kwargs):
        """Prints wrapped message without any decoration."""
        raise NotImplementedError('Should be implemented in derived class!')

    def log(self, message, indent_level=0, is_verbose=False, **kwargs):
        """Logs message.

        The message is wrapped with indent, and will be disabled if `is_verbose`
        is set as `True`.
        """
        if is_verbose and not self.verbose_log:
            return
        message = self.wrap_message(message, indent_level=indent_level)
        self._log(message, **kwargs)

    def debug(self, message, indent_level=0, is_verbose=False, **kwargs):
        """Logs message with `DEBUG` level.

        The message is wrapped with indent, and will be disabled if `is_verbose`
        is set as `True`.
        """
        if is_verbose and not self.verbose_log:
            return
        message = self.wrap_message(message, indent_level=indent_level)
        self._debug(message, **kwargs)

    def info(self, message, indent_level=0, is_verbose=False, **kwargs):
        """Logs message with `INFO` level.

        The message is wrapped with indent, and will be disabled if `is_verbose`
        is set as `True`.
        """
        if is_verbose and not self.verbose_log:
            return
        message = self.wrap_message(message, indent_level=indent_level)
        self._info(message, **kwargs)

    def warning(self, message, indent_level=0, is_verbose=False, **kwargs):
        """Logs message with `WARNING` level.

        The message is wrapped with indent, and will be disabled if `is_verbose`
        is set as `True`.
        """
        if is_verbose and not self.verbose_log:
            return
        message = self.wrap_message(message, indent_level=indent_level)
        self._warning(message, **kwargs)

    def error(self, message, indent_level=0, is_verbose=False, **kwargs):
        """Logs message with `ERROR` level.

        The message is wrapped with indent, and will be disabled if `is_verbose`
        is set as `True`.
        """
        if is_verbose and not self.verbose_log:
            return
        message = self.wrap_message(message, indent_level=indent_level)
        self._error(message, **kwargs)

    def exception(self, message, indent_level=0, is_verbose=False, **kwargs):
        """Logs message with exception information.

        The message is wrapped with indent, and will be disabled if `is_verbose`
        is set as `True`.
        """
        if is_verbose and not self.verbose_log:
            return
        message = self.wrap_message(message, indent_level=indent_level)
        self._exception(message, **kwargs)

    def critical(self, message, indent_level=0, is_verbose=False, **kwargs):
        """Logs message with `CRITICAL` level.

        The message is wrapped with indent, and will be disabled if `is_verbose`
        is set as `True`.
        """
        if is_verbose and not self.verbose_log:
            return
        message = self.wrap_message(message, indent_level=indent_level)
        self._critical(message, **kwargs)

    def print(self, *messages, indent_level=0, is_verbose=False, **kwargs):
        """Prints message without any decoration.

        The message is wrapped with indent, and will be disabled if `is_verbose`
        is set as `True`.
        """
        if is_verbose and not self.verbose_log:
            return
        new_messages = []
        for message in messages:
            new_messages.append(
                self.wrap_message(message, indent_level=indent_level))
        self._print(*new_messages, **kwargs)

    # Progressive bar.
    def init_pbar(self, leave=False):
        """Initializes the progressive bar.

        Args:
            leave: Whether to leave the trace of the progressive bar.
                (default: False)
        """
        raise NotImplementedError('Should be implemented in derived class!')

    def add_pbar_task(self, name, total, **kwargs):
        """Adds a task to the progressive bar.

        Args:
            name: Name of the added task.
            total: Total number of steps (samples) contained in the task.
            **kwargs: Additional arguments.

        Returns:
            Task ID.
        """
        raise NotImplementedError('Should be implemented in derived class!')

    def update_pbar(self, task_id, advance=1):
        """Updates the progressive bar.

        Args:
            task_id: ID of the task to update.
            advance: Number of steps advanced onto the target task. (default: 1)
        """
        raise NotImplementedError('Should be implemented in derived class!')

    def close_pbar(self):
        """Closes the progress bar."""
        raise NotImplementedError('Should be implemented in derived class!')