python写入日志文件并实时输出在控制台

python添加log日志配置代码

日志级别: debug --> info --> warning --> error --> critical。

  • DEBUG 详细信息,调试使用
  • INFO 正常信息
  • WARNING 警告信息
  • ERROR 错误信息
  • CRITICAL 问题很严重
import logging
from logging import handlers

class Logger(object):
    level_relations = {
        'debug':logging.DEBUG,
        'info':logging.INFO,
        'warning':logging.WARNING,
        'error':logging.ERROR,
        'crit':logging.CRITICAL
    }     #日志关系映射

    def __init__(self,filename,level='info',backCount=10,fmt='%(asctime)s - %(pathname)s[line:%(lineno)d] - %(levelname)s: %(message)s'):
        self.logger = logging.getLogger(filename)
        format_str = logging.Formatter(fmt)                  #设置日志格式
        self.logger.setLevel(self.level_relations.get(level))#设置日志级别
        
        sh = logging.StreamHandler()  #往屏幕上输出
        sh.setFormatter(format_str)   #设置屏幕上显示的格式
        self.logger.addHandler(sh)    #把对象加到logger里
        
        fh = handlers.RotatingFileHandler(filename=filename,maxBytes=10485760,backupCount=backCount)   # 按照文件大小分割日志文件
        fh.setLevel(self.level_relations.get(level))
        fh.setFormatter(format_str)   #设置文件里写入的格式
        self.logger.addHandler(fh)
        
if __name__ == '__main__':
    log = Logger('my.log',level='debug')
    log.logger.debug('------0. it is a debug ------')
    log.logger.info('------ 1. it is a test ------')
    log.logger.warning('------ 2. it is a warning ------')
    log.logger.error('------ 3. it is an error ------')
    log.logger.critical('------ 4. serious problem ------')

实时查看log日志

tail -f my.log
原文地址:https://www.cnblogs.com/lihouqi/p/14283201.html