python 以单例模式封装logging相关api实现日志打印类

python 以单例模式封装logging相关api实现日志打印类

 

by:授客QQ1033553122

测试环境:

Python版本:Python 2.7

 

实现功能:

支持*配置,如下log.conf,

1)可以配置日志文件路径(log_file);

2)按日志数量配置(backup_count)及单个日志文件的大小(max_bytes_each),自动化循环切换日志文件;

3)支持日志格式自定义(fmt);

4)支持日志记录器名称自定义(logger_name)

6)支持控制台日志和文件日志

5) 支持控制台日志级别自定义(log_level_in_console)

6)支持文件日志级别自定义(log_level_in_logfile)

7) 支持控制台和文件日志的各自的开启和关闭(分别为console_log_on, logfile_log_on)

log.conf配置文件

./config/logconfig.conf配置如下:

[LOGGING]

log_file = d:/testlog.txt

max_bytes_each = 3

backup_count = 5

fmt = |(asctime)s |(filename)s[line: |(lineno)d] |(levelname)s: |(message)s

logger_name = test_logger

log_level_in_console = 20

log_level_in_logfile = 10

console_log_on = 1

logfile_log_on = 1

#日志级别:CRITICAL = 50 ERROR = 40 WARNING = 30 INFO = 20 DEBUG = 10 NOTSET = 0

#console_log_on  = 1 开启控制台日志,logfile_log_on = 1 开启文件日志

实践代码

#!/usr/bin/env python

# -*- coding:utf-8 -*-

 

 

#!/usr/bin/env python

# -*- coding:utf-8 -*-

 

 

__author__ = 'shouke'

import logging

from logging.handlers import RotatingFileHandler

import threading

import configparser

 

class LogSignleton(object):

    def __init__(self, log_config):

        pass

 

    def __new__(cls, log_config):

        mutex=threading.Lock()

        mutex.acquire() # 上锁,防止多线程下出问题

        if not hasattr(cls, 'instance'):

            cls.instance = super(LogSignleton, cls).__new__(cls)

            config = configparser.ConfigParser()

            config.read(log_config)

            cls.instance.log_filename = config.get('LOGGING', 'log_file')

            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()

        mutex.release()

        return cls.instance

 

    def get_logger(self):

        return  self.logger

 

    def __config_logger(self):

        # 设置日志格式

        fmt = self.fmt.replace('|','%')

        formatter = logging.Formatter(fmt)

 

        if self.console_log_on == 1: # 如果开启控制台日志

            console = logging.StreamHandler()

            #console.setLevel(self.log_level_in_console)

            console.setFormatter(formatter)

            self.logger.addHandler(console)

            self.logger.setLevel(self.log_level_in_console)

 

        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.setFormatter(formatter)

            self.logger.addHandler(rt_file_handler)

            self.logger.setLevel(self.log_level_in_logfile)

 

if __name__ == '__main__':

    logsignleton = LogSignleton('./config/logconfig.conf')

    logger = logsignleton.get_logger()

    #logger = logging.getLogger('test_logger') # 在其它模块中时,可这样获取该日志实例

    logger.debug('this is a debug 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')

 

注:多次使用相同的name调用getLogger方法返回同一个logger对象,可通过id(obj)进行验证

运行结果:

python 以单例模式封装logging相关api实现日志打印类

d:\\目录下生成文件如下:

python 以单例模式封装logging相关api实现日志打印类

上一篇:【python】Python的单例模式


下一篇:控制div位于最上层