配置文件??conf/log.conf
[LOGGING]
log_file =
max_bytes_each = 512000
backup_count = 10
fmt = |(asctime)s |(filename)s[line: |(lineno)d] |(levelname)s: |(message)s
logger_name = test_logger
log_level_in_console = 10
log_level_in_logfile = 20
console_log_on = 1
logfile_log_on = 1
[README]
log_level = '日志级别:CRITICAL = 50 ERROR = 40 WARNING = 30 INFO = 20 DEBUG = 10 NOTSET = 0'
log_on = 'console_log_on = 1 开启控制台日志,0则关闭,logfile_log_on = 1 开启文件日志, 0则关闭'
log_file = 'log.txt所在的目录必须已存在'
文件名??logger.py
# -*- coding:utf-8 -*-
__author__ = 'WangBenYan'
import logging
from logging.handlers import TimedRotatingFileHandler
import threading
import configparser
import os
class Logger(object):
def __init__(self, log_config):
self.log_config = log_config
def __new__(cls, log_config):
mutex = threading.Lock()
mutex.acquire() # 上锁,防止多线程下出问题
if not hasattr(cls, 'instance'):
cls.instance = super(Logger, cls).__new__(cls)
config = configparser.ConfigParser()
config.read(log_config, encoding='utf-8-sig')
cls.instance.log_filename = config.get('LOGGING', 'log_file')
if not cls.instance.log_filename.strip(' '):
# 日志存放路径
cls.instance.log_filename = './logs/log.log'
elif os.path.exists(cls.instance.log_filename):
if os.path.isdir(cls.instance.log_filename):
print(u'日志路径不能为目录,终止程序')
exit()
else:
print(u'日志路径不存在,终止程序')
exit()
cls.instance.max_bytes_each = int(config.get('LOGGING', 'max_bytes_each'))
cls.instance.backup_count = int(config.get('LOGGING', 'backup_count'))
cls.instance.fmt = config.get('LOGGING', 'fmt')
cls.instance.log_level_in_console = int(config.get('LOGGING', 'log_level_in_console'))
cls.instance.log_level_in_logfile = int(config.get('LOGGING', 'log_level_in_logfile'))
cls.instance.logger_name = config.get('LOGGING', 'logger_name')
cls.instance.console_log_on = int(config.get('LOGGING', 'console_log_on'))
cls.instance.logfile_log_on = int(config.get('LOGGING', 'logfile_log_on'))
cls.instance.logger = logging.getLogger(cls.instance.logger_name)
cls.instance.__config_logger()
cls.instance.logger.setLevel(1)
mutex.release()
return cls.instance
def get_logger(self):
return self.logger
def __config_logger(self):
# 设置日志格式
fmt = self.fmt.replace('|', '%')
formatter = logging.Formatter(fmt)
""" 控制台日志开关 =2 则关闭控制台日志,只写日志文件,=1则打开控制台日志"""
if self.console_log_on == 1: # =1 如果开启控制台日志,非1 关闭
console = logging.StreamHandler()
console.setFormatter(formatter)
console.setLevel(self.log_level_in_console)
self.logger.addHandler(console)
# 此处打印中文乱码,需解决
print(u'当前控制台生效的日志级别为:', self.logger.getEffectiveLevel())
if self.logfile_log_on == 1: # 如果开启文件日志
# rt_file_handler = RotatingFileHandler(self.log_filename, maxBytes=self.max_bytes_each,
# backupCount=self.backup_count)
rt_file_handler = TimedRotatingFileHandler(self.log_filename, when='D', interval=1,
backupCount=self.backup_count)
rt_file_handler.setFormatter(formatter)
rt_file_handler.setLevel(self.log_level_in_logfile)
self.logger.addHandler(rt_file_handler)
logger = Logger('./conf/log.conf')
logger = logger.get_logger()
# 使用时,用from logger import logger
# 测试
# logger.debug('this is info level message')
# logger.info('this is info level message')
# logger.warning('this is warning level message')
# logger.error('this is error level message')
# logger.critical('this is critical level message')
|