python logging封裝成類

2021-10-06 04:41:24 字數 2759 閱讀 9714

話不多說,直接上**

import sys

import time

import logging

import os.path

class logger_handler(object):

'''封裝後的logging'''

def __init__(self, logger = none):

'''指定儲存日誌的檔案路徑,日誌級別,以及呼叫檔案

將日誌存入到指定的檔案中

'''# 第一步,建立乙個logger

self.logger = logging.getlogger(logger)

self.logger.setlevel(logging.debug) # log等級總開關

# 第二步,建立乙個handler,用於寫入日誌檔案

self.rq = time.strftime('%y%m%d%h%m', time.localtime(time.time()))

self.log_path = os.path.dirname(os.getcwd()) + '/log/logs/'

self.log_name = self.log_path + 'xx_' + self.rq + '.log'

self.log_name_detail = self.log_path + 'xx_detail_' + self.rq + '.log'

self.logfile = self.log_name

self.logfile_detail = self.log_name_detail

fh = logging.filehandler(self.logfile, mode='w')

fh_detail = logging.filehandler(self.logfile_detail, mode='w')

fh.setlevel(logging.info) # 輸出到file的log等級的開關

fh_detail.setlevel(logging.info) # 輸出到file的log等級的開關

# ch = logging.streamhandler()

# ch.setlevel(logging.info) # 輸出到console的log等級的開關

# 第三步,定義handler的輸出格式

formatter_file = logging.formatter(

"[%(asctime)s] %(filename)s->%(funcname)s [line:%(lineno)d] - %(levelname)s: %(message)s")

formatter_detail = logging.formatter(

"[%(asctime)s] %(pathname)s->%(filename)s->%(funcname)s [line:%(lineno)d] - %(levelname)s: %(message)s")

formatter_console = logging.formatter(

"[%(asctime)s] %(pathname)s->%(filename)s->%(funcname)s [line:%(lineno)d] - %(levelname)s: %(message)s")

fh.setformatter(formatter_file)

fh_detail.setformatter(formatter_detail)

# ch.setformatter(formatter_console)

# 第四步,將logger新增到handler裡面

self.logger.addhandler(fh)

self.logger.addhandler(fh_detail)

# self.logger.addhandler(ch)

# 日誌

self.logger.debug('this is a logger debug message')

self.logger.info('this is a logger info message')

self.logger.warning('this is a logger warning message')

self.logger.error('this is a logger error message')

self.logger.critical('this is a logger critical message')

# 2432jdsf

try:

open("sklearn.txt", "rb")

except (systemexit, keyboardinterrupt):

raise

except exception:

self.logger.error("faild to open sklearn.txt from logger.error", exc_info=true)

self.logger.info("finish")

# 新增下面一句,在記錄日誌之後移除控制代碼

# self.logger.removehandler(ch)

# self.logger.removehandler(fh)

# 關閉開啟的檔案

# fh.close()

# ch.close()

def getlog(self):

return self.logger

if __name__ == '__main__':

logger_handler().getlog()

Python logging日誌模組 封裝完善

import logging import os class log 模組化使用 建立乙個logger物件,並且進行初始化設定 將logger物件進行返回,方便使用 notset debug info warning error critical 注意這裡有個大坑,notset不是顯示所有訊息,而是...

python logging 最佳實踐

建立乙個logger,這裡的級別debug是總開關,控制了下面file 和console handler的級別 logger logging.getlogger logger.setlevel logging.debug 建立乙個handler,用於寫入日誌檔案,並定義輸出格式 fh logging...

Python logging模組學習

import logging 日誌級別列表,預設為logging.warning levels logging.notset,logging.debug,logging.info,logging.warning,logging.error,logging.critical log format as...