python logging库

logging应用

python logging库_第1张图片

1.loggers : 写日志

# 提供应用程序的调用接口
logger = logging.getLogger(__name__)
# 决定日志记录的级别
logger.setLevel()
# 把日志传递到handlers
logger.addHandler()
logger.removeHandler()

2.handlers : 指定日志的目的地(console,file,email,http…)

# StreamHandler 日志输出到显示器
sh = logging.StreamHandler(stream=None)
# FileHandler 日志保存在一个文件中
fh = logging.FileHandler(filename,mode='a'encoding=None,delay=False)
# RotatingFileHandler
# TimeRotatingFileHandler
...

3.filters : 控制输出日志的级别(非必要)

用于过滤(保留包含关键字的)logger和handler

# 创建filter
filter = logging.Filter('app')  # 保留日志名字包含app的日志
# 关联filter
logger.addFilter(filter)
consoleHandler.addFilter(filter)
fileHandler.addFilter(filter)

4.formatters : 格式化日志

ft = logging.Formatter.__init__(fmt=None,datefmt=Node,style=' %')
属性 描述
asctime 日志产生的时间
created 生成日志创建时间戳
filename 生成日志的程序名
funcName 调用日志的函数名

通过编程的方式处理日志

import logging

# logger
logger = logging.getLogger('applog') #实例化logger对象
logger.setLevel(logging.INFO) #设置logger级别(logger级别优先级高于handler)

# handler
consoleHandler = logging.StreamHandler() #实例化handler对象
consoleHandler.setLevel(logging.DEBUG) #设置handler级别

fileHandler = logging.FileHandler(filename='demo.log',mode='w')  # 没有指定日志级别,默认用logger的级别

# filter(非必要)
filter = logging.Filter('applog')  # logger或者handler名字包含applog的会输出
logger.addFilter(filter)  # logger关联filter
consoleHandler.addFilter(filter)  # handler关联filter

# formatters
formatter = logging.Formatter('%(asctime)s | %(levelname)8s | %(filename)s:%(lineno)s | %(message)s')

# 给handler设置格式
consoleHandler.setFormatter(formatter)
fileHandler.setFormatter(formatter)

# 给logger关联handler
logger.addHandler(consoleHandler)
logger.addHandler(fileHandler)

# 打印日志
logger.debug('this is debug log')
logger.info('this is info log')
logger.warning('this is warning log')
logger.error('this is error log')
logger.critical('this is critical log')

通过配置文件的方式处理日志

logging.conf

[loggers]
keys=root,error

[handlers]
keys = consoleHandler,fileHandler

[formatters]
keys = simpleFormatter

[logger_root]
level = DEBUG
handlers = consoleHandler

[logger_error]
level=ERROR
qualname=error
handlers=fileHandler
propagate=0

[handler_consoleHandler]
class = StreamHandler
args=(sys.stdout,)
level=DEBUG
formatter = simpleFormatter

[formatter_simpleFormatter]
format = %(asctime)s | %(levelname)8s | %(filename)s:%(lineno)s | %(message)s

main.py

import logging.config
from pandas import DataFrame

logging.config.fileConfig('logging.conf')
logger_debug = logging.getLogger()
logger_error = logging.getLogger('error')

def read_csv(filePath: str, usecols=None,fillna: bool = False) ->DataFrame:
    try:
        if fillna == True:
            df = pd.read_csv(filePath, float_precision="high",usecols=usecols)
            df = df.fillna(0)
        else:
            df = pd.read_csv(filePath, float_precision="high",usecols=usecols)
        logger_debug.debug(f'read "{filePath}" sucessfully')
        return df
    except Exception as e:
        logger_error.error(f'{e}')

参考

bilibili: BV1sK4y1x7e1

你可能感兴趣的:(python,开发语言,后端)