• log输出到日志和控制台


    新增Log类,输出日志到文件

    import os
    import logging
    
    PATH = lambda p: os.path.abspath(
        os.path.join(os.path.dirname(__file__), p)
    )
    
    class Log(object):
        """
        log类
        """
        def __init__(self):
            global logger, logPath, resultPath
            resultPath = PATH('../logs')
            # logPath = os.path.join(resultPath, time.strftime('%Y%m%d%H%M%S', time.localtime()))
    
            # if not os.path.exists(logPath):
            #     os.mkdir(logPath)
            if not os.path.exists(resultPath):
                os.mkdir(resultPath)
    
            # 创建logger,设置日志等级
            # DEBUG INFO WARNING ERROR CRITICAL等级依次递增
            self.logger = logging.getLogger()
            self.logger.setLevel(logging.INFO)
    
            # 创建handler,输出日志到文件
            # fh = logging.FileHandler(os.path.join(logPath, 'outPut.log'), encoding='utf-8', mode='a')
            fh = logging.FileHandler(os.path.join(resultPath, 'outPut.log'), encoding='utf-8', mode='a')
            formatter = logging.Formatter('%(asctime)s  - %(levelname)s - %(message)s')
            fh.setFormatter(formatter)
    
            # 创建handler,输出日志到terminal
            ch = logging.StreamHandler()
            formatter = logging.Formatter('%(asctime)s  - %(levelname)s - %(message)s')
            ch.setFormatter(formatter)
    
            # if str(self.logger.handlers) == '[]':
            if not self.logger.handlers:
                self.logger.addHandler(fh)
                self.logger.addHandler(ch)
            else:
                self.logger.info('log handler已存在')
    
            ch.close()
            fh.close()
    
        def getLogger(self):
            """
            get logger
            :return:
            """
            return self.logger
    
    if __name__ == '__main__':
        my_log = Log()
        my_log.logger.info('test info')
    
  • 相关阅读:
    C计算double能精确到多少位
    C计算int最大值、最小值
    AndroidStudio右键new无activity
    java替换特殊字符串 $
    lamda表达式排序
    docker toolbox 设置镜像加速
    tomcat优化
    nginx配置相关
    SQL 优化
    elasticsearch 概念初识
  • 原文地址:https://www.cnblogs.com/Jerry165/p/13560989.html
Copyright © 2020-2023  润新知