日志生成的位置为当前文件目录下的tmp 文件夹,是以固定大小(10M)的方式去滚动日志,
如想设置为按时间滚动日志,需要设置为TimedRotatingFileHandler(filename=_create_log_path(), when="midnight", interval=1, backupCount=7)去替换RotatingFileHandler,每天晚上12点生成一个新的日志文件。
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import logging
from logging.handlers import RotatingFileHandler
import os
import re
import time
class Log(object):
def __init__(self, cls_name):
self._cls_name = cls_name
def get_logger(self):
_logger = logging.getLogger(self._cls_name)
# 此处要整体设置 logger level = DEBUG,否则后面在不同的 handler 中设置 level 无效
_logger.setLevel(logging.DEBUG)
# 创建一个handler,用于写入日志文件
file_handler = RotatingFileHandler(filename=_create_log_path(), mode='a', maxBytes=10 * 1024 * 1024,
encoding='utf8', backupCount=100)
# to avoid missing date for print daily log
file_handler.suffix = "%Y-%m-%d"
file_handler.extMatch = re.compile(r"^\d{4}-\d{2}-\d{2}$")
# 设置日志输出格式
logging_format = logging.Formatter('%(asctime)s - %(levelname)s - %(filename)s - [%(funcName)s] '
'- %(lineno)s - %(message)s')
file_handler.setFormatter(logging_format)
_logger.addHandler(file_handler)
# 设置控制台的日志输出
console_handler = logging.StreamHandler()
console_handler.setLevel(logging.DEBUG)
# 标准输出
console_formatter = logging.Formatter('%(asctime)s - %(levelname)s - %(filename)s - [%(funcName)s] '
'- %(lineno)s - %(message)s')
console_handler.setFormatter(console_formatter)
_logger.addHandler(console_handler)
return _logger
def _get_current_dir():
current_dir = os.path.dirname(os.path.abspath(__file__))
# 创建一个新的文件夹
return os.path.join(current_dir, 'tmp')
def _create_log_dir(log_path: str):
"""
在此文件下生成日志文件夹
:param log_path:
:return:
"""
if not os.path.exists(log_path):
os.mkdir(log_path)
def _create_log_path():
log_dir = _get_current_dir()
_create_log_dir(log_dir)
application_name = "parse_label"
time_value = time.strftime('%Y%m%d', time.localtime(time.time()))
# #create logger name
log_file_name = application_name + "_" + time_value + '.log'
log_file_str = log_dir+"/" + log_file_name
print(log_file_str)
return log_file_str
if __name__ == '__main__':
logger = Log(__name__).get_logger()
logger.info(time.strftime('%Y-%m-%d'))
标签:logging,log,python,handler,path,日志,logger,name
From: https://www.cnblogs.com/lyuSky/p/18383228