Python日志配置类
# -*- coding: utf-8 -* """日志工具类 author: Jill usage: from common.logger import Log log = Log().get_logger() log.error("error occurred when xxx") """ import logging import time import os cur_path = os.path.dirname(os.path.realpath(__file__)) log_path = os.path.join(os.path.dirname(cur_path), 'logs') # 如果不存在这个logs文件夹,就自动创建一个 if not os.path.exists(log_path): os.mkdir(log_path) class Log: @staticmethod def get_logger(): fmt = logging.Formatter('[%(asctime)s] [%(threadName)s] [%(levelname)s] [%(pathname)s:%(lineno)s]: %(message)s', "%Y-%m-%d %H:%M:%S") console_handler = logging.StreamHandler() console_handler.setFormatter(fmt) log_name = os.path.join(log_path, '%s.log' % time.strftime('%Y_%m_%d')) file_handler = logging.FileHandler(log_name, 'a', encoding='utf-8') # 这个是python3的 file_handler.setFormatter(fmt) logger = logging.getLogger('App') logger.setLevel(logging.DEBUG) if logger.handlers: return logger logger.addHandler(console_handler) logger.addHandler(file_handler) return logger if __name__ == "__main__": log2 = Log.get_logger() log = Log.get_logger() log2.info('test') log.info('test') log2.error('test') log.warning('test') log.debug('test')
本博客文章皆出于学习目的,个人总结或摘抄整理自网络。引用参考部分在文章中都有原文链接,如疏忽未给出请联系本人。另外,作为一名菜鸟程序媛,如文章内容有错误,欢迎点击博客右上方的扣扣链接指导交流。