Python線上環(huán)境使用日志的及配置文件的示例分析-創(chuàng)新互聯(lián)

這篇文章主要為大家展示了“Python線上環(huán)境使用日志的及配置文件的示例分析”,內(nèi)容簡而易懂,條理清晰,希望能夠幫助大家解決疑惑,下面讓小編帶領大家一起研究并學習一下“Python線上環(huán)境使用日志的及配置文件的示例分析”這篇文章吧。

成都創(chuàng)新互聯(lián)2013年至今,先為盧氏等服務建站,盧氏等地企業(yè),進行企業(yè)商務咨詢服務。為盧氏企業(yè)網(wǎng)站制作PC+手機+微官網(wǎng)三網(wǎng)同步一站式服務解決您的所有建站問題。

 在初學 Python 的時候,我們使用

print("hello world")

輸出了我們的第一行代碼。在之后的日子里,便一直使用 print 進行調(diào)試(當然,還有 IDE 的 debug 模式)。但是,當你在線上運行 Python 腳本的時候,你并不可能一直守著你的運行終端??墒侨绻皇刂脑?,每當出現(xiàn) bug ,錯誤又無從查起。這個時候,你需要對你的調(diào)試工具進行更新?lián)Q代了,這里我推薦一個優(yōu)雅的調(diào)試工具 logging。

與 print 相比 logging 有什么優(yōu)勢?

那既然我推薦這個工具,它憑什么要被推薦呢?且來看看它有什么優(yōu)勢:

  • 可以輸出到多處,例如:在輸出到控制臺的同時,可以保存日志到日志文件里面,或者保存到其他遠程服務器

  • 可以設置日志等級,DEBUG、INFO、ERROR等,在不同的環(huán)境(調(diào)試環(huán)境、線上環(huán)境)使用不同的等級來過濾日志,使用起來很方便

  • 配置靈活,可保存到配置文件,格式化輸出

基礎用法

下面涉及到的代碼我都省略了導包部分,詳見源碼(后臺回復 logging 獲取源碼)

base_usage.py

logging.basicConfig(level=log_level, format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')
logger = logging.getLogger(__name__)
logger.info("Log level info")
logger.debug("Log level debug")
logger.warning("Log level warning")
# 捕獲異常,并打印出出錯行數(shù)
try:
  raise Exception("my exception")
except (SystemExit, KeyboardInterrupt):
  raise
except Exception:
  logger.error("there is an error =>", exc_info=True)

level為日志等級,分為:

FATAL:致命錯誤
CRITICAL:特別糟糕的事情,如內(nèi)存耗盡、磁盤空間為空,一般很少使用
ERROR:發(fā)生錯誤時,如IO操作失敗或者連接問題
WARNING:發(fā)生很重要的事件,但是并不是錯誤時,如用戶登錄密碼錯誤
INFO:處理請求或者狀態(tài)變化等日常事務
DEBUG:調(diào)試過程中使用DEBUG等級,如算法中每個循環(huán)的中間狀態(tài)

foamat可以格式化輸出,其參數(shù)有如下:

%(levelno)s:打印日志級別的數(shù)值
%(levelname)s:打印日志級別的名稱
%(pathname)s:打印當前執(zhí)行程序的路徑,其實就是sys.argv[0]
%(filename)s:打印當前執(zhí)行程序名
%(funcName)s:打印日志的當前函數(shù)
%(lineno)d:打印日志的當前行號
%(asctime)s:打印日志的時間
%(thread)d:打印線程ID
%(threadName)s:打印線程名稱
%(process)d:打印進程ID
%(message)s:打印日志信息

捕獲異常,以下兩行代碼都具有相同的作用

logger.exception(msg,_args)
logger.error(msg,exc_info = True,_args)

保存到文件,并輸出到命令行

這個用法直接 copy 使用就行

import logging
# 寫入文件
import logging
logger = logging.getLogger(__name__)
logger.setLevel(level=logging.INFO)
handler = logging.FileHandler("info.log")
handler.setLevel(logging.INFO)
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
handler.setFormatter(formatter)
logger.addHandler(handler)
logger.info("Log level info")
logger.debug("Log level debug")
logger.warning("Log level warning")
# 寫入文件,同時輸出到屏幕
import logging
logger = logging.getLogger(__name__)
logger.setLevel(level = logging.INFO)
handler = logging.FileHandler("info.log")
handler.setLevel(logging.INFO)
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
handler.setFormatter(formatter)
console = logging.StreamHandler()
console.setLevel(logging.INFO)
logger.addHandler(handler)
logger.addHandler(console)
logger.info("Log level info")
logger.debug("Log level debug")
logger.warning("Log level warning")

多模塊使用 logging

被調(diào)用者的日志格式會與調(diào)用者的日志格式一樣 main.py

# -*- coding: utf-8 -*-
__auth__ = 'zone'
__date__ = '2019/6/17 下午11:46'
'''
公眾號:zone7

小程序:編程面試題庫

'''
import os
import logging
from python.logging_model.code import sub_of_main
logger = logging.getLogger("zone7Model")
logger.setLevel(level=logging.INFO)
handler = logging.FileHandler("log.txt")
handler.setLevel(logging.INFO)
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
handler.setFormatter(formatter)
console = logging.StreamHandler()
console.setLevel(logging.INFO)
console.setFormatter(formatter)
logger.addHandler(handler)
logger.addHandler(console)
sub = sub_of_main.SubOfMain()
logger.info("main module log")
sub.print_some_log()
sub_of_main.py
# -*- coding: utf-8 -*-
__auth__ = 'zone'
__date__ = '2019/6/17 下午11:47'
'''

公眾號:zone7

小程序:編程面試題庫

'''
import logging
module_logger = logging.getLogger("zone7Model.sub.module")
class SubOfMain(object):
  def __init__(self):
    self.logger = logging.getLogger("zone7Model.sub.module")
    self.logger.info("init sub class")
  def print_some_log(self):
    self.logger.info("sub class log is printed")

def som_function():
  module_logger.info("call function some_function")

使用配置文件配置 logging

這里分別給出了兩種配置文件的使用案例,都分別使用了三種輸出,輸出到命令行、輸出到文件、將錯誤信息獨立輸出到一個文件

log_cfg.json
{
  "version":1,
  "disable_existing_loggers":false,
  "formatters":{
    "simple":{
      "format":"%(asctime)s - %(name)s - %(levelname)s - %(message)s"
    }
  },
  "handlers":{
    "console":{
      "class":"logging.StreamHandler",
      "level":"DEBUG",
      "formatter":"simple",
      "stream":"ext://sys.stdout"
    },
    "info_file_handler":{
      "class":"logging.handlers.RotatingFileHandler",
      "level":"INFO",
      "formatter":"simple",
      "filename":"info.log",
      "maxBytes":10485760,
      "backupCount":20,
      "encoding":"utf8"
    },
    "error_file_handler":{
      "class":"logging.handlers.RotatingFileHandler",
      "level":"ERROR",
      "formatter":"simple",
      "filename":"errors.log",
      "maxBytes":10485760,
      "backupCount":20,
      "encoding":"utf8"
    }
  },
  "loggers":{
    "my_module":{
      "level":"ERROR",
      "handlers":["info_file_handler2"],
      "propagate":"no"
    }
  },
  "root":{
    "level":"INFO",
    "handlers":["console","info_file_handler","error_file_handler"]
  }
}

通過 json 文件讀取配置:

import json
import logging.config
import os
def set_log_cfg(default_path="log_cfg.json", default_level=logging.INFO, env_key="LOG_CFG"):
  path = default_path
  value = os.getenv(env_key, None)
  if value:
    path = value
  if os.path.exists(path):
    with open(path, "r") as f:
      config = json.load(f)
      logging.config.dictConfig(config)
  else:
    logging.basicConfig(level=default_level)
def record_some_thing():
  logging.info("Log level info")
  logging.debug("Log level debug")
  logging.warning("Log level warning")
if __name__ == "__main__":
  set_log_cfg(default_path="log_cfg.json")
  record_some_thing()
log_cfg.yaml
version: 1
disable_existing_loggers: False
formatters:
    simple:
      format: "%(asctime)s - %(name)s - %(levelname)s - %(message)s"
handlers:
  console:
      class: logging.StreamHandler
      level: DEBUG
      formatter: simple
      stream: ext://sys.stdout
  info_file_handler:
      class: logging.handlers.RotatingFileHandler
      level: INFO
      formatter: simple
      filename: info.log
      maxBytes: 10485760
      backupCount: 20
      encoding: utf8
  error_file_handler:
      class: logging.handlers.RotatingFileHandler
      level: ERROR
      formatter: simple
      filename: errors.log
      maxBytes: 10485760
      backupCount: 20
      encoding: utf8
loggers:
  my_module:
      level: ERROR
      handlers: [info_file_handler]
      propagate: no
root:
  level: INFO
  handlers: [console,info_file_handler,error_file_handler]

通過 yaml 文件讀取配置:

import yaml
import logging.config
import os
def set_log_cfg(default_path="log_cfg.yaml", default_level=logging.INFO, env_key="LOG_CFG"):
  path = default_path
  value = os.getenv(env_key, None)
  if value:
    path = value
  if os.path.exists(path):
    with open(path, "r") as f:
      config = yaml.load(f)
      logging.config.dictConfig(config)
  else:
    logging.basicConfig(level=default_level)
def record_some_thing():
  logging.info("Log level info")
  logging.debug("Log level debug")
  logging.warning("Log level warning")
if __name__ == "__main__":
  set_log_cfg(default_path="log_cfg.yaml")
  record_some_thing()

以上是“Python線上環(huán)境使用日志的及配置文件的示例分析”這篇文章的所有內(nèi)容,感謝各位的閱讀!相信大家都有了一定的了解,希望分享的內(nèi)容對大家有所幫助,如果還想學習更多知識,歡迎關注創(chuàng)新互聯(lián)成都網(wǎng)站設計公司行業(yè)資訊頻道!

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

網(wǎng)頁題目:Python線上環(huán)境使用日志的及配置文件的示例分析-創(chuàng)新互聯(lián)
文章分享:http://www.muchs.cn/article14/hgdde.html

成都網(wǎng)站建設公司_創(chuàng)新互聯(lián),為您提供App設計、網(wǎng)站策劃、網(wǎng)站制作、網(wǎng)頁設計公司域名注冊、自適應網(wǎng)站

廣告

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

成都app開發(fā)公司