Python根據(jù)日志級別打印不同顏色的日志的方法示例-創(chuàng)新互聯(lián)

本文介紹了Python 根據(jù)日志級別打印不同顏色的日志的方法示例,分享給大家,具體如下:

創(chuàng)新互聯(lián)公司專業(yè)為企業(yè)提供梁園網(wǎng)站建設、梁園做網(wǎng)站、梁園網(wǎng)站設計、梁園網(wǎng)站制作等企業(yè)網(wǎng)站建設、網(wǎng)頁設計與制作、梁園企業(yè)網(wǎng)站模板建站服務,10余年梁園做網(wǎng)站經(jīng)驗,不只是建網(wǎng)站,更提供有價值的思路和整體網(wǎng)絡服務。
# -*-coding:UTF-8-*-
import logging
import os
import time
 
 
class logger(object):
  
  """
  終端打印不同顏色的日志,在pycharm中如果強行規(guī)定了日志的顏色, 這個方法不會起作用, 但是
  對于終端,這個方法是可以打印不同顏色的日志的。
  """ 
 
  #在這里定義StreamHandler,可以實現(xiàn)單例, 所有的logger()共用一個StreamHandler
  ch = logging.StreamHandler()
  def __init__(self):
    self.logger = logging.getLogger()
    if not self.logger.handlers:
      #如果self.logger沒有handler, 就執(zhí)行以下代碼添加handler
      self.logger.setLevel(logging.DEBUG)
      from serviceProgram.utils.FileUtil import FileUtil
      rootPath = FileUtil.getProgrameRootPath()
      self.log_path = rootPath + '/logs'
      if not os.path.exists(self.log_path):
        os.makedirs(self.log_path)
 
      # 創(chuàng)建一個handler,用于寫入日志文件
      fh = logging.FileHandler(self.log_path + '/runlog' + time.strftime("%Y%m%d", time.localtime()) + '.log', encoding='utf-8')
      fh.setLevel(logging.INFO)
 
      # 定義handler的輸出格式
      formatter = logging.Formatter('[%(asctime)s] - [%(levelname)s] - %(message)s')
      fh.setFormatter(formatter)
 
      # 給logger添加handler
      self.logger.addHandler(fh)
 
  def debug(self, message):
    self.fontColor('\033[0;32m%s\033[0m')
    self.logger.debug(message)
 
  def info(self, message):
    self.fontColor('\033[0;34m%s\033[0m')
    self.logger.info(message)
 
  def warning(self, message):
    self.fontColor('\033[0;37m%s\033[0m')
    self.logger.warning(message)
 
  def error(self, message):
    self.fontColor('\033[0;31m%s\033[0m')
    self.logger.error(message)
 
  def critical(self, message):
    self.fontColor('\033[0;35m%s\033[0m')
    self.logger.critical(message)
 
  def fontColor(self, color):
    #不同的日志輸出不同的顏色
    formatter = logging.Formatter(color % '[%(asctime)s] - [%(levelname)s] - %(message)s')
    self.ch.setFormatter(formatter)
    self.logger.addHandler(self.ch)
 
 
if __name__ == "__main__":
  logger = logger()
  logger.info("12345")
  logger.debug("12345")
  logger.warning("12345")
  logger.error("12345")

另外有需要云服務器可以了解下創(chuàng)新互聯(lián)scvps.cn,海內(nèi)外云服務器15元起步,三天無理由+7*72小時售后在線,公司持有idc許可證,提供“云服務器、裸金屬服務器、高防服務器、香港服務器、美國服務器、虛擬主機、免備案服務器”等云主機租用服務以及企業(yè)上云的綜合解決方案,具有“安全穩(wěn)定、簡單易用、服務可用性高、性價比高”等特點與優(yōu)勢,專為企業(yè)上云打造定制,能夠滿足用戶豐富、多元化的應用場景需求。

本文名稱:Python根據(jù)日志級別打印不同顏色的日志的方法示例-創(chuàng)新互聯(lián)
網(wǎng)站網(wǎng)址:http://muchs.cn/article38/dshhpp.html

成都網(wǎng)站建設公司_創(chuàng)新互聯(lián),為您提供網(wǎng)站營銷、網(wǎng)站排名、網(wǎng)站維護商城網(wǎng)站、面包屑導航、外貿(mào)網(wǎng)站建設

廣告

聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權請盡快告知,我們將會在第一時間刪除。文章觀點不代表本網(wǎng)站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時需注明來源: 創(chuàng)新互聯(lián)

成都app開發(fā)公司