logging.py 2.56 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
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
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.
        """
        formatter = logging.Formatter('[%(asctime)s %(hostname)s][%(filename)s:%(lineno)s][%(levelname)s] %(message)s')
        if color:
            formatter = colorlog.ColoredFormatter(
                '[%(cyan)s%(asctime)s %(hostname)s%(reset)s]'
                '[%(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)

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

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

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

        return logger


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