您好,登錄后才能下訂單哦!
今天就跟大家聊聊有關怎么在Python項目中利用 logging實現自定義輸出字段顏色,可能很多人都不太了解,為了讓大家更加了解,小編給大家總結了以下內容,希望大家根據這篇文章可以有所收獲。
logging模塊是Python的一個標準庫模塊,開發過程中,可以通過該模塊,靈活的完成日志的記錄。
logging模塊提供了兩種記錄日志的方式:
1)使用logging提供的模塊級別的函數(logging.basicConfig,logging.debug,logging.info...)
2)使用logging模塊的組件(loggers,handlers,filters,formatters)
簡單示例
import json import logging class JsonFilter(logging.Filter): #此處定義字段的默認值,如果打印信息時不設置對應字段,則為默認值 #服務服務名或者服務主機 server = "" #訪問ip ip = "" #訪問資源路徑 sourceurl = "" #訪問方式 method = "" # 訪問設備 devices = "" # 訪問協議 Protocols = "" #訪問結果的HTTP狀態碼 result_Httpstatus = "" #訪問結果的狀態碼 result_status = "" #訪問結果的msg信息 result_msg = "" #訪問結果的數據大小 result_msgsize = "" def filter(self, record): record.server = self.server record.ip = self.ip record.sourceurl = self.sourceurl record.method = self.method record.devices = self.devices record.Protocols = self.Protocols record.result_Httpstatus = self.result_Httpstatus record.result_status = self.result_status record.result_msg = self.result_msg record.result_msgsize = self.result_msgsize return True if __name__ == '__main__': formate = json.dumps({ "time": "%(asctime)s", "levelname": "%(levelname)s", "server": "%(server)s", "ip": "%(ip)s", "sourceurl": "%(sourceurl)s", "method": "%(method)s", "devices": "%(devices)s", "Protocols": "%(Protocols)s", "result_Httpstatus": "%(result_Httpstatus)s", "result_status": "%(result_status)s", "result_msg": "%(result_msg)s", "result_msgsize": "%(result_msgsize)s", }) logging.basicConfig(level=logging.DEBUG,format=formate) logger = logging.getLogger() filter_ = JsonFilter() logger.addFilter(filter_) filter_.server = '127.0.0.1:8100' filter_.ip = '127.0.0.1' filter_.sourceurl = 'http://127.0.0.1:8100/test' filter_.method = 'Get' filter_.devices = 'Chrome' filter_.Protocols = 'HTTP' filter_.result_Httpstatus = '200' filter_.result_status = '1001' filter_.result_msg = '增加成功' filter_.result_msgsize = '4296' logger.info("") #如果你需要在打印字段中設置
一個完整的例子
import logging import os from logging import handlers class JsonFilter(logging.Filter): # 此處定義字段的默認值,如果打印信息時不設置對應字段,則為默認值 # 服務服務名或者服務主機 server = "" # 訪問ip ip = "" # 訪問資源路徑 sourceurl = "" # 訪問方式 method = "" # 訪問設備 devices = "" # 訪問協議 Protocols = "" # 訪問結果的HTTP狀態碼 result_Httpstatus = "" # 訪問結果的狀態碼 result_status = "" # 訪問結果的msg信息 result_msg = "" # 訪問結果的數據大小 result_msgsize = "" def filter(self, record): record.server = self.server record.ip = self.ip record.sourceurl = self.sourceurl record.method = self.method record.devices = self.devices record.Protocols = self.Protocols record.result_Httpstatus = self.result_Httpstatus record.result_status = self.result_status record.result_msg = self.result_msg record.result_msgsize = self.result_msgsize return True class CommonLog(object): """ 日志記錄 """ def __init__(self, logger, logname='Access_log'): self.logname = os.path.join("D:\python protest\protest", '%s' % logname) self.logger = logger self.logger.setLevel(logging.INFO) self.logger.propagate = False self.filter_ = JsonFilter() self.logger.addFilter(self.filter_) self.formatter = logging.Formatter("time:%(asctime)s - levelname:%(levelname)s - server:%(server)s - ip:%(ip)s - sourceurl:%(sourceurl)s - method:%(method)s - devices:%(devices)s - Protocols:%(Protocols)s - result_Httpstatus:%(result_Httpstatus)s - result_status:%(result_status)s - result_msg:%(result_msg)s - result_msgsize:%(result_msgsize)s ") def console(self, level, message): # 創建一個FileHandler,用于寫到本地 fh = logging.handlers.TimedRotatingFileHandler(self.logname, when='MIDNIGHT', interval=1, encoding='utf-8') fh.suffix = '%Y-%m-%d.log' fh.setLevel(logging.INFO) fh.setFormatter(self.formatter) self.logger.addHandler(fh) # 創建一個StreamHandler,用于輸出到控制臺 ch = logging.StreamHandler() ch.setLevel(logging.INFO) ch.setFormatter(self.formatter) self.logger.addHandler(ch) if level == 'info': self.logger.info(message) elif level == 'debug': self.logger.debug(message) elif level == 'warning': self.logger.warning(message) elif level == 'error': self.logger.error(message) # 這兩行代碼是為了避免日志輸出重復問題 self.logger.removeHandler(ch) self.logger.removeHandler(fh) # 關閉打開的文件 fh.close() def debug(self, message): self.console('debug', message) def info(self, message): self.console('info', message) def warning(self, message): self.console('warning', message) def error(self, message): self.console('error', message) if __name__ == '__main__': logger = logging.getLogger() log = CommonLog(logger) log.filter_.server = '127.0.0.1:8100' log.filter_.ip = '127.0.0.1' log.filter_.sourceurl = 'http://127.0.0.1:8100/test' log.filter_.method = 'Get' log.filter_.devices = 'Chrome' log.filter_.Protocols = 'HTTP' log.filter_.result_Httpstatus = '200' log.filter_.result_status = '1001' log.filter_.result_msg = '增加成功' log.filter_.result_msgsize = '4296' log.info("")
設置日志打印顏色
# coding:utf-8 import logging import os from logging.handlers import RotatingFileHandler # import colorlog # 控制臺日志輸入顏色 log_colors_config = { 'DEBUG': 'cyan', 'INFO': 'green', 'WARNING': 'yellow', 'ERROR': 'red', 'CRITICAL': 'red', } class Log: def __init__(self, logname='Access_log'): self.logname = os.path.join("D:\python_protest\protest", '%s' % logname) self.logger = logging.getLogger() self.logger.setLevel(logging.DEBUG) self.formatter = colorlog.ColoredFormatter( '%(log_color)s[%(asctime)s] [%(filename)s:%(lineno)d] [%(module)s:%(funcName)s] [%(levelname)s]- %(message)s', log_colors=log_colors_config) # 日志輸出格式 def console(self, level, message): # 創建一個FileHandler,用于寫到本地 fh = logging.handlers.TimedRotatingFileHandler(self.logname, when='MIDNIGHT', interval=1, encoding='utf-8') fh.setLevel(logging.DEBUG) fh.setFormatter(self.formatter) self.logger.addHandler(fh) # 創建一個StreamHandler,用于輸出到控制臺 ch = logging.StreamHandler() ch.setLevel(logging.DEBUG) ch.setFormatter(self.formatter) self.logger.addHandler(ch) if level == 'info': self.logger.info(message) elif level == 'debug': self.logger.debug(message) elif level == 'warning': self.logger.warning(message) elif level == 'error': self.logger.error(message) # 這兩行代碼是為了避免日志輸出重復問題 self.logger.removeHandler(ch) self.logger.removeHandler(fh) fh.close() # 關閉打開的文件 def debug(self, message): self.console('debug', message) def info(self, message): self.console('info', message) def warning(self, message): self.console('warning', message) def error(self, message): self.console('error', message) if __name__ == "__main__": log = Log() log.info("測試1") # 如果你需要在打印字段中設置 log.debug("測試2") # 如果你需要在打印字段中設置
看完上述內容,你們對怎么在Python項目中利用 logging實現自定義輸出字段顏色有進一步的了解嗎?如果還想了解更多知識或者相關內容,請關注億速云行業資訊頻道,感謝大家的支持。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。