很多程序都有记录日志的需求,并且日志中包含的信息即有正常的程序访问日志,还可能有错误、警告等信息输出,python的logging模块提供了标准的日志接口,你可以通过它存储各种格式的日志,logging的日志可以分为 debug(), info(), warning(), error() and critical()5个级别,但是内置的logging使用不够灵活,我们通过继承类重新封装logging,实现自定义logging模块。
# coding:utf-8
import logging,time,logging.handlers,os
class Log(object):
def __init__(self, logger=None):
# 创建一个logger
self.logger = logging.getLogger(logger)
self.logger.setLevel(logging.DEBUG)
# 创建一个handler,用于写入日志文件
self.logTime = time.strftime("%Y-%m-%d")
self.logPath = os.path.abspath(os.path.join(os.path.dirname(__file__), './logs'))
# 如果不存在这个logs文件夹,就自动创建一个
if not os.path.exists(self.logPath):
os.mkdir(self.logPath)
# 日志文件的地址
self.logName = self.logPath + '/' + self.logTime