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
|
# Copyright (C) 2011, Aleksey Lim
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 2 of the License, or
# (at your option) any later version.
#
# This program 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 General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
import os
import sys
import atexit
import logging
import dbus
import cjson
_SHELL_SERVICE = "org.laptop.Shell"
_SHELL_PATH = "/org/laptop/Shell"
_SHELL_IFACE = "org.laptop.Shell"
_report = {}
_need_log = False
_log_formatter = None
def start(activity_id, log_path=None):
if log_path is None:
# TODO more portable solution
stdout_file = os.readlink('/proc/self/fd/%s' % sys.stdout.fileno())
if os.path.isfile(stdout_file):
log_path = stdout_file
else:
log_path = ''
atexit.register(_send, activity_id, log_path)
def trigger(key, need_log=False):
global _need_log
if key not in _report:
_report[key] = 0
_report[key] += 1
_need_log = _need_log or need_log
logging.debug('Feedback[%s] == %s', key, _report[key])
def flush():
global _report
global _need_log
report = _report
need_log = _need_log
_report = {}
_need_log = False
return report, need_log
def _send(activity_id, log_path):
if not _report:
return
report, need_log = flush()
bus = dbus.SessionBus()
bus_object = bus.get_object(_SHELL_SERVICE, _SHELL_PATH)
shell = dbus.Interface(bus_object, _SHELL_IFACE)
shell.Feedback(activity_id, cjson.encode(report),
log_path if need_log else '')
def _excepthook(exctype, value, tb):
global _log_formatter
if _log_formatter is None:
try:
# Attempt to provide verbose IPython tracebacks.
# Importing IPython is slow, so we import it lazily.
from IPython.ultraTB import AutoFormattedTB
formatter = AutoFormattedTB(mode='Verbose', color_scheme='NoColor')
_log_formatter = formatter.text
except ImportError:
import traceback
_log_formatter = \
lambda * args: ''.join(traceback.format_exception(*args))
message = _log_formatter(exctype, value, tb)
logging.error(message)
trigger('unhandled_exception', need_log=True)
sys.excepthook = _excepthook
|