增加记录日志到MongoDB数据库的功能

This commit is contained in:
chenxy123 2017-01-05 22:57:08 +08:00
parent 304c6a9fdb
commit 12af4af14c
4 changed files with 29 additions and 3 deletions

View File

@ -4,6 +4,7 @@
"mongoHost": "localhost",
"mongoPort": 27017,
"mongoLogging": true,
"darkStyle": true
}

View File

@ -81,3 +81,6 @@ CURRENCY_CNY = 'CNY' # 人民币
CURRENCY_HKD = 'HKD' # 港币
CURRENCY_UNKNOWN = 'UNKNOWN' # 未知货币
CURRENCY_NONE = '' # 空货币
# 数据库
LOG_DB_NAME = 'VnTrader_Log_Db'

View File

@ -2,6 +2,7 @@
import shelve
from collections import OrderedDict
from datetime import datetime
from pymongo import MongoClient
from pymongo.errors import ConnectionFailure
@ -22,6 +23,9 @@ class MainEngine(object):
#----------------------------------------------------------------------
def __init__(self):
"""Constructor"""
# 记录今日日期
self.todayDate = datetime.now().strftime('%Y%m%d')
# 创建事件引擎
self.eventEngine = EventEngine()
self.eventEngine.start()
@ -236,7 +240,7 @@ class MainEngine(object):
"""连接MongoDB数据库"""
if not self.dbClient:
# 读取MongoDB的设置
host, port = loadMongoSetting()
host, port, logging = loadMongoSetting()
try:
# 设置MongoDB操作的超时时间为0.5秒
@ -246,6 +250,11 @@ class MainEngine(object):
self.dbClient.server_info()
self.writeLog(u'MongoDB连接成功')
# 如果启动日志记录,则注册日志事件监听函数
if logging:
self.eventEngine.register(EVENT_LOG, self.dbLogging)
except ConnectionFailure:
self.writeLog(u'MongoDB连接失败')
@ -281,6 +290,17 @@ class MainEngine(object):
else:
self.writeLog(u'数据更新失败MongoDB没有连接')
#----------------------------------------------------------------------
def dbLogging(self, event):
"""向MongoDB中插入日志"""
log = event.dict_['data']
d = {
'content': log.logContent,
'time': log.logTime,
'gateway': log.gatewayName
}
self.dbInsert(LOG_DB_NAME, self.todayDate, d)
#----------------------------------------------------------------------
def getContract(self, vtSymbol):
"""查询合约"""

View File

@ -40,11 +40,13 @@ def loadMongoSetting():
setting = json.load(f)
host = setting['mongoHost']
port = setting['mongoPort']
logging = setting['mongoLogging']
except:
host = 'localhost'
port = 27017
logging = False
return host, port
return host, port, logging
#----------------------------------------------------------------------
def todayDate():