logging.py 2.6 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
18
19
20
21
22
23
24
25
26


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
27
28
29
30
31
32
33
34
35
36
37
38
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.
        """
39
40
41
        formatter = logging.Formatter(
            '[%(asctime)s %(hostname)s:%(process)d][%(filename)s:%(lineno)s][%(levelname)s] %(message)s'
        )
Yifan Xiong's avatar
Yifan Xiong committed
42
43
        if color:
            formatter = colorlog.ColoredFormatter(
44
                '[%(cyan)s%(asctime)s %(hostname)s:%(process)d%(reset)s]'
Yifan Xiong's avatar
Yifan Xiong committed
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
                '[%(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)

60
    @staticmethod
Yifan Xiong's avatar
Yifan Xiong committed
61
    def create_logger(name, level=logging.INFO):
62
63
64
        """Create logger instance with customized format.

        Args:
Yifan Xiong's avatar
Yifan Xiong committed
65
66
            name (str): Logger name.
            level (int): Logging level. Defaults to logging.INFO.
67
68

        Return:
Yifan Xiong's avatar
Yifan Xiong committed
69
            Logger: logger with the specified name, level and adapters.
70
71
72
        """
        logger = logging.getLogger(name)
        logger.setLevel(level)
Yifan Xiong's avatar
Yifan Xiong committed
73
        SuperBenchLogger.add_handler(logger, stream=sys.stdout, color=True)
74
75
76
77
78
        logger = LoggerAdapter(logger, extra={'hostname': socket.gethostname()})

        return logger


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