logging.py 2.78 KB
Newer Older
1
2
3
# Copyright (c) Microsoft Corporation.
# Licensed under the MIT License.

guoshzhao's avatar
guoshzhao committed
4
"""SuperBench logging module."""
5
6
7
8

import socket
import logging
import sys
Yifan Xiong's avatar
Yifan Xiong committed
9
10

import colorlog
11
12
13
14
15
16
17
# workaround to get rid of isatty from
# colorama StreamWrapper in WSL2
try:
    from colorama import deinit
    deinit()
except Exception:
    pass
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33


class LoggerAdapter(logging.LoggerAdapter):
    """LoggerAdapter class which add customized function for log error and raise exception."""
    def log_and_raise(self, exception, msg, *args):
        """Log error and raise exception.

        Args:
            exception (BaseException): Exception class.
            msg (str): logging message.
            args (dict): arguments dict for message.
        """
        self.error(msg, *args)
        raise exception(msg % args)


Yifan Xiong's avatar
Yifan Xiong committed
34
35
36
37
38
39
40
41
42
43
44
45
class SuperBenchLogger:
    """SuperBench Logger class."""
    @staticmethod
    def add_handler(logger, stream=sys.stdout, filename=None, color=False):
        """Add handler for logger.

        Args:
            logger (Logger): Logger to which the handler is added.
            stream (IO, optional): The stream that the stream handler should use. Defaults to sys.stdout.
            filename (str, optional): The filename that file handler should use. Defaults to None.
            color (bool, optional): Colored format or not. Defaults to False.
        """
46
47
48
        formatter = logging.Formatter(
            '[%(asctime)s %(hostname)s:%(process)d][%(filename)s:%(lineno)s][%(levelname)s] %(message)s'
        )
Yifan Xiong's avatar
Yifan Xiong committed
49
50
        if color:
            formatter = colorlog.ColoredFormatter(
51
                '%(reset)s'
52
                '[%(cyan)s%(asctime)s %(hostname)s:%(process)d%(reset)s]'
Yifan Xiong's avatar
Yifan Xiong committed
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
                '[%(blue)s%(filename)s:%(lineno)s%(reset)s]'
                '[%(log_color)s%(levelname)s%(reset)s] %(message)s'
            )

        handler = logging.NullHandler()
        if filename:
            # Create file handler if filename exists
            handler = logging.FileHandler(filename)
        else:
            # Create stream handler otherwise
            handler = logging.StreamHandler(stream=stream)

        handler.setFormatter(formatter)
        logger.addHandler(handler)

68
    @staticmethod
Yifan Xiong's avatar
Yifan Xiong committed
69
    def create_logger(name, level=logging.INFO):
70
71
72
        """Create logger instance with customized format.

        Args:
Yifan Xiong's avatar
Yifan Xiong committed
73
74
            name (str): Logger name.
            level (int): Logging level. Defaults to logging.INFO.
75
76

        Return:
Yifan Xiong's avatar
Yifan Xiong committed
77
            Logger: logger with the specified name, level and adapters.
78
79
80
        """
        logger = logging.getLogger(name)
        logger.setLevel(level)
Yifan Xiong's avatar
Yifan Xiong committed
81
        SuperBenchLogger.add_handler(logger, stream=sys.stdout, color=True)
82
83
84
85
86
        logger = LoggerAdapter(logger, extra={'hostname': socket.gethostname()})

        return logger


Yifan Xiong's avatar
Yifan Xiong committed
87
logger = SuperBenchLogger.create_logger('superbench')