python日志logging模块使用

“只要log打的好,没有bug解不了”

【参考链接:https://www.jb51.net/article/63502.htm

信息级别:notset < debug < info < warn < error < critical

>>> log文件里的内容是默认追加的,每次执行程序的产生的日志都会存在日志文件里,不会覆盖。

logging模块介绍:

Python的logging模块提供了通用的日志系统,熟练使用logging模块可以方便开发者开发第三方模块或者是自己的Python应用。同样这个模块提供不同的日志级别,并可以采用不同的方式记录日志,比如文件,HTTP、GET/POST,SMTP,Socket等,甚至可以自己实现具体的日志记录方式。下文将主要介绍如何使用文件方式记录log。

logging模块包括logger,handler,filter,formatter这四个基本概念。

logger:提供日志接口,供应用代码使用。logger最长用的操作有两类:配置和发送日志消息。可以通过logging.getLogger(name)获取logger对象,如果不指定name则返回root对象,多次使用相同的name调用getLogger方法返回同一个logger对象。
handler:将日志记录(log record)发送到合适的目的地(destination),比如文件,socket等。一个logger对象可以通过addHandler方法添加0到多个handler,每个handler又可以定义不同日志级别,以实现日志分级过滤显示。
filter:提供一种优雅的方式决定一个日志记录是否发送到handler。
formatter:指定日志记录输出的具体格式。formatter的构造方法需要两个参数:消息的格式字符串日期字符串,这两个参数都是可选的。

基本使用方法:

一些小型的程序我们不需要构造太复杂的log系统,直接使用logging模块的basicConfig函数即可,代码如下:

import logging
 
log_file = "./basic_logger.log"
logging.basicConfig(filename = log_file, level = logging.DEBUG)
 
logging.debug("this is a debug msg!")
logging.info("this is a info msg!")
logging.warn("this is a warn msg!")
logging.error("this is a error msg!")
logging.critical("this is a critical msg!")

运行程序时我们就会在该文件的当前目录下发现basic_logger.log文件,查看basic_logger.log内容如下:

INFO:root:this is a info msg!
DEBUG:root:this is a debug msg!
WARNING:root:this is a warn msg!
ERROR:root:this is a error msg!
CRITICAL:root:this is a critical msg!

需要说明的是,将level设定为DEBUG级别,所以log日志中只显示了包含该级别及该级别以上的log信息。如果在多个模块中使用这个配置的话,只需在主模块中配置即可,其他模块会有相同的使用效果。

较高级版本:

上述的基础使用比较简单,没有显示出logging模块的厉害,适合小程序用,现在我介绍一个较高级版本的代码,我们需要依次设置logger、handler、formatter等配置。

import logging
 
log_file = "./nomal_logger.log"
log_level = logging.DEBUG
 
logger = logging.getLogger("loggingmodule.NomalLogger")
handler = logging.FileHandler(log_file)
formatter = logging.Formatter("[%(levelname)s][%(funcName)s][%(asctime)s]%(message)s")
 
handler.setFormatter(formatter)
logger.addHandler(handler)
logger.setLevel(log_level)
 
#test
logger.debug("this is a debug msg!")
logger.info("this is a info msg!")
logger.warn("this is a warn msg!")
logger.error("this is a error msg!")
logger.critical("this is a critical msg!")

这时我们查看当前目录的nomal_logger.log日志文件,内容如下:

[DEBUG][][2012-08-12 17:43:59,295]this is a debug msg!
[INFO][][2012-08-12 17:43:59,295]this is a info msg!
[WARNING][][2012-08-12 17:43:59,295]this is a warn msg!
[ERROR][][2012-08-12 17:43:59,295]this is a error msg!
[CRITICAL][][2012-08-12 17:43:59,295]this is a critical msg!

这个对照前面介绍的logging模块,不难理解,下面的最终版本将会更加完整。

完善版本:

这个最终版本cai用singleton设计模式来写一个Logger类,代码如下:

 
import logging.handlers
 
class FinalLogger:
    logger = None
 
    levels = {"n" : logging.NOTSET,
      "d" : logging.DEBUG,
      "i" : logging.INFO,
      "w" : logging.WARN,
      "e" : logging.ERROR,
      "c" : logging.CRITICAL}
 
    log_level = "d"
    log_file = "final_logger.log"
    log_max_byte = 10 * 1024 * 1024;
    log_backup_count = 5
 
    @staticmethod
    def getLogger():
        if FinalLogger.logger is not None:
            return FinalLogger.logger
 
    FinalLogger.logger = logging.Logger("oggingmodule.FinalLogger")
    log_handler = logging.handlers.RotatingFileHandler(filename = FinalLogger.log_file,\
                                                       maxBytes = FinalLogger.log_max_byte,\
                                                       backupCount = FinalLogger.log_backup_count)
    log_fmt = logging.Formatter("[%(levelname)s][%(funcName)s][%(asctime)s]%(message)s")
    log_handler.setFormatter(log_fmt)
    FinalLogger.logger.addHandler(log_handler)
    FinalLogger.logger.setLevel(FinalLogger.levels.get(FinalLogger.log_level))
    return FinalLogger.logger
 
if __name__ == "__main__":
logger = FinalLogger.getLogger() logger.debug("this is a debug msg!") logger.info("this is a info msg!") logger.warn("this is a warn msg!") logger.error("this is a error msg!") logger.critical("this is a critical msg!")

当前目录下的 final_logger.log内容如下:

[DEBUG][][2012-08-12 18:12:23,029]this is a debug msg!
[INFO][][2012-08-12 18:12:23,029]this is a info msg!
[WARNING][][2012-08-12 18:12:23,029]this is a warn msg!
[ERROR][][2012-08-12 18:12:23,029]this is a error msg!
[CRITICAL][][2012-08-12 18:12:23,029]this is a critical msg!

  

猜你喜欢

转载自www.cnblogs.com/skzxc/p/12771284.html