• logging 日志封装


    记录一种日志封装

    logger.py

    import os
    import logging
    
    
    class AppLogger:
        def __init__(self, name, level=logging.DEBUG, stdout=False, tofile=None):
            # 创建一个logger
            self.logger = logging.Logger(name)
            self.logger.setLevel(level)
    
            # 定义日志输出格式
            formatter = logging.Formatter('%(asctime)s [%(levelname)5s] %(filename)s:%(lineno)d %(message)s')
    
            if tofile:
                # 创建一个handler,用于写入日志文件
                log_path = os.path.join(tofile)
                fh = logging.FileHandler(log_path)
                fh.setFormatter(formatter)
                self.logger.addHandler(fh)
    
            if stdout:
                # 再创建一个handler,用于输出到控制台
                ch = logging.StreamHandler()
                ch.setFormatter(formatter)
                self.logger.addHandler(ch)
    
        def getlog(self):
            return self.logger
    
    
    if __name__ == '__main__':
        applog = AppLogger('applog', stdout=True).getlog()
        applog.info('this is a info log')
    
    

    引用

    api.py

    from logger import AppLogger
    
    LOGLVL = logging.DEBUG
    logger = AppLogger("autotest", LOGLVL, True, "migration.log").getlog()
    
    logger.error('error, export file not found')
    
    
  • 相关阅读:
    Redis学习
    MySQL索引
    细数 Java 线程池的原理
    红黑树学习
    HashMap学习
    Java集合框架
    Java性能优化的45个细节
    MyBatis理解
    jenkins+git+maven+tomcat+jdk本地部署windows版
    windows版docker安装nginx,并设置目录挂载
  • 原文地址:https://www.cnblogs.com/hanfe1/p/16630696.html
Copyright © 2020-2023  润新知