Coverage for tests/test_logging.py: 8%

194 statements  

« prev     ^ index     » next       coverage.py v7.2.7, created at 2023-07-14 19:21 +0000

1# This file is part of daf_butler. 

2# 

3# Developed for the LSST Data Management System. 

4# This product includes software developed by the LSST Project 

5# (http://www.lsst.org). 

6# See the COPYRIGHT file at the top-level directory of this distribution 

7# for details of code ownership. 

8# 

9# This program is free software: you can redistribute it and/or modify 

10# it under the terms of the GNU General Public License as published by 

11# the Free Software Foundation, either version 3 of the License, or 

12# (at your option) any later version. 

13# 

14# This program is distributed in the hope that it will be useful, 

15# but WITHOUT ANY WARRANTY; without even the implied warranty of 

16# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 

17# GNU General Public License for more details. 

18# 

19# You should have received a copy of the GNU General Public License 

20# along with this program. If not, see <http://www.gnu.org/licenses/>. 

21 

22import io 

23import logging 

24import tempfile 

25import unittest 

26from logging import FileHandler, StreamHandler 

27 

28import lsst.utils.logging 

29from lsst.daf.butler.core.logging import ( 

30 ButlerLogRecord, 

31 ButlerLogRecordHandler, 

32 ButlerLogRecords, 

33 ButlerMDC, 

34 JsonLogFormatter, 

35) 

36from lsst.utils.logging import VERBOSE 

37 

38 

39class LoggingTestCase(unittest.TestCase): 

40 """Test we can capture log messages.""" 

41 

42 def setUp(self): 

43 self.handler = ButlerLogRecordHandler() 

44 

45 self.log = lsst.utils.logging.getLogger(self.id()) 

46 self.log.addHandler(self.handler) 

47 

48 def tearDown(self): 

49 if self.handler and self.log: 

50 self.log.removeHandler(self.handler) 

51 ButlerMDC.restore_log_record_factory() 

52 

53 def testRecordCapture(self): 

54 """Test basic log capture and serialization.""" 

55 self.log.setLevel(VERBOSE) 

56 

57 test_messages = ( 

58 (logging.INFO, "This is a log message", True), 

59 (logging.WARNING, "This is a warning message", True), 

60 (logging.DEBUG, "This debug message should not be stored", False), 

61 (VERBOSE, "A verbose message should appear", True), 

62 ) 

63 

64 for level, message, _ in test_messages: 

65 self.log.log(level, message) 

66 

67 expected = [info for info in test_messages if info[2]] 

68 

69 self.assertEqual(len(self.handler.records), len(expected)) 

70 

71 for given, record in zip(expected, self.handler.records): 

72 self.assertEqual(given[0], record.levelno) 

73 self.assertEqual(given[1], record.message) 

74 

75 # Check that we can serialize the records 

76 json = self.handler.records.json() 

77 

78 records = ButlerLogRecords.parse_raw(json) 

79 for original_record, new_record in zip(self.handler.records, records): 

80 self.assertEqual(new_record, original_record) 

81 self.assertEqual(str(records), str(self.handler.records)) 

82 

83 # Create stream form of serialization. 

84 json_stream = "\n".join(record.json() for record in records) 

85 

86 # Also check we can autodetect the format. 

87 for raw in (json, json.encode(), json_stream, json_stream.encode()): 

88 records = ButlerLogRecords.from_raw(json) 

89 self.assertEqual(records, self.handler.records) 

90 

91 for raw in ("", b""): 

92 self.assertEqual(len(ButlerLogRecords.from_raw(raw)), 0) 

93 self.assertEqual(len(ButlerLogRecords.from_stream(io.StringIO())), 0) 

94 

95 # Send bad text to the parser and it should fail (both bytes and str). 

96 bad_text = "x" * 100 

97 

98 # Include short and long values to trigger different code paths 

99 # in error message creation. 

100 for trim in (True, False): 

101 for bad in (bad_text, bad_text.encode()): 

102 bad = bad[:10] if trim else bad 

103 with self.assertRaises(ValueError) as cm: 

104 ButlerLogRecords.from_raw(bad) 

105 if not trim: 

106 self.assertIn("...", str(cm.exception)) 

107 

108 def testRecordsFormatting(self): 

109 self.log.setLevel(logging.DEBUG) 

110 self.log.debug("debug message") 

111 self.log.warning("warning message") 

112 self.log.critical("critical message") 

113 self.log.verbose("verbose message") 

114 

115 self.assertEqual(len(self.handler.records), 4) 

116 

117 format_default = str(self.handler.records) 

118 

119 # Set the format for these records. 

120 self.handler.records.set_log_format("{levelname}") 

121 format_override = str(self.handler.records) 

122 

123 self.assertNotEqual(format_default, format_override) 

124 self.assertEqual(format_override, "DEBUG\nWARNING\nCRITICAL\nVERBOSE") 

125 

126 # Reset the log format and it should match the original text. 

127 self.handler.records.set_log_format(None) 

128 self.assertEqual(str(self.handler.records), format_default) 

129 

130 def testButlerLogRecords(self): 

131 """Test the list-like methods of ButlerLogRecords.""" 

132 self.log.setLevel(logging.INFO) 

133 

134 n_messages = 10 

135 message = "Message #%d" 

136 for counter in range(n_messages): 

137 self.log.info(message, counter) 

138 

139 records = self.handler.records 

140 self.assertEqual(len(records), n_messages) 

141 

142 # Test slicing. 

143 start = 2 

144 end = 6 

145 subset = records[start:end] 

146 self.assertIsInstance(subset, ButlerLogRecords) 

147 self.assertEqual(len(subset), end - start) 

148 self.assertIn(f"#{start}", subset[0].message) 

149 

150 # Reverse the collection. 

151 backwards = list(reversed(records)) 

152 self.assertEqual(len(backwards), len(records)) 

153 self.assertEqual(records[0], backwards[-1]) 

154 

155 # Test some of the collection manipulation methods. 

156 record_0 = records[0] 

157 records.reverse() 

158 self.assertEqual(records[-1], record_0) 

159 self.assertEqual(records.pop(), record_0) 

160 records[0] = record_0 

161 self.assertEqual(records[0], record_0) 

162 len_records = len(records) 

163 records.insert(2, record_0) 

164 self.assertEqual(len(records), len_records + 1) 

165 self.assertEqual(records[0], records[2]) 

166 

167 # Put the subset records back onto the end of the original. 

168 records.extend(subset) 

169 self.assertEqual(len(records), n_messages + len(subset)) 

170 

171 # Test slice for deleting 

172 initial_length = len(records) 

173 start_del = 1 

174 end_del = 3 

175 del records[start_del:end_del] 

176 self.assertEqual(len(records), initial_length - (end_del - start_del)) 

177 

178 records.clear() 

179 self.assertEqual(len(records), 0) 

180 

181 with self.assertRaises(ValueError): 

182 records.append({}) 

183 

184 def testExceptionInfo(self): 

185 self.log.setLevel(logging.DEBUG) 

186 try: 

187 raise RuntimeError("A problem has been encountered.") 

188 except RuntimeError: 

189 self.log.exception("Caught") 

190 

191 self.assertIn("A problem has been encountered", self.handler.records[0].exc_info) 

192 

193 self.log.warning("No exc_info") 

194 self.assertIsNone(self.handler.records[-1].exc_info) 

195 

196 try: 

197 raise RuntimeError("Debug exception log") 

198 except RuntimeError: 

199 self.log.debug("A problem", exc_info=1) 

200 

201 self.assertIn("Debug exception", self.handler.records[-1].exc_info) 

202 

203 def testMDC(self): 

204 """Test that MDC information appears in messages.""" 

205 self.log.setLevel(logging.INFO) 

206 

207 i = 0 

208 self.log.info("Message %d", i) 

209 i += 1 

210 self.assertEqual(self.handler.records[-1].MDC, {}) 

211 

212 ButlerMDC.add_mdc_log_record_factory() 

213 label = "MDC value" 

214 ButlerMDC.MDC("LABEL", label) 

215 self.log.info("Message %d", i) 

216 self.assertEqual(self.handler.records[-1].MDC["LABEL"], label) 

217 

218 # Change the label and check that the previous record does not 

219 # itself change. 

220 ButlerMDC.MDC("LABEL", "dataId") 

221 self.assertEqual(self.handler.records[-1].MDC["LABEL"], label) 

222 

223 # Format a record with MDC. 

224 record = self.handler.records[-1] 

225 

226 # By default the MDC label should not be involved. 

227 self.assertNotIn(label, str(record)) 

228 

229 # But it can be included. 

230 fmt = "x{MDC[LABEL]}" 

231 self.assertEqual(record.format(fmt), "x" + label) 

232 

233 # But can be optional on a record that didn't set it. 

234 self.assertEqual(self.handler.records[0].format(fmt), "x") 

235 

236 # Set an extra MDC entry and include all content. 

237 extra = "extra" 

238 ButlerMDC.MDC("EXTRA", extra) 

239 

240 i += 1 

241 self.log.info("Message %d", i) 

242 formatted = self.handler.records[-1].format("x{MDC} - {message}") 

243 self.assertIn(f"EXTRA={extra}", formatted) 

244 self.assertIn("LABEL=dataId", formatted) 

245 self.assertIn(f"Message {i}", formatted) 

246 

247 # Clear the MDC and ensure that it does not continue to appear 

248 # in messages. 

249 ButlerMDC.MDCRemove("LABEL") 

250 i += 1 

251 self.log.info("Message %d", i) 

252 self.assertEqual(self.handler.records[-1].format(fmt), "x") 

253 self.assertEqual(self.handler.records[-1].format("{message}"), f"Message {i}") 

254 

255 # MDC context manager 

256 fmt = "x{MDC[LABEL]} - {message}" 

257 ButlerMDC.MDC("LABEL", "original") 

258 with ButlerMDC.set_mdc({"LABEL": "test"}): 

259 i += 1 

260 self.log.info("Message %d", i) 

261 self.assertEqual(self.handler.records[-1].format(fmt), f"xtest - Message {i}") 

262 i += 1 

263 self.log.info("Message %d", i) 

264 self.assertEqual(self.handler.records[-1].format(fmt), f"xoriginal - Message {i}") 

265 

266 

267class TestJsonLogging(unittest.TestCase): 

268 """Test logging using JSON.""" 

269 

270 def testJsonLogStream(self): 

271 log = logging.getLogger(self.id()) 

272 log.setLevel(logging.INFO) 

273 

274 # Log to a stream and also to a file. 

275 formatter = JsonLogFormatter() 

276 

277 stream = io.StringIO() 

278 stream_handler = StreamHandler(stream) 

279 stream_handler.setFormatter(formatter) 

280 log.addHandler(stream_handler) 

281 

282 file = tempfile.NamedTemporaryFile(suffix=".json") 

283 filename = file.name 

284 file.close() 

285 

286 file_handler = FileHandler(filename) 

287 file_handler.setFormatter(formatter) 

288 log.addHandler(file_handler) 

289 

290 log.info("A message") 

291 log.warning("A warning") 

292 

293 # Add a blank line to the stream to check the parser ignores it. 

294 print(file=stream) 

295 

296 # Rewind the stream and pull messages out of it. 

297 stream.seek(0) 

298 records = ButlerLogRecords.from_stream(stream) 

299 self.assertIsInstance(records[0], ButlerLogRecord) 

300 self.assertEqual(records[0].message, "A message") 

301 self.assertEqual(records[1].levelname, "WARNING") 

302 

303 # Now read from the file. Add two blank lines to test the parser 

304 # will filter them out. 

305 file_handler.close() 

306 

307 with open(filename, "a") as fd: 

308 print(file=fd) 

309 print(file=fd) 

310 

311 file_records = ButlerLogRecords.from_file(filename) 

312 self.assertEqual(file_records, records) 

313 

314 # And read the file again in bytes and text. 

315 for mode in ("rb", "r"): 

316 with open(filename, mode) as fd: 

317 file_records = ButlerLogRecords.from_stream(fd) 

318 self.assertEqual(file_records, records) 

319 fd.seek(0) 

320 file_records = ButlerLogRecords.from_raw(fd.read()) 

321 self.assertEqual(file_records, records) 

322 

323 # Serialize this model to stream. 

324 stream2 = io.StringIO() 

325 print(records.json(), file=stream2) 

326 stream2.seek(0) 

327 stream_records = ButlerLogRecords.from_stream(stream2) 

328 self.assertEqual(stream_records, records) 

329 

330 

331if __name__ == "__main__": 

332 unittest.main()