# _*_ coding: utf-8 _*_
import logging
import os.path
import time
class Logger(object):
def __init__(self, logger="comment"):
'''
指定保存日志的文件路径,日志级别,以及调用文件
将日志存入到指定的文件中
'''
# 创建一个logger
self.logger = logging.getLogger(logger)
self.logger.setLevel(logging.DEBUG)
rq = time.strftime('%Y%m%d%H%M', time.localtime(time.time()))
path = os.path.join(__file__)
log_name = path + rq + '.txt'
fh = logging.FileHandler(log_name)
fh.setLevel(logging.INFO)
# 再创建一个handler,用于输出到控制台
ch = logging.StreamHandler()
ch.setLevel(logging.INFO)
# 定义handler的输出格式
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
fh.setFormatter(formatter)
ch.setFormatter(formatter)
self.logger.addHandler(fh)
self.logger.addHandler(ch)
def getlog(self):
return self.logger
引用
from logger import Logger
logger = Logger(logger=Path(__file__).name).getlog()