python单例模式实现日志记录(logging模块应用)

通过单例模块实现日志记录,代码如下:

import logging

class Logger(object):
    def __init__(self):
        self.log_file_path = "./test.log"
        file_handler = logging.FileHandler(self.log_file_path, 'a', encoding='utf-8')
        file_handler.setFormatter(logging.Formatter(fmt="%(asctime)s - %(name)s - %(levelname)s - %(filename)s[line: %(lineno)d] :  %(message)s"))

        self.logger = logging.Logger('cmdb', level=logging.INFO)
        self.logger.addHandler(file_handler)


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

logger = Logger()

日志记录的变量请参考: https://www.jianshu.com/p/d5ed1d5bc976 #十二、logging模块

引用:

from .logger import logger

if __name__ == '__main__':
    logger.info("hello world")

日志输出:

2018-10-22 12:24:37,510 - cmdb - INFO - logger.py[line: 16] :  hello world
2018-10-22 12:26:18,157 - cmdb - ERROR - logger.py[line: 18] :  hello world
2018-10-22 14:00:05,689 - cmdb - ERROR - logger.py[line: 19] :  hello world
上一篇:第1天,Python入门


下一篇:Memcached工作原理