今天就跟大家聊聊有關(guān)怎么在Python項(xiàng)目中利用 logging實(shí)現(xiàn)自定義輸出字段顏色,可能很多人都不太了解,為了讓大家更加了解,小編給大家總結(jié)了以下內(nèi)容,希望大家根據(jù)這篇文章可以有所收獲。
創(chuàng)新互聯(lián)專注于茂南企業(yè)網(wǎng)站建設(shè),成都響應(yīng)式網(wǎng)站建設(shè),商城網(wǎng)站制作。茂南網(wǎng)站建設(shè)公司,為茂南等地區(qū)提供建站服務(wù)。全流程按需開發(fā),專業(yè)設(shè)計(jì),全程項(xiàng)目跟蹤,創(chuàng)新互聯(lián)專業(yè)和態(tài)度為您提供的服務(wù)logging模塊是Python的一個(gè)標(biāo)準(zhǔn)庫模塊,開發(fā)過程中,可以通過該模塊,靈活的完成日志的記錄。
logging模塊提供了兩種記錄日志的方式:
1)使用logging提供的模塊級別的函數(shù)(logging.basicConfig,logging.debug,logging.info...)
2)使用logging模塊的組件(loggers,handlers,filters,formatters)
簡單示例
import json import logging class JsonFilter(logging.Filter): #此處定義字段的默認(rèn)值,如果打印信息時(shí)不設(shè)置對應(yīng)字段,則為默認(rèn)值 #服務(wù)服務(wù)名或者服務(wù)主機(jī) server = "" #訪問ip ip = "" #訪問資源路徑 sourceurl = "" #訪問方式 method = "" # 訪問設(shè)備 devices = "" # 訪問協(xié)議 Protocols = "" #訪問結(jié)果的HTTP狀態(tài)碼 result_Httpstatus = "" #訪問結(jié)果的狀態(tài)碼 result_status = "" #訪問結(jié)果的msg信息 result_msg = "" #訪問結(jié)果的數(shù)據(jù)大小 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("") #如果你需要在打印字段中設(shè)置
一個(gè)完整的例子
import logging import os from logging import handlers class JsonFilter(logging.Filter): # 此處定義字段的默認(rèn)值,如果打印信息時(shí)不設(shè)置對應(yīng)字段,則為默認(rèn)值 # 服務(wù)服務(wù)名或者服務(wù)主機(jī) server = "" # 訪問ip ip = "" # 訪問資源路徑 sourceurl = "" # 訪問方式 method = "" # 訪問設(shè)備 devices = "" # 訪問協(xié)議 Protocols = "" # 訪問結(jié)果的HTTP狀態(tài)碼 result_Httpstatus = "" # 訪問結(jié)果的狀態(tài)碼 result_status = "" # 訪問結(jié)果的msg信息 result_msg = "" # 訪問結(jié)果的數(shù)據(jù)大小 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): # 創(chuàng)建一個(gè)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) # 創(chuàng)建一個(gè)StreamHandler,用于輸出到控制臺(tái) 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) # 這兩行代碼是為了避免日志輸出重復(fù)問題 self.logger.removeHandler(ch) self.logger.removeHandler(fh) # 關(guān)閉打開的文件 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("")
設(shè)置日志打印顏色
# coding:utf-8 import logging import os from logging.handlers import RotatingFileHandler # import colorlog # 控制臺(tái)日志輸入顏色 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): # 創(chuàng)建一個(gè)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) # 創(chuàng)建一個(gè)StreamHandler,用于輸出到控制臺(tái) 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) # 這兩行代碼是為了避免日志輸出重復(fù)問題 self.logger.removeHandler(ch) self.logger.removeHandler(fh) fh.close() # 關(guān)閉打開的文件 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") # 如果你需要在打印字段中設(shè)置 log.debug("測試2") # 如果你需要在打印字段中設(shè)置
看完上述內(nèi)容,你們對怎么在Python項(xiàng)目中利用 logging實(shí)現(xiàn)自定義輸出字段顏色有進(jìn)一步的了解嗎?如果還想了解更多知識或者相關(guān)內(nèi)容,請關(guān)注創(chuàng)新互聯(lián)行業(yè)資訊頻道,感謝大家的支持。