forked from mi8882255/3dprinteros-client
-
Notifications
You must be signed in to change notification settings - Fork 0
/
log.py
243 lines (221 loc) · 8.82 KB
/
log.py
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
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#Copyright (c) 2015 3D Control Systems LTD
#3DPrinterOS client is free software: you can redistribute it and/or modify
#it under the terms of the GNU Affero General Public License as published by
#the Free Software Foundation, either version 3 of the License, or
#(at your option) any later version.
#3DPrinterOS client is distributed in the hope that it will be useful,
#but WITHOUT ANY WARRANTY; without even the implied warranty of
#MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
#GNU Affero General Public License for more details.
#You should have received a copy of the GNU Affero General Public License
#along with 3DPrinterOS client. If not, see <http://www.gnu.org/licenses/>.
# Author: Vladimir Avdeev <another.vic@yandex.ru>, Oleg Panasevych <panasevychol@gmail.com>
import os
import sys
import time
import zipfile
import logging
import logging.handlers
import traceback
import shutil
import platform
import os.path
import paths
import requests
import http_client
import config
import version
import subprocess
LOG_SNAPSHOT_LINES = 200
SETTINGS_FOLDER = paths.current_settings_folder()
LOG_FILE = os.path.join(SETTINGS_FOLDER, "3dprinteros_client.log")
EXCEPTIONS_LOG_FILE = os.path.join(SETTINGS_FOLDER, 'critical_errors.log')
CLOUD_SYNC_LOG_FILE = os.path.join(SETTINGS_FOLDER, '3dprinteros_cloudsync.log')
CAMERA_LOG_FILE = os.path.join(SETTINGS_FOLDER, "3dprinteros_camera.log")
LOG_SNAPSHOTS_DIR = os.path.join(SETTINGS_FOLDER, 'log_snapshots')
REPORT_FILE_NAME = 'problem_report.txt'
REPORT_FILE_PATH = os.path.join(LOG_SNAPSHOTS_DIR, REPORT_FILE_NAME)
LOG_FILE_SIZE = 1024*1024*10#(10MB)
LOG_BACKUPS = 10
def create_logger(logger_name, log_file_name=None):
logger = logging.getLogger(logger_name)
logger.propagate = False
logger.setLevel(logging.DEBUG)
std_handler = logging.StreamHandler(stream=sys.stdout)
std_handler.setLevel(logging.DEBUG)
logger.addHandler(std_handler)
if log_file_name:
try:
os.remove(log_file_name)
except:
pass
try:
file_handler = logging.FileHandler(log_file_name)
file_handler.setFormatter(logging.Formatter('%(levelname)s\t%(asctime)s\t%(threadName)s/%(funcName)s\t%(message)s'))
file_handler.setLevel(logging.DEBUG)
logger.addHandler(file_handler)
print "File logger created: " + log_file_name
except Exception as e:
logger.debug('Could not create log file because' + e.message + '\n.No log mode.')
return logger
def log_exception(func_or_method):
def decorator(*args, **kwargs):
try:
result = func_or_method(*args, **kwargs)
except SystemExit:
pass
except:
trace = traceback.format_exc()
print trace
with open(EXCEPTIONS_LOG_FILE, "a") as f:
f.write(time.ctime() + "\n" + trace + "\n")
sys.exit(0)
else:
return result
return decorator
def prepare_logs_to_send():
log_files = []
logger = logging.getLogger("app." + __name__)
for handler in logger.handlers:
handler.flush()
possible_paths = paths.get_paths_to_settings_folder()
for path in possible_paths:
for log in os.listdir(path):
try:
if log.startswith(os.path.basename(LOG_FILE))\
or log.startswith(os.path.basename(EXCEPTIONS_LOG_FILE))\
or log.startswith(os.path.basename(CLOUD_SYNC_LOG_FILE)):
log_files.append(os.path.join(path, log))
except Exception:
continue
if not log_files:
logger.info('Log files was not created for some reason. Nothing to send')
return
if not os.path.exists(LOG_SNAPSHOTS_DIR):
try:
os.mkdir(LOG_SNAPSHOTS_DIR)
except Exception as e:
logger.warning("Can't create directory %s" % LOG_SNAPSHOTS_DIR)
return e
for fname in log_files:
shutil.copyfile(fname, os.path.join(LOG_SNAPSHOTS_DIR, os.path.basename(fname)))
def get_paths_to_logs_snapshots(log_file_names):
for number, name in enumerate(log_file_names):
log_file_names[number] = os.path.abspath(os.path.join(LOG_SNAPSHOTS_DIR, name))
return log_file_names
def compress_and_send(user_token, log_file_names=None):
if not log_file_names:
return
logger = logging.getLogger('app.' + __name__)
zip_file_name = time.strftime("%Y_%m_%d___%H_%M_%S", time.localtime()) + ".zip"
zip_file_name_path = os.path.abspath(os.path.join(LOG_SNAPSHOTS_DIR, zip_file_name))
logger.info('Creating zip file : ' + zip_file_name)
try:
zf = zipfile.ZipFile(zip_file_name_path, mode='w')
for name in log_file_names:
if not name.endswith('zip'):
zf.write(name, os.path.basename(name), compress_type=zipfile.ZIP_DEFLATED)
zf.close()
except Exception as e:
logger.warning("Error while creating logs archive " + zip_file_name)
logger.warning('Error: ' + e.message)
else:
get_path = http_client.HTTPClient()
url = 'https://' + get_path.URL + get_path.token_send_logs_path
data = {'user_token': user_token}
if os.path.exists(REPORT_FILE_PATH):
with open(REPORT_FILE_PATH) as f:
data['problem_report'] = f.read()
logger.info('Sending logs to %s' % url)
with open(zip_file_name_path, 'rb') as f:
files = {'file_data': f}
r = requests.post(url, data=data, files=files)
result = r.text
logger.info("Log sending response: " + result)
os.remove(zip_file_name_path)
if '"success":true' in result:
for name in log_file_names:
os.remove(name)
else:
logger.warning('Error while sending logs: %s' % result)
return result
def send_logs():
logger = logging.getLogger('app.' + __name__)
prepare_logs_to_send()
try:
snapshot_files = os.listdir(LOG_SNAPSHOTS_DIR)
except OSError:
logging.info("No logs snapshots to send")
else:
#print '\n\n%s\n\n' % str(file_name)
error = compress_and_send(config.get_app().user_login.user_token, get_paths_to_logs_snapshots(snapshot_files))
if error:
logger.warning('Error while sending logs: ' + error)
return error
logger.debug('Logs successfully sent')
def tail(f, lines=200):
total_lines_wanted = lines
BLOCK_SIZE = 1024
f.seek(0, 2)
block_end_byte = f.tell()
lines_to_go = total_lines_wanted
block_number = -1
blocks = [] # blocks of size BLOCK_SIZE, in reverse order starting
# from the end of the file
while lines_to_go > 0 and block_end_byte > 0:
if (block_end_byte - BLOCK_SIZE > 0):
# read the last block we haven't yet read
f.seek(block_number*BLOCK_SIZE, 2)
blocks.append(f.read(BLOCK_SIZE))
else:
# file too small, start from begining
f.seek(0,0)
# only read what was not read
blocks.append(f.read(block_end_byte))
lines_found = blocks[-1].count('\n')
lines_to_go -= lines_found
block_end_byte -= BLOCK_SIZE
block_number -= 1
all_read_text = ''.join(reversed(blocks))
return '\n'.join(all_read_text.splitlines()[-total_lines_wanted:])
def get_file_tail(file_path):
if os.path.isfile(file_path):
with open(file_path) as file:
f = file.readlines()
file_tail = []
for line in range(-1,-100, -1):
try:
file_tail.append(f[line])
except IndexError:
break
return file_tail
def create_report(report_text):
report_text = 'Version: ' + version.version + version.build + \
'\nOperating system: ' + platform.system() + ' ' + platform.release() + '\n\n' + report_text
paths.check_and_create_dirs(REPORT_FILE_PATH)
with open(REPORT_FILE_PATH, 'w') as f:
f.write(report_text)
def report_problem(report_text):
create_report(report_text)
result = send_logs()
return result
def clear_logs():
logger = logging.getLogger('app.' + __name__)
logger.info('Cleaning logs...')
log_file_names = os.listdir(SETTINGS_FOLDER)
for name in log_file_names:
if '.log' in name:
path = os.path.join(SETTINGS_FOLDER, name)
os.remove(path)
logger.info('Log file removed: ' + path)
logger.info('...logs cleared')
def open_settings_folder():
path = os.path.abspath(SETTINGS_FOLDER)
if sys.platform.startswith('darwin'):
subprocess.Popen(['open', path])
elif sys.platform.startswith('linux'):
subprocess.Popen(['xdg-open', path])
elif sys.platform.startswith('win32'):
subprocess.Popen(['explorer', path])