# Coverage for utils/log.py : 36%

## 135 statements 54 run 81 missing 0 excluded 2 partial

Hot-keys on this page

r m x p toggle line displays

j k next/prev highlighted chunk

0 (zero) top of page

1 (one) first highlighted chunk

1# -*- coding: utf-8 -*-

2 from __future__ import annotations

3

4# -- stdlib --

5 from typing import Any

6 import datetime

7 import logging

8 import sys

9

10# -- third party --

11 from raven.handlers.logging import SentryHandler

12 from raven.transport.gevent import GeventedHTTPTransport

13 import gevent

14 import raven

15

16# -- own --

17 from utils.escapes import escape_codes

18

19

20# -- code --

21 class UnityLogHandler(logging.Handler):

22

23 def emit(self, rec):

24 msg = self.format(rec)

25

26 try:

27 from UnityEngine import Debug

28 if rec.levelno <= logging.DEBUG:

29 Debug.LogDebug(msg)

30 elif rec.levelno <= logging.INFO:

31 Debug.LogInfo(msg)

32 elif rec.levelno <= logging.ERROR:

33 Debug.LogError(msg)

34 else:

35 Debug.LogError(msg)

36 except Exception:

37 # fuck

38 pass

39

40

41 class _ServerLogFormatter_OLD(logging.Formatter):

42 def __init__(self, with_gr_name=True):

43 logging.Formatter.__init__(self)

44 self.with_gr_name = with_gr_name

45

46 def format(self, rec):

47

48 if rec.exc_info:

49 s = []

50 s.append('>>>>>>' + '-' * 74)

51 s.append(self._format(rec))

52 import traceback

53 s.append(''.join(traceback.format_exception(*rec.exc_info)).strip())

54 s.append('<<<<<<' + '-' * 74)

55 return '\n'.join(s)

56 else:

57 return self._format(rec)

58

59 def _format(self, rec):

60 import time

61 g = gevent.getcurrent()

62

63 if self.with_gr_name:

64 gr_name = ' ' + getattr(g, 'gr_name', repr(g))

65 else:

66 gr_name = ''

67

68 if rec.args:

69 msg = (rec.msg % rec.args) if isinstance(rec.msg, str) else repr((rec.msg, rec.args))

70 else:

71 msg = rec.msg

72

73 return '[%s %s%s] %s' % (

74 rec.levelname[0],

75 time.strftime('%y%m%d %H:%M:%S'),

76 gr_name,

77 msg,

78 )

79

80

81 class ServerLogFormatter(logging.Formatter):

82 def __init__(self, use_color=True):

83 super().__init__()

84 self.use_color = use_color

85 self.color_mapping = {

86 'CRITICAL': 'bold_red',

87 'ERROR': 'red',

88 'WARNING': 'yellow',

89 'INFO': 'green',

90 'DEBUG': 'blue',

91 }

92

93 def format(self, rec):

94

95 if rec.exc_info:

96 s = []

97 s.append('>>>>>>' + '-' * 74)

98 s.append(self._format(rec))

99 import traceback

100 s.append(''.join(traceback.format_exception(*rec.exc_info)).strip())

101 s.append('<<<<<<' + '-' * 74)

102 return '\n'.join(s)

103 else:

104 return self._format(rec)

105

106 def _format(self, rec):

107 import time

108 g = gevent.getcurrent()

109 gr_name = getattr(g, 'gr_name', None)

110 if not gr_name: 110 ↛ 111line 110 didn't jump to line 111, because the condition on line 110 was never true

111 if isinstance(g, gevent.Greenlet):

112 gr_name = repr(g)

113 else:

114 gr_name = '<RAW>'

115

116 rec.message = rec.getMessage()

117 lvl = rec.levelname

118 prefix = '[{} {} {}:{} {}]'.format(

119 lvl[0],

120 time.strftime('%y%m%d %H:%M:%S'),

121 rec.module,

122 rec.lineno,

123 gr_name,

124 )

125 if self.use_color: 125 ↛ 130line 125 didn't jump to line 130, because the condition on line 125 was never false

126 E = escape_codes

127 M = self.color_mapping

128 prefix = f"{E[M[lvl]]}{prefix}{E['reset']}"

129

130 return f'{prefix} {rec.message}'

131

132

133 def init(level, sentry_dsn, release):

134 patch_gevent_hub_print_exception()

135

136 root = logging.getLogger()

137 root.setLevel(0)

138

139 hdlr: Any

140

141 hdlr = logging.FileHandler('client_log.txt', encoding='utf-8')

142 hdlr.setLevel(logging.INFO)

143 root.addHandler(hdlr)

144

145 if sentry_dsn:

146 hdlr = SentryHandler(raven.Client(sentry_dsn, transport=GeventedHTTPTransport, release=release))

147 hdlr.setLevel(logging.ERROR)

148 root.addHandler(hdlr)

149

150 hdlr = logging.StreamHandler(sys.stdout)

151 hdlr.setLevel(getattr(logging, level))

152

153 logging.getLogger('sentry.errors').setLevel(1000)

154

155 formatter = ServerLogFormatter()

156 hdlr.setFormatter(formatter)

157 root.addHandler(hdlr)

158

159 root.info(datetime.datetime.now().strftime("%Y-%m-%d %H:%M"))

160 root.info('==============================================')

161

162

163 def init_unity(level, sentry_dsn, release):

164 root = logging.getLogger()

165 root.setLevel(0)

166

167 if sentry_dsn:

168 hdlr = SentryHandler(raven.Client(sentry_dsn, transport=GeventedHTTPTransport, release=release))

169 hdlr.setLevel(logging.ERROR)

170 root.addHandler(hdlr)

171

172 hdlr = UnityLogHandler()

173 hdlr.setLevel(level)

174 root.addHandler(hdlr)

175

176 root.info(datetime.datetime.now().strftime("%Y-%m-%d %H:%M"))

177 root.info('==============================================')

178

179

180 def init_server(level, sentry_dsn, release, logfile, with_gr_name=True):

181 patch_gevent_hub_print_exception()

182

183 root = logging.getLogger()

184 root.setLevel(level)

185

186 fmter = ServerLogFormatter()

187 std = logging.StreamHandler(stream=sys.stdout)

188 std.setFormatter(fmter)

189 root.addHandler(std)

190

191 if sentry_dsn:

192 hdlr = SentryHandler(raven.Client(sentry_dsn, transport=GeventedHTTPTransport, release=release))

193 hdlr.setLevel(logging.ERROR)

194 root.addHandler(hdlr)

195

196 logging.getLogger('sentry.errors').setLevel(1000)

197

198 if logfile:

199 from logging.handlers import WatchedFileHandler

200 filehdlr = WatchedFileHandler(logfile)

201 filehdlr.setFormatter(fmter)

202 root.addHandler(filehdlr)

203

204

205 def patch_gevent_hub_print_exception():

206 from gevent.hub import Hub

207

208 def print_exception(self, context, type, value, tb):

209 import logging

210 log = logging.getLogger('exception')

211 log.error(

212 '%s failed with %s',

213 context, getattr(type, '__name__', 'exception'),

214 exc_info=(type, value, tb),

215 )

216

217 Hub.print_exception = print_exception