日志模块

from logging import getLogger, FileHandler, StreamHandler, Formatter


class Logger:

    def __init__(self, name, log_level='info', log_file=None):
        self.logger = getLogger(name)
        self.logger.setLevel(log_level)
        formatter = Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s', datefmt='%Y-%m-%d %H:%M:%S')
        if log_file:
            fh = FileHandler(log_file)
            fh.setLevel(log_level)
            self.logger.addHandler(fh)
            fh.setFormatter(formatter)
        else:
            ch = StreamHandler()
            ch.setLevel(log_level)
            self.logger.addHandler(ch)
            ch.setFormatter(formatter)

    def info(self, msg):
        self.logger.info(msg)

    def debug(self, msg):
        self.logger.debug(msg)

    def warning(self, msg):
        self.logger.warning(msg)

    def error(self, msg):
        self.logger.error(msg)

    def critical(self, msg):
        self.logger.critical(msg)

    def exception(self, msg):
        self.logger.exception(msg)


if __name__ == '__main__':
    logger = Logger('测试日志', log_level='DEBUG')
    logger.debug('test')
    logger.info('test')
    logger.warning('test')
    logger.error('test')
    logger.critical('test')
    try:
        a = 1/0
    except Exception as e:
        logger.exception(e)
    logger.info('test')

2022-04-12 22:23:34 - 测试日志 - DEBUG - test
2022-04-12 22:23:34 - 测试日志 - INFO - test
2022-04-12 22:23:34 - 测试日志 - WARNING - test
2022-04-12 22:23:34 - 测试日志 - ERROR - test
2022-04-12 22:23:34 - 测试日志 - CRITICAL - test
2022-04-12 22:23:34 - 测试日志 - ERROR - division by zero
Traceback (most recent call last):
  File "E:\python project\log.py", line 48, in <module>
    a = 1/0
ZeroDivisionError: division by zero
2022-04-12 22:23:34 - 测试日志 - INFO - test

posted @ 2022-04-15 08:15  leecy125  阅读(31)  评论(0编辑  收藏  举报