控制台打印和log日志输出

Zss 发表于:

使用到了python内置的logging模块

  1. 可以通过设置不同的日志等级,在release版本中只输出重要信息,而不必显示大量的调试信息;
  2. print将所有信息都输出到标准输出中,严重影响开发者从标准输出中查看其它数据;logging则可以由开发者决定将信息输出到什么地方,以及怎么输出

对于中间的__new__方法和多线程的锁不理解,先记录下来,还得再多想想

在一个自动化框架里面找到一个很好的log类模块,实时打印输出和日志的写入

配置文件:

[LOGGING]
log_file = C:\Users\Zss-pc\Desktop\Py\log\log.txt
max_bytes_each = 51200
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则关闭'

脚本:

#coding:utf-8
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, encoding='utf-8')
            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.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)

logsignleton = LogSignleton('logconfig.conf')
logger = logsignleton.get_logger()

使用:

#coding:utf-8
from mylog import logger

logger.info('哈哈'.decode('utf-8'))
logger.error('哈哈'.decode('utf-8'))

控制台将输出打印信息且将其输出到log日志中

自定义的格式为%(asctime)s %(filename)s[line: %(lineno)d] %(levelname)s: %(message)s

2018-08-21 21:47:28,092 test.py[line: 7] INFO: 哈哈
2018-08-21 21:47:28,092 test.py[line: 8] INFO: 哈哈
2018-08-21 22:27:23,552 test.py[line: 4] INFO: 哈哈
2018-08-21 22:27:23,553 test.py[line: 5] ERROR: 哈哈