孤坟丶

导航

 

1. loggin模块的5个级别:

# logging.debug('debug message')      # 调试
# logging.info('info message')        # 普通信息
# logging.warning('warning message')  # 警告
# logging.error('error message')      # 错误信息
# logging.critical('critical message')# 严重错误

# 默认情况下 不打印warning以下级别的信息
View Code

2. loggin模块的简单使用

logging.basicConfig(level=logging.DEBUG,
                     format='%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s',
                     datefmt='%a, %d %b %Y %H:%M:%S')
View Code

 此方法的缺点:

   1.中文显示乱码
   2.不能同时输出到文件和屏幕

3.logger对象的方式来使用logging模块
import logging


logger = logging.getLogger()   # 首先 先创建logger对象
logger.setLevel(logging.DEBUG)  #设置显示级别

fh = logging.FileHandler('log',encoding='utf-8')# 第二 创建一个文件操作符


sh = logging.StreamHandler()# 第三 创建一个屏幕操作符


fmt = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')# 第四 创建一个格式


logger.addHandler(fh)#第五 logger 绑定 文件操作符

logger.addHandler(sh)#第六 logger 绑定 屏幕操作符

fh.setFormatter(fmt)#第七 文件操作符 绑定格式

sh.setFormatter(fmt)#第八 屏幕操作符 绑定格式

logger.debug('logger debug message')
logger.info('logger info message')
logger.warning('logger warning message')
logger.error('logger error message')
logger.critical('logger critical message')
View Code

 

4. 面向对象:loggin的单例模式

 

import logging


class Log(object):
    def __init__(self, level=logging.DEBUG):
        logger = logging.getLogger()
        logger.setLevel(level)
        fh = logging.FileHandler('test.log', encoding='utf-8')
        ch = logging.StreamHandler()
        formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
        fh.setFormatter(formatter)
        ch.setFormatter(formatter)
        logger.addHandler(fh)
        logger.addHandler(ch)
        self.logger = logger


log = Log()
log.logger.info("wahaha01")
log = Log()
log.logger.info("wahaha02")
log = Log()
log.logger.info("wahaha03")
View Code

 

当执行上面代码时, 输出结果如图: 

 

 这是由于,其源码中运用了单例模式

想要解决这种情况, 就需要自己重写一个单例模式, 如下代码:

class Log(object):
    __instance = None
    def __new__(cls, *args, **kwargs):
        if not cls.__instance:
            cls.__instance = super().__new__(cls)
        return cls.__instance

    def __init__(self,level = logging.DEBUG):
        if 'logger' not in self.__dict__:
            logger = logging.getLogger()
            logger.setLevel(level)
            fh = logging.FileHandler('test.log', encoding='utf-8')
            ch = logging.StreamHandler()
            formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
            fh.setFormatter(formatter)
            ch.setFormatter(formatter)
            logger.addHandler(fh)
            logger.addHandler(ch)
            self.logger = logger

log = Log()
log.logger.info("wahaha01")
log = Log()
log.logger.info("wahaha02")
log = Log()
log.logger.info("wahaha03")
View Code

输出结果为:

 

 

 

 
posted on 2019-04-15 17:49  孤坟丶  阅读(163)  评论(0编辑  收藏  举报