實現思路:新建乙個佇列,將logging的http 傳送任務放入佇列中。啟動乙個執行緒監控佇列情況,並從佇列依次取任務傳送。從而將日誌記錄和日誌傳送分離開,日誌傳送與業務功能**解耦,提高執行速率。
import pytz
import logging
from logging.handlers import rotatingfilehandler
from logging.handlers import queuehandler
from logging.handlers import queuelistener
from logging import handler
import os
from datetime import datetime
host = '' # 日誌接收的網域名稱
path = '/log' # 日誌接收path
# --------------------------------------------log queue------------------------
class slackqueuehandler(queuehandler):
"""日誌佇列"""
def __init__(self, queue=none):
queuehandler.__init__(self, queue)
def prepare(self, record):
"""override the method to allow the formatter to work.
"""record.msg = self.format(record)
record.args = none
record.exc_info = none
return record
class slackqueuelistener(queuelistener, handler):
"""日誌佇列監聽者,非同步傳送日誌"""
"""http log日誌傳送"""
def __init__(self, host, url, method="post", secure=false, credentials=none, context=none, report_id=none):
super().__init__(host, url, method=method, secure=secure, credentials=credentials, context=context)
self.report_id = report_id
def maplogrecord(self, record):
"""傳送內容"""
tz = pytz.timezone('asia/shanghai')
asctime = datetime.now(tz).strftime("%y-%m-%d %h:%m:%s")
if hasattr(record,'name') and hasattr(record, 'message'):
data =
else:
data =
record_ = '%(asctime)s | %(name)s | %(message)s' % dict(data)
record_msg =
print('----record msg----{}'.format(record_msg))
return record_msg
class testlogger():
def __init__(self, filepath, filename):
self.filepath = filepath # 存放檔案的路徑
self.filename = filename # 存放檔案的名字
# self.back_up_count = 5000 # 檔案分割上限數
# self.max_log_bytes = 1024 * 1024 * 10 # 單個檔案最大記錄數10m
self.create_handler() # 初始化建立日誌handler
self.create_logger() # 初始化建立logger
def create_handler(self):
"""建立handler"""
self.handler = rotatingfilehandler(filename=os.path.join(self.filepath, self.filename),
# maxbytes=self.max_log_bytes,
# backupcount=self.back_up_count,
delay=1
)formatter = logging.formatter('%(asctime)s | %(name)s | %(message)s') # 設定輸出格式
# formatter.converter = time.gmtime # 時間轉換
self.handler.setformatter(formatter) # 格式載入到handler
self.http_handler = testhttphandler(host=log_host, url=path, secure=secure) # 網域名稱不帶http:// , secure=false 表示http, secure=true 表示https 請求
def create_logger(self):
"""建立logger"""
Python logging日誌模組
1.日誌的級別 日誌一共分成5個等級,從低到高分別是 1 debug 2.info 3.warning 4.error 5.critical說明 這5個等級,也分別對應5種打日誌的方法 debug info warning error critical。預設的是 warning,當在warning或...
python logging日誌模組
logging模組是python的乙個標準庫模組,由標準庫模組提供日誌記錄api的關鍵好處是所有python模組都可以使用這個日誌記錄功能。所以,你的應用日誌可以將你自己的日誌資訊與來自第三方模組的資訊整合起來。1.日誌級別 logging模組預設定義了以下幾個日誌等級,開發應用程式或部署開發環境時...
python logging日誌設定
log等級,輸出格式,輸出檔名,檔案讀寫模式 logging.basicconfig level logging.debug,format asctime s filename s line lineno d levelname s message s filename log.txt filemo...