File size: 12,573 Bytes
8c212a5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
# python3.7
"""Utility functions for logging."""

import os
import sys
import logging
from tqdm import tqdm
from rich.console import Console
from rich.logging import RichHandler
from rich.progress import Progress
from rich.progress import ProgressColumn
from rich.progress import TextColumn
from rich.progress import BarColumn
from rich.text import Text

__all__ = ['build_logger', 'Logger', 'RichLogger', 'DumbLogger']

DEFAULT_WORK_DIR = 'work_dirs'

_LOGGER_TYPES = ['normal', 'rich', 'dumb']


def build_logger(logger_type='normal', **kwargs):
    """Builds a logger.

    Supported Logger types:
        `normal`: The default logger.
        `rich`: Record messages with decoration, using `rich` module.
        `dumb`: Do NOT record any message.

    Args:
        logger_type: Type of logger, which is case insensitive.
            (default: `normal`)
        **kwargs: Additional arguments.
    """
    assert isinstance(logger_type, str)
    logger_type = logger_type.lower()
    if logger_type not in _LOGGER_TYPES:
        raise ValueError(f'Invalid logger type `{logger_type}`!\n'
                         f'Types allowed: {_LOGGER_TYPES}.')
    if logger_type == 'normal':
        return Logger(**kwargs)
    if logger_type == 'rich':
        return RichLogger(**kwargs)
    if logger_type == 'dumb':
        return DumbLogger(**kwargs)
    raise NotImplementedError(f'Not implemented logger type `{logger_type}`!')


class Logger(object):
    """Defines a logger to record log message both on screen and to file.

    The class sets up a logger with `DEBUG` log level. Two handlers will be
    added to the logger. One is the `sys.stderr` stream, with `INFO` log level,
    which will print improtant messages on the screen. The other is used to save
    all messages to file `$WORK_DIR/$LOGFILE_NAME`. Messages will be added time
    stamp and log level before logged.

    NOTE: If `logfile_name` is empty, the file stream will be skipped.
    """

    def __init__(self,
                 work_dir=DEFAULT_WORK_DIR,
                 logfile_name='log.txt',
                 logger_name='logger'):
        """Initializes the logger.

        Args:
            work_dir: The work directory. (default: DEFAULT_WORK_DIR)
            logfile_name: Name of the log file. (default: `log.txt`)
            logger_name: Unique name for the logger. (default: `logger`)
        """
        self.logger = logging.getLogger(logger_name)
        self.logger.propagate = False
        if self.logger.hasHandlers():  # Already existed
            raise SystemExit(f'Logger `{logger_name}` has already existed!\n'
                             f'Please use another name, or otherwise the '
                             f'messages from these two logger may be mixed up.')

        self.logger.setLevel(logging.DEBUG)
        formatter = logging.Formatter(
            '[%(asctime)s][%(levelname)s] %(message)s',
            datefmt='%Y-%m-%d %H:%M:%S')

        # Print log message with `INFO` level or above onto the screen.
        terminal_handler = logging.StreamHandler(stream=sys.stdout)
        terminal_handler.setLevel(logging.INFO)
        terminal_handler.setFormatter(formatter)
        self.logger.addHandler(terminal_handler)

        # Save log message with all levels into log file if needed.
        if logfile_name:
            os.makedirs(work_dir, exist_ok=True)
            self.file_stream = open(os.path.join(work_dir, logfile_name), 'a')
            file_handler = logging.StreamHandler(stream=self.file_stream)
            file_handler.setLevel(logging.DEBUG)
            file_handler.setFormatter(formatter)
            self.logger.addHandler(file_handler)

        self.log = self.logger.log
        self.debug = self.logger.debug
        self.info = self.logger.info
        self.warning = self.logger.warning
        self.error = self.logger.error
        self.exception = self.logger.exception
        self.critical = self.logger.critical

        self.pbar = []
        self.pbar_kwargs = None

    def __del__(self):
        if hasattr(self, 'file_stream'):
            self.file_stream.close()

    def print(self, *messages, **_unused_kwargs):
        """Prints messages without time stamp or log level."""
        for handler in self.logger.handlers:
            print(*messages, file=handler.stream)

    def init_pbar(self, leave=False):
        """Initializes a progress bar which will display on the screen only.

        Args:
            leave: Whether to leave the trace. (default: False)
        """
        columns = [
            '{desc}',
            '{bar}',
            ' {percentage:5.1f}%',
            '[{elapsed}<{remaining}, {rate_fmt}{postfix}]',
        ]
        self.pbar_kwargs = dict(
            leave=leave,
            bar_format=' '.join(columns),
            unit='',
        )

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

        Args:
            name: Name of the new task.
            total: Total number of steps (samples) contained in the task.

        Returns:
            The task ID.
        """
        assert isinstance(self.pbar_kwargs, dict)
        self.pbar.append(tqdm(desc=name, total=total, **self.pbar_kwargs))
        return len(self.pbar) - 1

    def update_pbar(self, task_id, advance=1):
        """Updates a certain task in the progress bar.

        Args:
            task_id: ID of the task to update.
            advance: Number of steps advanced onto the target task. (default: 1)
        """
        assert len(self.pbar) > task_id and isinstance(self.pbar[task_id], tqdm)
        if self.pbar[task_id].n < self.pbar[task_id].total:
            self.pbar[task_id].update(advance)
            if self.pbar[task_id].n >= self.pbar[task_id].total:
                self.pbar[task_id].refresh()

    def close_pbar(self):
        """Closes the progress bar"""
        for pbar in self.pbar[::-1]:
            pbar.close()
        self.pbar.clear()
        self.pbar_kwargs = None


def _format_time(seconds):
    """Formats seconds to readable time string.

    This function is used to display time in progress bar.
    """
    if not seconds:
        return '--:--'

    seconds = int(seconds)
    hours, seconds = divmod(seconds, 3600)
    minutes, seconds = divmod(seconds, 60)
    if hours:
        return f'{hours}:{minutes:02d}:{seconds:02d}'
    return f'{minutes:02d}:{seconds:02d}'


class TimeColumn(ProgressColumn):
    """Renders total time, ETA, and speed in progress bar."""

    max_refresh = 0.5  # Only refresh twice a second to prevent jitter

    def render(self, task):
        elapsed_time = _format_time(task.elapsed)
        eta = _format_time(task.time_remaining)
        speed = f'{task.speed:.2f}/s' if task.speed else '?/s'
        return Text(f'[{elapsed_time}<{eta}, {speed}]',
                    style="progress.remaining")


class RichLogger(object):
    """Defines a logger based on `rich.RichHandler`.

    Compared to the basic Logger, this logger will decorate the log message in
    a pretty format automatically.
    """

    def __init__(self,
                 work_dir=DEFAULT_WORK_DIR,
                 logfile_name='log.txt',
                 logger_name='logger'):
        """Initializes the logger.

        Args:
            work_dir: The work directory. (default: DEFAULT_WORK_DIR)
            logfile_name: Name of the log file. (default: `log.txt`)
            logger_name: Unique name for the logger. (default: `logger`)
        """
        self.logger = logging.getLogger(logger_name)
        self.logger.propagate = False
        if self.logger.hasHandlers():  # Already existed
            raise SystemExit(f'Logger `{logger_name}` has already existed!\n'
                             f'Please use another name, or otherwise the '
                             f'messages from these two logger may be mixed up.')

        self.logger.setLevel(logging.DEBUG)

        # Print log message with `INFO` level or above onto the screen.
        terminal_console = Console(
            file=sys.stderr, log_time=False, log_path=False)
        terminal_handler = RichHandler(
            level=logging.INFO,
            console=terminal_console,
            show_time=True,
            show_level=True,
            show_path=False)
        terminal_handler.setFormatter(logging.Formatter('%(message)s'))
        self.logger.addHandler(terminal_handler)

        # Save log message with all levels into log file if needed.
        if logfile_name:
            os.makedirs(work_dir, exist_ok=True)
            self.file_stream = open(os.path.join(work_dir, logfile_name), 'a')
            file_console = Console(
                file=self.file_stream, log_time=False, log_path=False)
            file_handler = RichHandler(
                level=logging.DEBUG,
                console=file_console,
                show_time=True,
                show_level=True,
                show_path=False)
            file_handler.setFormatter(logging.Formatter('%(message)s'))
            self.logger.addHandler(file_handler)

        self.log = self.logger.log
        self.debug = self.logger.debug
        self.info = self.logger.info
        self.warning = self.logger.warning
        self.error = self.logger.error
        self.exception = self.logger.exception
        self.critical = self.logger.critical

        self.pbar = None

    def __del__(self):
        if hasattr(self, 'file_stream'):
            self.file_stream.close()

    def print(self, *messages, **kwargs):
        """Prints messages without time stamp or log level."""
        for handler in self.logger.handlers:
            handler.console.print(*messages, **kwargs)

    def init_pbar(self, leave=False):
        """Initializes a progress bar which will display on the screen only.

        Args:
            leave: Whether to leave the trace. (default: False)
        """
        assert self.pbar is None

        # Columns shown in the progress bar.
        columns = (
            TextColumn("[progress.description]{task.description}"),
            BarColumn(bar_width=None),
            TextColumn("[progress.percentage]{task.percentage:>5.1f}%"),
            TimeColumn(),
        )

        self.pbar = Progress(*columns,
                             console=self.logger.handlers[0].console,
                             transient=not leave,
                             auto_refresh=True,
                             refresh_per_second=10)
        self.pbar.start()

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

        Args:
            name: Name of the new task.
            total: Total number of steps (samples) contained in the task.

        Returns:
            The task ID.
        """
        assert isinstance(self.pbar, Progress)
        task_id = self.pbar.add_task(name, total=total)
        return task_id

    def update_pbar(self, task_id, advance=1):
        """Updates a certain task in the progress bar.

        Args:
            task_id: ID of the task to update.
            advance: Number of steps advanced onto the target task. (default: 1)
        """
        assert isinstance(self.pbar, Progress)
        if self.pbar.tasks[int(task_id)].finished:
            if self.pbar.tasks[int(task_id)].stop_time is None:
                self.pbar.stop_task(task_id)
        else:
            self.pbar.update(task_id, advance=advance)

    def close_pbar(self):
        """Closes the progress bar"""
        assert isinstance(self.pbar, Progress)
        self.pbar.stop()
        self.pbar = None


class DumbLogger(object):
    """Implements a dumb logger.

    This logger also has member functions like `info()`, `warning()`, etc. But
    nothing will be logged.
    """

    def __init__(self, *_unused_args, **_unused_kwargs):
        """Initializes with dumb functions."""
        self.logger = None
        self.log = lambda *args, **kwargs: None
        self.debug = lambda *args, **kwargs: None
        self.info = lambda *args, **kwargs: None
        self.warning = lambda *args, **kwargs: None
        self.error = lambda *args, **kwargs: None
        self.exception = lambda *args, **kwargs: None
        self.critical = lambda *args, **kwargs: None
        self.print = lambda *args, **kwargs: None

        self.pbar = None
        self.init_pbar = lambda *args, **kwargs: None
        self.add_pbar_task = lambda *args, **kwargs: -1
        self.update_pbar = lambda *args, **kwargs: None
        self.close_pbar = lambda *args, **kwargs: None