python日志 logging模块

logging相关知识

日志级别 使用场景
DEBUG 详细信息,一般只在调试问题时使用
INFO 证明事情按预期工作
WARNING 某些没有预料到的时间提示,或者在将来可能会出现的问题提示
ERROR 由于更严重的问题,软件已不能执行一些功能了
CRITICAL 严重错误,表明软件已不能继续运行了

注释:
严重级别 : CRITICAL>ERROR>WARNING>INFO>DEBUG
默认等级: WARNING
设置输出日志级别: 如果日志等级是WARNING, 日志只能打印WARNING 和 以上的日志内容, 严重级别小于WARING是不打印的

默认生成的root logger的level是logging.WARNING,低于该级别的就不输出了

Formatter对象设置日志信息最后的规则、结构和内容

参数 输出内容
%(name)s Logger的名字
%(levelno)s 数字形式的日志级别
%(message)s 用户输出的信息
%(levelname)s 文本形式的日志级别
%(pathname)s 调用日志输出函数的模块的完整路径名,可能没有
%(filename)s 调用日志输出函数的模块的文件名
%(module)s 调用日志输出函数的模块名
%(lineno)d 调用日志输出函数的语句所在的代码行
%(asctime)s 字符串形式的当前时间。默认格式是 “2003-07-08 16:49:45,896”。逗号后面的是毫秒
%(thread)d 线程ID, 可能没有
%(threadName)s 线程名。可能没有

logging打印到控制台

import logging
logging.debug('it is debug')
logging.info('it is info')
logging.warning('it is waring')
logging.error('it is error')
logging.critical('it is critical')
输出只有:
WARNING:root:it is waring
ERROR:root:it is error
CRITICAL:root:it is critical
注释: 默认生成的root logger的level是logging.WARNING,低于该级别的就不输出了

logging输出到文件中

import logging
#创建一个logger
logger = logging.getLogger()
#设置log等级开关
logger.setLevel(logging.INFO)
logfile = 'recorder.log'
fh = logging.FileHandler(logfile, mode='w', encoding='utf-8')
#设置输出格式
fh.setLevel(logging.DEBUG)
#设置格式
formatter = logging.Formatter('%(asctime)s - %(filename)s[line:%(lineno)d] - %(levelname)s: %(message)s')
fh.setFormatter(formatter)
#将logger添加到hander里面
logger.addHandler(fh)
logger.debug('this is a logger debug message')
logger.info('this is a logger info message')
logger.warning('this is a logger warning message')
logger.error('this is a logger error message')
logger.critical('this is a logger critical message')

简单日志装饰器

import logging
import json

def create_log():
    logger = logging.getLogger()
    # 设置log等级开关
    logger.setLevel(logging.INFO)
    logfile = 'warrp.log'
    fh = logging.FileHandler(logfile, mode='w', encoding='utf-8')
    # 设置输出格式
    fh.setLevel(logging.DEBUG)
    # 设置格式
    formatter = logging.Formatter('%(asctime)s - %(filename)s[line:%(lineno)d] - %(levelname)s: %(message)s')
    fh.setFormatter(formatter)
    # 将logger添加到hander里面
    logger.addHandler(fh)
    return logger


def write_log(func):
    def wrapper():
        result = func()
        logger = create_log()
        logger.info(json.dumps(result))
        return result
    return wrapper

@write_log
def func():
    return {
    
    'name': 'hh', 'age': 20}

if __name__ == '__main__':
	func()

猜你喜欢

转载自blog.csdn.net/xxy_yang/article/details/107913769