常用模块——logging模块

logging模块

日志模块的级别分为5级,debug,info,error,warning,critical严重程度一次增高,也可由数字表示级别分别是10,20,30,40,50.

logging.debug('this is debug')
logging.info('this is info')
#默认的设置只处理和显示warning及以上的
logging.warning('this is warning')
logging.error('this is error')
logging.critical('this is critical')
#结果
#ERROR:root:this is error
#WARNING:root:this is warning
#CRITICAL:root:this is critical

这种系统默认logging的设置方法,是无法满足需要的那么现在需要定制属于自己的logging规则。

为logging模块设置全局配置,对正对所有logger优先

设定方法logging.basicConfig() 函数中可以通过具体的参数来更改logging模块的默认参数,从而改变默认行为,有下列参数:

可在logging.basicConfig()函数中可通过具体参数来更改logging模块默认行为,可用参数有
filename:用指定的文件名创建FiledHandler(后边会具体讲解handler的概念),这样日志会被存储在指定的文件中。
filemode:文件打开方式,在指定了filename时使用这个参数,默认值为“a”还可指定为“w”。
format:指定handler使用的日志显示格式。
datefmt:指定日期时间格式。
level:设置rootlogger(后边会讲解具体概念)的日志级别
stream:用指定的stream创建StreamHandler。可以指定输出到sys.stderr,sys.stdout或者文件,默认为sys.stderr。若同时列出了filename和stream两个参数,则stream参数会被忽略。

format=“”字符串中的设定方法,会为logging输出的内容。

format参数中可能用到的格式化串:
%(name)s Logger的名字
%(levelno)s 数字形式的日志级别
%(levelname)s 文本形式的日志级别
%(pathname)s 调用日志输出函数的模块的完整路径名,可能没有
%(filename)s 调用日志输出函数的模块的文件名
%(module)s 调用日志输出函数的模块名
%(funcName)s 调用日志输出函数的函数名
%(lineno)d 调用日志输出函数的语句所在的代码行
%(created)f 当前时间,用UNIX标准的表示时间的浮 点数表示
%(relativeCreated)d 输出日志信息时的,自Logger创建以 来的毫秒数
%(asctime)s 字符串形式的当前时间。默认格式是 “2003-07-08 16:49:45,896”。逗号后面的是毫秒
%(thread)d 线程ID。可能没有
%(threadName)s 线程名。可能没有
%(process)d 进程ID。可能没有
%(message)s用户输出的消息

使用演示:

logging.basicConfig(
    filename='a.log',#日志文件的路径
    # filemode='a'#默认为a追加模式,还可以修改为w覆盖写模式
    format='%(asctime)s %(name)s %(levelname)s %(message)s',
    #使用的format特定的参数,主要是靠查表来写
    datefmt='%Y-%m-%d %X %p',#时间格式定义方式
    level=10,#设定处理的级别
    # stream 默认为控制台输出,filename存在的就会忽略点stream的设置所以一般不用记忆
)
logging.debug('this is debug')
logging.info('this is info')
logging.warning('this is warning')
logging.error('this is error')
logging.critical('this is critical')

效果:

a.log 文件中

2018-10-18 15:33:17 PM root DEBUG this is debug
2018-10-18 15:33:17 PM root INFO this is info
2018-10-18 15:33:17 PM root WARNING this is warning
2018-10-18 15:33:17 PM root ERROR this is error
2018-10-18 15:33:17 PM root CRITICAL this is critical

上述设定的logging参数是正对全局的logging的参数,显然对于较大系统而言,会有不同需求的log输出需求,那么针对的自定义logging就有存在的必要。

logging中有四个对象,分别是:

1.logger(生成日志器)

2.handler(处理日志器)

3.filter(过滤日志器)

4.formatter(日志格式生成器)

一条日志完整生命周期

1.由logger产生日志——>2.交由过滤器判断是否被过滤——>将日志消息分布绑定的所有处理器——>处理器按照绑定的格式化对象输出日志

其中第一步会先检查日志级别,如果低于设置的级别则你执行。

第二步:使用场景不多,需要面向对象的技术点后续用到再讲

第四步不指定格式则按照默认格式。

对于自定义日志功能

#生成一个名为a的logger对象
logger = logging.getLogger('a')

#生成一个handler对象 由FileHandler文件处理,还有StreamHandler控制台
h1 = logging.FileHandler('b.log')
h2 = logging.FileHandler('c.log')
h3 = logging.StreamHandler()

#生成日志格式生成器
f1 = logging.Formatter('%(lineno)s %(name)s %(message)s',datefmt='%Y-%m-%d')
f2 = logging.Formatter('%(asctime)s %(message)s')

#将格式生成器帮个给Handler处理器
h1.setFormatter(f1)
h2.setFormatter(f2)
h3.setFormatter(f2)
h1.setLevel(10)
#生成器加载处理工具Handler
logger.addHandler(h1)
logger.addHandler(h2)
logger.addHandler(h3)
#调用logger模块
logger.debug('this is a bug')
logger.info('this is a info')
logger.warning('this is warning ')
logger.error('this is a error')
logger.critical('this a critical')
View Code

同时basicConfig的配置信息是为默认logger设置,他同时也会生效。

使用配置文件自定义logger功能

logger的继承(了解)

对于logger有子日志功能,

log1 = logging.getLogger("father")
log2 = logging.getLogger("father.son")
log3 = logging.getLogger("father.son.grandson")
#称log3是log2的子日志,log2是log1的子日志文件

也可以通过propagate来关闭日志文件

log3.propagate= False#关闭子日志关系

生成继承日志关系后,子日志生成一份日志,父日志也会获得相同的日志信息,

通过配置配置文件来操作logging设置

在规范目录下的实现

配置文件logcfg.py

standard_format = "%(name)s %(asctime)s %(levelname)s %(module)s %(funcName)s %(lineno)s %(message)s"
simple_format = "%(name)s %(asctime)s  %(module)s  %(message)s"
complete_format = "%(asctime)s %(levelname)s %(funcName)s %(lineno)s %(thread)s %(process)s %(message)s"
logfile_path = r"D:\上海python全栈4期\day22\代码\log\d.log"

LOGGING_DIC = {
    'version': 1,
    'formatters': {
        'standard': {
            'format': standard_format
        },
        'simple': {
            'format': simple_format
        },
        "complete":{
            "format": complete_format
        }
    },
    'filters': {},
    'handlers': {
        'console': {
            'level': 'DEBUG',
            'class': 'logging.StreamHandler',
            'formatter': 'simple'
        },
        'default': {
            'level': 'DEBUG',
            'class': 'logging.handlers.RotatingFileHandler',
            'formatter': 'standard',
            'filename': logfile_path,  #
            'maxBytes': 1024 * 1024 * 5,  # 日志文件的最大大小为5M 超出后 换文件
            'backupCount': 5, # 最多留五个日志文件
            'encoding': 'utf-8',
        },
    },
    'loggers': {
        # 在getLogger的时候  如果指定的名称 不存在 或者不给名称 用的就是默认的
        # 在这里如果key为空 它就是默认的
        # 你可以自己定义生成器的名称 并且他们还能使用相同的默认配置
        '': {
            'handlers': ['default', 'console'],
            'level': 'DEBUG',
            'propagate': False,
        },
    },
}
View Code

core文件夹下chief.py文件

from conf.logcfg import *
import logging.config
def load_my_log():
    logging.config.dictConfig(LOGGING_DIC)
    logger = logging.getLogger(__name__)
    return logger

bin目录下start.py文件

import os,sys
DP_PATH = os.path.dirname(os.path.dirname(__file__))
sys.path.append(DP_PATH)

import core.chief
logger =core.chief.load_my_log()
logger.debug('this is a debug')

log文件夹下的a.log文件

[2018-10-18 19:48:28,285][MainThread:15676][task_id:core.chief][chief.py:8][INFO][测试信息]
[2018-10-18 19:57:59,595][MainThread:15340][task_id:core.chief][start.py:9][DEBUG][this is a debug]

 

猜你喜欢

转载自www.cnblogs.com/msj513/p/9812805.html