-
Notifications
You must be signed in to change notification settings - Fork 349
Expand file tree
/
Copy pathLogger.py
More file actions
183 lines (152 loc) · 6.18 KB
/
Logger.py
File metadata and controls
183 lines (152 loc) · 6.18 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
# coding=utf-8
import atexit
import datetime
import io
import json
import sys
import time
import ConsoleUtils
import modules.Configuration as Config
from RingBuffer import RingBuffer
from Notify import send_notification
class ConsoleOutput(object):
def __init__(self):
self._status = ''
atexit.register(self._exit)
def _exit(self):
self._status += ' ' # In case the shell added a ^C
self.status('')
def status(self, msg, time='', days_remaining_msg=''):
status = str(msg)
cols = ConsoleUtils.get_terminal_size()[0]
if msg != '' and len(status) > cols:
# truncate status, try preventing console bloating
status = str(msg)[:cols - 4] + '...'
update = '\r'
update += status
update += ' ' * (len(self._status) - len(status))
update += '\b' * (len(self._status) - len(status))
sys.stderr.write(update)
self._status = status
def printline(self, line):
update = '\r'
update += line + ' ' * (len(self._status) - len(line)) + '\n'
update += self._status
sys.stderr.write(update)
class JsonOutput(object):
def __init__(self, file, logLimit, exchange=''):
self.jsonOutputFile = file
self.jsonOutput = {}
self.clearStatusValues()
self.jsonOutputLog = RingBuffer(logLimit)
self.jsonOutput['exchange'] = exchange
self.jsonOutput['label'] = Config.get("BOT", "label", "Lending Bot")
def status(self, status, time, days_remaining_msg):
self.jsonOutput["last_update"] = time + days_remaining_msg
self.jsonOutput["last_status"] = status
def printline(self, line):
line = line.replace("\n", ' | ')
self.jsonOutputLog.append(line)
def writeJsonFile(self):
with io.open(self.jsonOutputFile, 'w', encoding='utf-8') as f:
self.jsonOutput["log"] = self.jsonOutputLog.get()
f.write(unicode(json.dumps(self.jsonOutput, ensure_ascii=False, sort_keys=True)))
f.close()
def addSectionLog(self, section, key, value):
if section not in self.jsonOutput:
self.jsonOutput[section] = {}
if key not in self.jsonOutput[section]:
self.jsonOutput[section][key] = {}
self.jsonOutput[section][key] = value
def statusValue(self, coin, key, value):
if coin not in self.jsonOutputCoins:
self.jsonOutputCoins[coin] = {}
self.jsonOutputCoins[coin][key] = str(value)
def clearStatusValues(self):
self.jsonOutputCoins = {}
self.jsonOutput["raw_data"] = self.jsonOutputCoins
self.jsonOutputCurrency = {}
self.jsonOutput["outputCurrency"] = self.jsonOutputCurrency
def outputCurrency(self, key, value):
self.jsonOutputCurrency[key] = str(value)
class Logger(object):
def __init__(self, json_file='', json_log_size=-1, exchange=''):
self._lent = ''
self._daysRemaining = ''
self.compactLog = False
if json_file != '' and json_log_size != -1:
self.output = JsonOutput(json_file, json_log_size, exchange)
self.compactLog = bool(Config.get('BOT', 'jsonlogcompact', False))
else:
self.output = ConsoleOutput()
self.refreshStatus()
@staticmethod
def timestamp():
ts = time.time()
return datetime.datetime.fromtimestamp(ts).strftime('%Y-%m-%d %H:%M:%S')
def log(self, msg):
log_message = "{0} {1}".format(self.timestamp(), msg)
self.output.printline(log_message)
self.refreshStatus()
def log_error(self, msg):
log_message = "{0} Error {1}".format(self.timestamp(), msg)
self.output.printline(log_message)
if isinstance(self.output, JsonOutput):
print log_message
self.refreshStatus()
def offer(self, amt, cur, rate, days, msg):
line = self.timestamp() + ' Placing ' + str(amt) + ' ' + str(cur) + ' at ' + str(
float(rate) * 100) + '% for ' + days + ' days... ' + self.digestApiMsg(msg)
self.output.printline(line)
if self.compactLog:
self.output.statusValue(cur, 'log', '')
self.refreshStatus()
def cancelOrder(self, cur, msg):
line = self.timestamp() + ' Canceling ' + str(cur) + ' order... ' + self.digestApiMsg(msg)
self.output.printline(line)
self.refreshStatus()
def notLending(self, cur, minRate, actRate):
if self.compactLog:
self.output.statusValue(cur, 'log',
'{:s} Not lending due to rate below {:.4f}% (actual: {:.4f}%)'
.format(self.timestamp(), (minRate * 100), (actRate * 100)))
else:
self.log('Not lending {:s} due to rate below {:.4f}% (actual: {:.4f}%)'
.format(cur, (minRate * 100), (actRate * 100)))
self.refreshStatus()
def refreshStatus(self, lent='', days_remaining=''):
if lent != '':
self._lent = lent
if days_remaining != '':
self._daysRemaining = days_remaining
self.output.status(self._lent, self.timestamp(), self._daysRemaining)
def addSectionLog(self, section, key, value):
if hasattr(self.output, 'addSectionLog'):
self.output.addSectionLog(section, key, value)
def updateStatusValue(self, coin, key, value):
if hasattr(self.output, 'statusValue'):
self.output.statusValue(coin, key, value)
def updateOutputCurrency(self, key, value):
if hasattr(self.output, 'outputCurrency'):
self.output.outputCurrency(key, value)
def persistStatus(self):
if hasattr(self.output, 'writeJsonFile'):
self.output.writeJsonFile()
if hasattr(self.output, 'clearStatusValues'):
self.output.clearStatusValues()
@staticmethod
def digestApiMsg(msg):
m = ""
try:
m = (msg['message'])
except KeyError:
pass
try:
m = (msg['error'])
except KeyError:
pass
return m
@staticmethod
def notify(msg, notify_conf):
if notify_conf['enable_notifications']:
send_notification(msg, notify_conf)