Coverage for tests/test_logging.py: 8%
194 statements
« prev ^ index » next coverage.py v6.5.0, created at 2022-12-01 19:55 +0000
« prev ^ index » next coverage.py v6.5.0, created at 2022-12-01 19:55 +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/>.
22import unittest
23import io
24import logging
25import tempfile
26from logging import StreamHandler, FileHandler
28from lsst.daf.butler.core.logging import (
29 ButlerLogRecordHandler,
30 ButlerLogRecords,
31 VERBOSE,
32 JsonLogFormatter,
33 ButlerLogRecord,
34 ButlerMDC,
35)
38class LoggingTestCase(unittest.TestCase):
39 """Test we can capture log messages."""
41 def setUp(self):
42 self.handler = ButlerLogRecordHandler()
44 self.log = logging.getLogger(self.id())
45 self.log.addHandler(self.handler)
47 def tearDown(self):
48 if self.handler and self.log:
49 self.log.removeHandler(self.handler)
50 ButlerMDC.restore_log_record_factory()
52 def testRecordCapture(self):
53 """Test basic log capture and serialization."""
55 self.log.setLevel(VERBOSE)
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 )
64 for level, message, _ in test_messages:
65 self.log.log(level, message)
67 expected = [info for info in test_messages if info[2]]
69 self.assertEqual(len(self.handler.records), len(expected))
71 for given, record in zip(expected, self.handler.records):
72 self.assertEqual(given[0], record.levelno)
73 self.assertEqual(given[1], record.message)
75 # Check that we can serialize the records
76 json = self.handler.records.json()
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))
83 # Create stream form of serialization.
84 json_stream = "\n".join(record.json() for record in records)
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)
91 for raw in ("", b""):
92 self.assertEqual(len(ButlerLogRecords.from_raw(raw)), 0)
93 self.assertEqual(len(ButlerLogRecords.from_stream(io.StringIO())), 0)
95 # Send bad text to the parser and it should fail (both bytes and str).
96 bad_text = "x" * 100
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))
108 def testRecordsFormatting(self):
110 self.log.setLevel(logging.DEBUG)
111 self.log.debug("debug message")
112 self.log.warning("warning message")
113 self.log.critical("critical message")
114 self.log.log(VERBOSE, "verbose message")
116 self.assertEqual(len(self.handler.records), 4)
118 format_default = str(self.handler.records)
120 # Set the format for these records.
121 self.handler.records.set_log_format("{levelname}")
122 format_override = str(self.handler.records)
124 self.assertNotEqual(format_default, format_override)
125 self.assertEqual(format_override, "DEBUG\nWARNING\nCRITICAL\nVERBOSE")
127 # Reset the log format and it should match the original text.
128 self.handler.records.set_log_format(None)
129 self.assertEqual(str(self.handler.records), format_default)
131 def testButlerLogRecords(self):
132 """Test the list-like methods of ButlerLogRecords."""
134 self.log.setLevel(logging.INFO)
136 n_messages = 10
137 message = "Message #%d"
138 for counter in range(n_messages):
139 self.log.info(message, counter)
141 records = self.handler.records
142 self.assertEqual(len(records), n_messages)
144 # Test slicing.
145 start = 2
146 end = 6
147 subset = records[start:end]
148 self.assertIsInstance(subset, ButlerLogRecords)
149 self.assertEqual(len(subset), end - start)
150 self.assertIn(f"#{start}", subset[0].message)
152 # Reverse the collection.
153 backwards = list(reversed(records))
154 self.assertEqual(len(backwards), len(records))
155 self.assertEqual(records[0], backwards[-1])
157 # Test some of the collection manipulation methods.
158 record_0 = records[0]
159 records.reverse()
160 self.assertEqual(records[-1], record_0)
161 self.assertEqual(records.pop(), record_0)
162 records[0] = record_0
163 self.assertEqual(records[0], record_0)
164 len_records = len(records)
165 records.insert(2, record_0)
166 self.assertEqual(len(records), len_records + 1)
167 self.assertEqual(records[0], records[2])
169 # Put the subset records back onto the end of the original.
170 records.extend(subset)
171 self.assertEqual(len(records), n_messages + len(subset))
173 # Test slice for deleting
174 initial_length = len(records)
175 start_del = 1
176 end_del = 3
177 del records[start_del:end_del]
178 self.assertEqual(len(records), initial_length - (end_del - start_del))
180 records.clear()
181 self.assertEqual(len(records), 0)
183 with self.assertRaises(ValueError):
184 records.append({})
186 def testExceptionInfo(self):
188 self.log.setLevel(logging.DEBUG)
189 try:
190 raise RuntimeError("A problem has been encountered.")
191 except RuntimeError:
192 self.log.exception("Caught")
194 self.assertIn("A problem has been encountered", self.handler.records[0].exc_info)
196 self.log.warning("No exc_info")
197 self.assertIsNone(self.handler.records[-1].exc_info)
199 try:
200 raise RuntimeError("Debug exception log")
201 except RuntimeError:
202 self.log.debug("A problem", exc_info=1)
204 self.assertIn("Debug exception", self.handler.records[-1].exc_info)
206 def testMDC(self):
207 """Test that MDC information appears in messages."""
208 self.log.setLevel(logging.INFO)
210 i = 0
211 self.log.info("Message %d", i)
212 i += 1
213 self.assertEqual(self.handler.records[-1].MDC, {})
215 ButlerMDC.add_mdc_log_record_factory()
216 label = "MDC value"
217 ButlerMDC.MDC("LABEL", label)
218 self.log.info("Message %d", i)
219 self.assertEqual(self.handler.records[-1].MDC["LABEL"], label)
221 # Change the label and check that the previous record does not
222 # itself change.
223 ButlerMDC.MDC("LABEL", "dataId")
224 self.assertEqual(self.handler.records[-1].MDC["LABEL"], label)
226 # Format a record with MDC.
227 record = self.handler.records[-1]
229 # By default the MDC label should not be involved.
230 self.assertNotIn(label, str(record))
232 # But it can be included.
233 fmt = "x{MDC[LABEL]}"
234 self.assertEqual(record.format(fmt), "x" + label)
236 # But can be optional on a record that didn't set it.
237 self.assertEqual(self.handler.records[0].format(fmt), "x")
239 # Set an extra MDC entry and include all content.
240 extra = "extra"
241 ButlerMDC.MDC("EXTRA", extra)
243 i += 1
244 self.log.info("Message %d", i)
245 formatted = self.handler.records[-1].format("x{MDC} - {message}")
246 self.assertIn(f"EXTRA={extra}", formatted)
247 self.assertIn("LABEL=dataId", formatted)
248 self.assertIn(f"Message {i}", formatted)
250 # Clear the MDC and ensure that it does not continue to appear
251 # in messages.
252 ButlerMDC.MDCRemove("LABEL")
253 i += 1
254 self.log.info("Message %d", i)
255 self.assertEqual(self.handler.records[-1].format(fmt), "x")
256 self.assertEqual(self.handler.records[-1].format("{message}"), f"Message {i}")
258 # MDC context manager
259 fmt = "x{MDC[LABEL]} - {message}"
260 ButlerMDC.MDC("LABEL", "original")
261 with ButlerMDC.set_mdc({"LABEL": "test"}):
262 i += 1
263 self.log.info("Message %d", i)
264 self.assertEqual(self.handler.records[-1].format(fmt), f"xtest - Message {i}")
265 i += 1
266 self.log.info("Message %d", i)
267 self.assertEqual(self.handler.records[-1].format(fmt), f"xoriginal - Message {i}")
270class TestJsonLogging(unittest.TestCase):
272 def testJsonLogStream(self):
273 log = logging.getLogger(self.id())
274 log.setLevel(logging.INFO)
276 # Log to a stream and also to a file.
277 formatter = JsonLogFormatter()
279 stream = io.StringIO()
280 stream_handler = StreamHandler(stream)
281 stream_handler.setFormatter(formatter)
282 log.addHandler(stream_handler)
284 file = tempfile.NamedTemporaryFile(suffix=".json")
285 filename = file.name
286 file.close()
288 file_handler = FileHandler(filename)
289 file_handler.setFormatter(formatter)
290 log.addHandler(file_handler)
292 log.info("A message")
293 log.warning("A warning")
295 # Add a blank line to the stream to check the parser ignores it.
296 print(file=stream)
298 # Rewind the stream and pull messages out of it.
299 stream.seek(0)
300 records = ButlerLogRecords.from_stream(stream)
301 self.assertIsInstance(records[0], ButlerLogRecord)
302 self.assertEqual(records[0].message, "A message")
303 self.assertEqual(records[1].levelname, "WARNING")
305 # Now read from the file. Add two blank lines to test the parser
306 # will filter them out.
307 file_handler.close()
309 with open(filename, "a") as fd:
310 print(file=fd)
311 print(file=fd)
313 file_records = ButlerLogRecords.from_file(filename)
314 self.assertEqual(file_records, records)
316 # And read the file again in bytes and text.
317 for mode in ("rb", "r"):
318 with open(filename, mode) as fd:
319 file_records = ButlerLogRecords.from_stream(fd)
320 self.assertEqual(file_records, records)
321 fd.seek(0)
322 file_records = ButlerLogRecords.from_raw(fd.read())
323 self.assertEqual(file_records, records)
325 # Serialize this model to stream.
326 stream2 = io.StringIO()
327 print(records.json(), file=stream2)
328 stream2.seek(0)
329 stream_records = ButlerLogRecords.from_stream(stream2)
330 self.assertEqual(stream_records, records)
333if __name__ == "__main__": 333 ↛ 334line 333 didn't jump to line 334, because the condition on line 333 was never true
334 unittest.main()