import logging
import logging.handlers
import os
import threading
import queue
class MyLog(threading.Thread):
def __init__(self,fileName):
threading.Thread.__init__(self)
self.name = fileName
self.m_dataQueue = queue.Queue()
self.m_running = False
filePath = os.path.join(os.path.abspath('.'),'log')
if not os.path.exists(filePath):
os.mkdir(filePath)
fileName = os.path.join(filePath,fileName)
self.logger = logging.getLogger(fileName)
self.logger.setLevel(level = logging.DEBUG)
fileHandler = logging.handlers.RotatingFileHandler(filename=fileName,mode='a+',maxBytes=1024*1024*100,backupCount=100,encoding='utf-8')
fileHandler.setLevel(logging.DEBUG)
formatter = logging.Formatter('%(asctime)s - %(levelname)s - %(message)s ---%(filename)s-%(lineno)d')
fileHandler.setFormatter(formatter)
self.logger.addHandler(fileHandler)
def run(self):
self.m_running = True
while self.m_running:
data = self.m_dataQueue.get()
if data is None:
continue
loglevel = list(data.keys())[0]
content = list(data.values())[0]
if 'debug' == loglevel:
self.logger.debug(*content)
elif 'info' == loglevel:
self.logger.info(*content)
elif 'warning' == loglevel:
self.logger.warning(*content)
elif 'error' == loglevel:
self.logger.error(*content)
elif 'critical' == loglevel:
self.logger.critical(*content)
def stop(self):
self.m_running = False
self.m_dataQueue.put(None)
def debug(self,*content):
self.m_dataQueue.put({'debug':content})
def info(self,*content):
self.m_dataQueue.put({'info':content})
def warning(self,*content):
self.m_dataQueue.put({'warning':content})
def error(self,*content):
self.m_dataQueue.put({'error':content})
def critical(self,*content):
self.m_dataQueue.put({'critical':content})
logDebug = MyLog('bar_debug.log')
logDebug.setDaemon(True)
logDebug.start()
logInfo = MyLog('bar_info.log')
logInfo.setDaemon(True)
logInfo.start()
logError = MyLog('bar_error.log')
logError.setDaemon(True)
logError.start()
logHqRecv = MyLog('bar_hq.log')
logHqRecv.setDaemon(True)
logHqRecv.start()
logCritical = MyLog('bar_critical.log')
logCritical.setDaemon(True)
logCritical.start()
logHeartBeat = MyLog('bar_heartbeat.log')
logHeartBeat.setDaemon(True)
logHeartBeat.start()
logNotInTradeTime = MyLog('bar_notintradetime.log')
logNotInTradeTime.setDaemon(True)
logNotInTradeTime.start()
logSql = MyLog('bar_sql.log')
logSql.setDaemon(True)
logSql.start()
python3 异步记日志
最新推荐文章于 2024-02-20 16:08:14 发布