您好,登錄后才能下訂單哦!
今天就跟大家聊聊有關(guān)怎么在Python項(xiàng)目中利用 logging實(shí)現(xiàn)自定義輸出字段顏色,可能很多人都不太了解,為了讓大家更加了解,小編給大家總結(jié)了以下內(nèi)容,希望大家根據(jù)這篇文章可以有所收獲。
logging模塊是Python的一個(gè)標(biāo)準(zhǔn)庫(kù)模塊,開(kāi)發(fā)過(guò)程中,可以通過(guò)該模塊,靈活的完成日志的記錄。
logging模塊提供了兩種記錄日志的方式:
1)使用logging提供的模塊級(jí)別的函數(shù)(logging.basicConfig,logging.debug,logging.info...)
2)使用logging模塊的組件(loggers,handlers,filters,formatters)
簡(jiǎn)單示例
import json import logging class JsonFilter(logging.Filter): #此處定義字段的默認(rèn)值,如果打印信息時(shí)不設(shè)置對(duì)應(yīng)字段,則為默認(rèn)值 #服務(wù)服務(wù)名或者服務(wù)主機(jī) server = "" #訪問(wèn)ip ip = "" #訪問(wèn)資源路徑 sourceurl = "" #訪問(wèn)方式 method = "" # 訪問(wèn)設(shè)備 devices = "" # 訪問(wèn)協(xié)議 Protocols = "" #訪問(wèn)結(jié)果的HTTP狀態(tài)碼 result_Httpstatus = "" #訪問(wèn)結(jié)果的狀態(tài)碼 result_status = "" #訪問(wèn)結(jié)果的msg信息 result_msg = "" #訪問(wèn)結(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è)置對(duì)應(yīng)字段,則為默認(rèn)值 # 服務(wù)服務(wù)名或者服務(wù)主機(jī) server = "" # 訪問(wèn)ip ip = "" # 訪問(wèn)資源路徑 sourceurl = "" # 訪問(wèn)方式 method = "" # 訪問(wèn)設(shè)備 devices = "" # 訪問(wèn)協(xié)議 Protocols = "" # 訪問(wèn)結(jié)果的HTTP狀態(tài)碼 result_Httpstatus = "" # 訪問(wèn)結(jié)果的狀態(tài)碼 result_status = "" # 訪問(wèn)結(jié)果的msg信息 result_msg = "" # 訪問(wèn)結(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,用于寫(xiě)到本地 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ù)問(wèn)題 self.logger.removeHandler(ch) self.logger.removeHandler(fh) # 關(guān)閉打開(kāi)的文件 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,用于寫(xiě)到本地 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ù)問(wèn)題 self.logger.removeHandler(ch) self.logger.removeHandler(fh) fh.close() # 關(guān)閉打開(kāi)的文件 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("測(cè)試1") # 如果你需要在打印字段中設(shè)置 log.debug("測(cè)試2") # 如果你需要在打印字段中設(shè)置
看完上述內(nèi)容,你們對(duì)怎么在Python項(xiàng)目中利用 logging實(shí)現(xiàn)自定義輸出字段顏色有進(jìn)一步的了解嗎?如果還想了解更多知識(shí)或者相關(guān)內(nèi)容,請(qǐng)關(guān)注億速云行業(yè)資訊頻道,感謝大家的支持。
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。