Python:寫入日志文件


python可以在執行時寫入日志用於查找問題,這里提供一個類,在需要的時候就可以直接使用:

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_test.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 ------')

屏幕顯示:

同樣可以在文件夾下找到 my_test.log文件。

日志級別: debug --> info --> warning --> error --> critical。

日志級別 使用備注
DEBUG 詳細信息,調試使用
INFO 正常信息
WARNING 警告信息
ERROR 錯誤信息
CRITICAL 問題很嚴重

注:

handlers.TimedRotatingFileHandler  ---> 可以按時間分割日志文件 

#

更多解釋和說明可參考某大神博客:https://www.cnblogs.com/nancyzhu/p/8551506.html


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM