8、python 记录脚本日志

python脚本记录日志

import logging

方法1:basicConfig()

# 记录日志的简单方法
# fmt = '%(asctime)-15s %(levelname)s %(filename)s %(lineno)d %(process)d %(message)s'
FORMAT = '%(asctime)s %(levelname)s %(message)s'
DATEFMT = '%Y/%m/%d %H:%M:%S'
# 设置保存路径、日志等级、样式、记录时间
logging.basicConfig(filename='my_log.log', level=logging.DEBUG, format=FORMAT, datefmt=DATEFMT)
# 添加日志(可添加不同等级的日志,调用不同的方法)
logging.debug('调试日志')
logging.info('信息日志')
logging.warning('警告日志')
logging.error('错误日志')

方法2:getLogger()

# 通过添加处理器的方法记录日志
logger = logging.getLogger()
logger.setLevel(logging.DEBUG)
# 格式化器
FORMAT = '%(asctime)s %(levelname)s %(filename)s %(lineno)s %(process)s %(message)s'
# '%a %d %b %Y %H%M%S'
DATEFMT = '%a %b %d %Y %H:%M:%S'
formatter = logging.Formatter(fmt=FORMAT, datefmt=DATEFMT)
# 添加处理器   mode:日志模式 (‘a’:追加)
# DEBUG
file_handler = logging.FileHandler('file_log.log', mode='a', encoding='UTF-8')
file_handler.setLevel(logging.DEBUG)
file_handler.setFormatter(formatter)
logger.addHandler(file_handler)
# ERROR
error_handler = logging.FileHandler('error_log.log', mode='a', encoding='UTF-8')
error_handler.setLevel(logging.ERROR)
error_handler.setFormatter(formatter)
logger.addHandler(error_handler)

# 流处理器 可在控制台显示打印
stream_handler = logging.StreamHandler()
stream_handler.setLevel(logging.DEBUG)
stream_handler.setFormatter(formatter)
logger.addHandler(stream_handler)

# 过滤器
log_filter = logging.Filter()
log_filter.filter = lambda record: record.levelno < logging.ERROR
file_handler.addFilter(log_filter)
stream_handler.addFilter(log_filter)

方法3:TimedRotatingFileHandler()

# 按时间周期记录日志
from logging.handlers import TimedRotatingFileHandler

logger = logging.getLogger('__name__')
logger.setLevel(logging.INFO)
log_name = 'redis_update_log.log'
handler = TimedRotatingFileHandler(log_name,
                                   when="midnight",
                                   interval=1,
                                   backupCount=10,
                                   encoding='UTF-8')
# formatter
# fmt = "%(asctime)-15s %(levelname)s %(filename)s %(lineno)d %(process)d %(message)s"
fmt = "%(asctime)-15s %(levelname)s %(message)s"
datefmt = "%a %d %b %Y %H:%M:%S"
formatter = logging.Formatter(fmt, datefmt)
# add handler and formatter to logger
handler.setFormatter(formatter)
logger.addHandler(handler)
# stream 日志打印
stream_handler = logging.StreamHandler()
stream_handler.setLevel(logging.DEBUG)
stream_handler.setFormatter(formatter)
logger.addHandler(stream_handler)

你可能感兴趣的:(8、python 记录脚本日志)