logging日誌模塊

#分別將日誌保存在文件和在終端打印


# -*- coding: utf-8 -*-
"""
Created on Mon Sep 16 20:24:20 2019

@author: Administrator
"""

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',when='D',backCount=3,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) #設置屏幕上顯示的格式
        th = handlers.TimedRotatingFileHandler(filename=filename,when=when,backupCount=backCount,encoding='utf-8')#往文件裏寫入#指定間隔時間自動生成文件的處理器
        #實例化TimedRotatingFileHandler
        #interval是時間間隔,backupCount是備份文件的個數,如果超過這個個數,就會自動刪除,when是間隔的時間單位,單位有以下幾種:
        # S 秒
        # M 分
        # H 小時、
        # D 天、
        # W 每星期(interval==0時代表星期一)
        # midnight 每天凌晨
        th.setFormatter(format_str)#設置文件裏寫入的格式
        self.logger.addHandler(sh) #把對象加到logger裏
        self.logger.addHandler(th)
if __name__ == '__main__':
    log = Logger('i://all.log',level='debug')
    log.logger.debug('debug')
    log.logger.info('info')
    log.logger.warning('警告')
    log.logger.error('報錯')
    log.logger.critical('嚴重')
    Logger('error.log', level='error').logger.error('error')

運行結果:
all.log日誌文件:
在這裏插入圖片描述
終端輸出:

在這裏插入圖片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章