Debian Codegraph @

brian2/utils/logger.py

raw
1 """
2 Brian's logging module.
3
4 Preferences
5 -----------
6 .. document_brian_prefs:: logging
7 """
8
9 import atexit
10 import logging
11 import logging.handlers
12 import os
13 import shutil
14 import sys
15 import tempfile
16 import time
17 from logging.handlers import RotatingFileHandler
18 from warnings import warn
19
20 import numpy
21
22 try:
23 import scipy
24 except ImportError:
25 scipy = None
26 import sympy
27
28 import brian2
29 from brian2.core.preferences import BrianPreference, prefs
30
31 from .environment import running_from_ipython
32
33 __all__ = ["get_logger", "BrianLogger", "std_silent"]
34
35 # ===============================================================================
36 # Logging preferences
37 # ===============================================================================
38
39
40 def log_level_validator(log_level):
41 log_levels = ("CRITICAL", "ERROR", "WARNING", "INFO", "DEBUG", "DIAGNOSTIC")
42 return log_level.upper() in log_levels
43
44
45 #: Our new log level for more detailed debug output (mostly useful for debugging
46 #: Brian itself, not for user scripts)
47 DIAGNOSTIC = 5
48
49 #: Translation from string representation to number
50 LOG_LEVELS = {
51 "CRITICAL": logging.CRITICAL,
52 "ERROR": logging.ERROR,
53 "WARNING": logging.WARNING,
54 "INFO": logging.INFO,
55 "DEBUG": logging.DEBUG,
56 "DIAGNOSTIC": DIAGNOSTIC,
57 }
58 logging.addLevelName(DIAGNOSTIC, "DIAGNOSTIC")
59
60 if "logging" not in prefs.pref_register:
61 # Duplicate import of this module can happen when the documentation is built
62 prefs.register_preferences(
63 "logging",
64 "Logging system preferences",
65 delete_log_on_exit=BrianPreference(
66 default=True,
67 docs="""
68 Whether to delete the log and script file on exit.
69
70 If set to ``True`` (the default), log files (and the copy of the main
71 script) will be deleted after the brian process has exited, unless an
72 uncaught exception occurred. If set to ``False``, all log files will be
73 kept.
74 """,
75 ),
76 file_log_level=BrianPreference(
77 default="DEBUG",
78 docs="""
79 What log level to use for the log written to the log file.
80
81 In case file logging is activated (see `logging.file_log`), which log
82 level should be used for logging. Has to be one of CRITICAL, ERROR,
83 WARNING, INFO, DEBUG or DIAGNOSTIC.
84 """,
85 validator=log_level_validator,
86 ),
87 console_log_level=BrianPreference(
88 default="INFO",
89 docs="""
90 What log level to use for the log written to the console.
91
92 Has to be one of CRITICAL, ERROR, WARNING, INFO, DEBUG or DIAGNOSTIC.
93 """,
94 validator=log_level_validator,
95 ),
96 file_log=BrianPreference(
97 default=True,
98 docs="""
99 Whether to log to a file or not.
100
101 If set to ``True`` (the default), logging information will be written
102 to a file. The log level can be set via the `logging.file_log_level`
103 preference.
104 """,
105 ),
106 file_log_max_size=BrianPreference(
107 default=10000000,
108 docs="""
109 The maximum size for the debug log before it will be rotated.
110
111 If set to any value ``> 0``, the debug log will be rotated once
112 this size is reached. Rotating the log means that the old debug log
113 will be moved into a file in the same directory but with suffix ``".1"``
114 and the a new log file will be created with the same pathname as the
115 original file. Only one backup is kept; if a file with suffix ``".1"``
116 already exists when rotating, it will be overwritten.
117 If set to ``0``, no log rotation will be applied.
118 The default setting rotates the log file after 10MB.
119 """,
120 ),
121 save_script=BrianPreference(
122 default=True,
123 docs="""
124 Whether to save a copy of the script that is run.
125
126 If set to ``True`` (the default), a copy of the currently run script
127 is saved to a temporary location. It is deleted after a successful
128 run (unless `logging.delete_log_on_exit` is ``False``) but is kept after
129 an uncaught exception occured. This can be helpful for debugging,
130 in particular when several simulations are running in parallel.
131 """,
132 ),
133 std_redirection=BrianPreference(
134 default=True,
135 docs="""
136 Whether or not to redirect stdout/stderr to null at certain places.
137
138 This silences a lot of annoying compiler output, but will also hide
139 error messages making it harder to debug problems. You can always
140 temporarily switch it off when debugging. If
141 `logging.std_redirection_to_file` is set to ``True`` as well, then the
142 output is saved to a file and if an error occurs the name of this file
143 will be printed.
144 """,
145 ),
146 std_redirection_to_file=BrianPreference(
147 default=True,
148 docs="""
149 Whether to redirect stdout/stderr to a file.
150
151 If both ``logging.std_redirection`` and this preference are set to
152 ``True``, all standard output/error (most importantly output from
153 the compiler) will be stored in files and if an error occurs the name
154 of this file will be printed. If `logging.std_redirection` is ``True``
155 and this preference is ``False``, then all standard output/error will
156 be completely suppressed, i.e. neither be displayed nor stored in a
157 file.
158
159 The value of this preference is ignore if `logging.std_redirection` is
160 set to ``False``.
161 """,
162 ),
163 display_brian_error_message=BrianPreference(
164 default=True,
165 docs="""
166 Whether to display a text for uncaught errors, mentioning the location
167 of the log file, the mailing list and the github issues.
168
169 Defaults to ``True``.""",
170 ),
171 warn_for_unused_objects=BrianPreference(
172 default=True,
173 docs="""
174 Whether to display a warning when an object gets deleted without ever
175 having been included in a network. This usually indicates a
176 programming error (e.g. a function creates a `Network` and returns it,
177 but forgets to include one of the created objects), but in some cases
178 adds unwanted noise (e.g. in interactive programming in a notebook, or
179 in the test suite).
180 """,
181 ),
182 )
183
184 # ===============================================================================
185 # Initial setup
186 # ===============================================================================
187
188
189 def _encode(text):
190 """Small helper function to encode unicode strings as UTF-8."""
191 return text.encode("UTF-8")
192
193
194 UNHANDLED_ERROR_MESSAGE = (
195 "Brian 2 encountered an unexpected error. "
196 "If you think this is a bug in Brian 2, please report this issue either to the "
197 "discourse forum at <http://brian.discourse.group/>, "
198 "or to the issue tracker at <https://github.com/brian-team/brian2/issues>."
199 )
200
201
202 def brian_excepthook(exc_type, exc_obj, exc_tb):
203 """
204 Display a message mentioning the debug log in case of an uncaught
205 exception.
206 """
207 # Do not catch Ctrl+C
208 if exc_type is KeyboardInterrupt:
209 return
210 logger = logging.getLogger("brian2")
211 BrianLogger.exception_occured = True
212
213 if not prefs["logging.display_brian_error_message"]:
214 # Put the exception message in the log file, but do not log to the
215 # console
216 if BrianLogger.console_handler is not None:
217 logger.removeHandler(BrianLogger.console_handler)
218 logger.exception("An exception occured", exc_info=(exc_type, exc_obj, exc_tb))
219 if BrianLogger.console_handler is not None:
220 logger.addHandler(BrianLogger.console_handler)
221 # Run the default except hook
222 return sys.__excepthook__(exc_type, exc_obj, exc_tb)
223
224 message = UNHANDLED_ERROR_MESSAGE
225 if BrianLogger.tmp_log is not None:
226 message += (
227 " Please include this file with debug information in your "
228 f"report: {BrianLogger.tmp_log} "
229 )
230 if BrianLogger.tmp_script is not None:
231 message += (
232 " Additionally, you can also include a copy "
233 "of the script that was run, available "
234 f"at: {BrianLogger.tmp_script}"
235 )
236 if hasattr(std_silent, "dest_fname_stdout"):
237 stdout = std_silent.dest_fname_stdout
238 stderr = std_silent.dest_fname_stderr
239 message += (
240 " You can also include a copy of the "
241 "redirected std stream outputs, available at "
242 f"'{stdout}' and '{stderr}'."
243 )
244
245 message += " Thanks!" # very important :)
246 logger.error(message, exc_info=(exc_type, exc_obj, exc_tb))
247
248
249 def clean_up_logging():
250 """
251 Shutdown the logging system and delete the debug log file if no error
252 occured.
253 """
254 BrianLogger.initialized = False
255 logging.shutdown()
256 if not BrianLogger.exception_occured and prefs["logging.delete_log_on_exit"]:
257 if BrianLogger.tmp_log is not None:
258 try:
259 os.remove(BrianLogger.tmp_log)
260 except OSError as exc:
261 warn(f"Could not delete log file: {exc}")
262 # Remove log files that have been rotated (currently only one)
263 rotated_log = f"{BrianLogger.tmp_log}.1"
264 if os.path.exists(rotated_log):
265 try:
266 os.remove(rotated_log)
267 except OSError as exc:
268 warn(f"Could not delete log file: {exc}")
269 if BrianLogger.tmp_script is not None:
270 try:
271 os.remove(BrianLogger.tmp_script)
272 except OSError as exc:
273 warn(f"Could not delete copy of script file: {exc}")
274 std_silent.close()
275
276
277 atexit.register(clean_up_logging)
278
279
280 class HierarchyFilter:
281 """
282 A class for suppressing all log messages in a subtree of the name hierarchy.
283 Does exactly the opposite as the `logging.Filter` class, which allows
284 messages in a certain name hierarchy to *pass*.
285
286 Parameters
287 ----------
288 name : str
289 The name hiearchy to suppress. See `BrianLogger.suppress_hierarchy` for
290 details.
291 """
292
293 def __init__(self, name):
294 self.orig_filter = logging.Filter(name)
295
296 def filter(self, record):
297 """
298 Filter out all messages in a subtree of the name hierarchy.
299 """
300 # do the opposite of what the standard filter class would do
301 return not self.orig_filter.filter(record)
302
303
304 class NameFilter:
305 """
306 A class for suppressing log messages ending with a certain name.
307
308 Parameters
309 ----------
310 name : str
311 The name to suppress. See `BrianLogger.suppress_name` for details.
312 """
313
314 def __init__(self, name):
315 self.name = name
316
317 def filter(self, record):
318 """
319 Filter out all messages ending with a certain name.
320 """
321 # The last part of the name
322 record_name = record.name.split(".")[-1]
323 return self.name != record_name
324
325
326 class RemoveBrian2Filter(logging.Filter):
327 """
328 A class for removing the ``brian2`` prefix from log messages.
329 Will be used for extension packages that use the Brian logging system.
330 """
331
332 def filter(self, record):
333 assert record.name.startswith("brian2."), record.name
334 record.name = record.name[7:]
335 return True
336
337
338 class BrianLogger:
339 """
340 Convenience object for logging. Call `get_logger` to get an instance of
341 this class.
342
343 Parameters
344 ----------
345 name : str
346 The name used for logging, normally the name of the module. If the name
347 does not start with ``brian2.``, it will be prepended automatically when
348 interacting with the `logging` module. This means that from the logging's
349 system point of view, it will use the configuration for the logger in the
350 ``brian2`` hierachy. However, when displaying the name in the log messages,
351 the ``brian2.`` prefix will be removed. This is useful for extension
352 modules, which can use the Brian logging system, but will be displayed as
353 ``myextension`` instead of ``brian2.myextension``. This is also used in
354 Brian's test suite, which only considers log messages starting with
355 ``brian2``.
356 """
357
358 #: Global flag to know whether the logging system is in a usable state
359 initialized = False
360
361 #: Class attribute to remember whether any exception occured
362 exception_occured = False
363
364 #: Class attribute for remembering log messages that should only be
365 #: displayed once
366 _log_messages = set()
367
368 #: The name of the temporary log file (by default deleted after the run if
369 #: no exception occurred), if any
370 tmp_log = None
371
372 #: The `logging.FileHandler` responsible for logging to the temporary log
373 #: file
374 file_handler = None
375
376 #: The `logging.StreamHandler` responsible for logging to the console
377 console_handler = None
378
379 #: The name of the temporary copy of the main script file (by default
380 #: deleted after the run if no exception occurred), if any
381 tmp_script = None
382
383 #: The pid of the process that initialized the logger – used to switch off file logging in
384 #: multiprocessing contexts
385 _pid = None
386
387 def __init__(self, name):
388 if not name.startswith("brian2."):
389 self.name = "brian2." + name
390 self.filter_name = True
391 else:
392 self.name = name
393 self.filter_name = False
394
395 def _log(self, log_level, msg, name_suffix, once):
396 """
397 Log an entry.
398
399 Parameters
400 ----------
401 log_level : {'debug', 'info', 'warn', 'error'}
402 The level with which to log the message.
403 msg : str
404 The log message.
405 name_suffix : str
406 A suffix that will be added to the logger name.
407 once : bool
408 Whether to suppress identical messages if they are logged again.
409 """
410 if not BrianLogger.initialized:
411 # Prevent logging errors on exit
412 return
413 name = self.name
414 if name_suffix:
415 name += f".{name_suffix}"
416
417 # Switch off file logging when using multiprocessing
418 if BrianLogger.tmp_log is not None and BrianLogger._pid != os.getpid():
419 BrianLogger.tmp_log = None
420 logging.getLogger("brian2").removeHandler(BrianLogger.file_handler)
421 BrianLogger.file_handler = None
422
423 if once:
424 # Check whether this exact message has already been displayed
425 log_tuple = (name, log_level, msg)
426 if log_tuple in BrianLogger._log_messages:
427 return
428 else:
429 BrianLogger._log_messages.add(log_tuple)
430
431 the_logger = logging.getLogger(name)
432 if self.filter_name:
433 filter = RemoveBrian2Filter()
434 the_logger.addFilter(filter)
435 the_logger.log(LOG_LEVELS[log_level], msg)
436 if self.filter_name:
437 the_logger.removeFilter(filter)
438
439 def diagnostic(self, msg, name_suffix=None, once=False):
440 """
441 Log a diagnostic message.
442
443 Parameters
444 ----------
445 msg : str
446 The message to log.
447 name_suffix : str, optional
448 A suffix to add to the name, e.g. a class or function name.
449 once : bool, optional
450 Whether this message should be logged only once and not repeated
451 if sent another time.
452 """
453 self._log("DIAGNOSTIC", msg, name_suffix, once)
454
455 def debug(self, msg, name_suffix=None, once=False):
456 """
457 Log a debug message.
458
459 Parameters
460 ----------
461 msg : str
462 The message to log.
463 name_suffix : str, optional
464 A suffix to add to the name, e.g. a class or function name.
465 once : bool, optional
466 Whether this message should be logged only once and not repeated
467 if sent another time.
468 """
469 self._log("DEBUG", msg, name_suffix, once)
470
471 def info(self, msg, name_suffix=None, once=False):
472 """
473 Log an info message.
474
475 Parameters
476 ----------
477 msg : str
478 The message to log.
479 name_suffix : str, optional
480 A suffix to add to the name, e.g. a class or function name.
481 once : bool, optional
482 Whether this message should be logged only once and not repeated
483 if sent another time.
484 """
485 self._log("INFO", msg, name_suffix, once)
486
487 def warn(self, msg, name_suffix=None, once=False):
488 """
489 Log a warn message.
490
491 Parameters
492 ----------
493 msg : str
494 The message to log.
495 name_suffix : str, optional
496 A suffix to add to the name, e.g. a class or function name.
497 once : bool, optional
498 Whether this message should be logged only once and not repeated
499 if sent another time.
500 """
501 self._log("WARNING", msg, name_suffix, once)
502
503 warning = warn
504
505 def error(self, msg, name_suffix=None, once=False):
506 """
507 Log an error message.
508
509 Parameters
510 ----------
511 msg : str
512 The message to log.
513 name_suffix : str, optional
514 A suffix to add to the name, e.g. a class or function name.
515 once : bool, optional
516 Whether this message should be logged only once and not repeated
517 if sent another time.
518 """
519 self._log("ERROR", msg, name_suffix, once)
520
521 @staticmethod
522 def _suppress(filterobj, filter_log_file):
523 """
524 Apply a filter object to log messages.
525
526 Parameters
527 ----------
528 filterobj : `logging.Filter`
529 A filter object to apply to log messages.
530 filter_log_file : bool
531 Whether the filter also applies to log messages in the log file.
532 """
533 BrianLogger.console_handler.addFilter(filterobj)
534
535 if filter_log_file:
536 BrianLogger.file_handler.addFilter(filterobj)
537
538 @staticmethod
539 def suppress_hierarchy(name, filter_log_file=False):
540 """
541 Suppress all log messages in a given hiearchy.
542
543 Parameters
544 ----------
545 name : str
546 Suppress all log messages in the given `name` hierarchy. For
547 example, specifying ``'brian2'`` suppresses all messages logged
548 by Brian, specifying ``'brian2.codegen'`` suppresses all messages
549 generated by the code generation modules.
550 filter_log_file : bool, optional
551 Whether to suppress the messages also in the log file. Defaults to
552 ``False`` meaning that suppressed messages are not displayed on
553 the console but are still saved to the log file.
554 """
555
556 suppress_filter = HierarchyFilter(name)
557
558 BrianLogger._suppress(suppress_filter, filter_log_file)
559
560 @staticmethod
561 def suppress_name(name, filter_log_file=False):
562 """
563 Suppress all log messages with a given name.
564
565 Parameters
566 ----------
567 name : str
568 Suppress all log messages ending in the given `name`. For
569 example, specifying ``'resolution_conflict'`` would suppress
570 messages with names such as
571 ``brian2.equations.codestrings.CodeString.resolution_conflict`` or
572 ``brian2.equations.equations.Equations.resolution_conflict``.
573 filter_log_file : bool, optional
574 Whether to suppress the messages also in the log file. Defaults to
575 ``False`` meaning that suppressed messages are not displayed on
576 the console but are still saved to the log file.
577 """
578 suppress_filter = NameFilter(name)
579
580 BrianLogger._suppress(suppress_filter, filter_log_file)
581
582 @staticmethod
583 def log_level_diagnostic():
584 """
585 Set the log level to "diagnostic".
586 """
587 BrianLogger.console_handler.setLevel(DIAGNOSTIC)
588
589 @staticmethod
590 def log_level_debug():
591 """
592 Set the log level to "debug".
593 """
594 BrianLogger.console_handler.setLevel(logging.DEBUG)
595
596 @staticmethod
597 def log_level_info():
598 """
599 Set the log level to "info".
600 """
601 BrianLogger.console_handler.setLevel(logging.INFO)
602
603 @staticmethod
604 def log_level_warn():
605 """
606 Set the log level to "warn".
607 """
608 BrianLogger.console_handler.setLevel(logging.WARN)
609
610 @staticmethod
611 def log_level_error():
612 """
613 Set the log level to "error".
614 """
615 BrianLogger.console_handler.setLevel(logging.ERROR)
616
617 @staticmethod
618 def initialize():
619 """
620 Initialize Brian's logging system. This function will be called
621 automatically when Brian is imported.
622 """
623 # get the main logger
624 logger = logging.getLogger("brian2")
625 logger.propagate = False
626 logger.setLevel(LOG_LEVELS["DIAGNOSTIC"])
627
628 # Log to a file
629 if prefs["logging.file_log"]:
630 try:
631 # Temporary filename used for logging
632 with tempfile.NamedTemporaryFile(
633 prefix="brian_debug_", suffix=".log", delete=False
634 ) as tmp_f:
635 BrianLogger.tmp_log = tmp_f.name
636 # Remove any previously existing file handler
637 if BrianLogger.file_handler is not None:
638 BrianLogger.file_handler.close()
639 logger.removeHandler(BrianLogger.file_handler)
640 # Rotate log file after prefs['logging.file_log_max_size'] bytes and keep one copy
641 BrianLogger.file_handler = RotatingFileHandler(
642 BrianLogger.tmp_log,
643 mode="a",
644 maxBytes=prefs["logging.file_log_max_size"],
645 backupCount=1,
646 encoding="utf-8",
647 )
648 BrianLogger.file_handler.setLevel(
649 LOG_LEVELS[prefs["logging.file_log_level"].upper()]
650 )
651 BrianLogger.file_handler.setFormatter(
652 logging.Formatter(
653 "%(asctime)s %(levelname)-10s %(name)s: %(message)s"
654 )
655 )
656 logger.addHandler(BrianLogger.file_handler)
657 BrianLogger._pid = os.getpid()
658 except OSError as ex:
659 warn(f"Could not create log file: {ex}")
660
661 # Save a copy of the script
662 BrianLogger.tmp_script = None
663 if prefs["logging.save_script"]:
664 if (
665 len(sys.argv[0])
666 and not running_from_ipython()
667 and os.path.isfile(sys.argv[0])
668 ):
669 try:
670 tmp_file = tempfile.NamedTemporaryFile(
671 prefix="brian_script_", suffix=".py", delete=False
672 )
673 with tmp_file:
674 # Timestamp
675 tmp_file.write(_encode(f"# {time.asctime()}\n"))
676 # Command line arguments
677 tmp_file.write(_encode(f"# Run as: {' '.join(sys.argv)}\n\n"))
678 # The actual script file
679 # TODO: We are copying the script file as it is, this might clash
680 # with the encoding we used for the comments added above
681 with open(os.path.abspath(sys.argv[0]), "rb") as script_file:
682 shutil.copyfileobj(script_file, tmp_file)
683 BrianLogger.tmp_script = tmp_file.name
684 except OSError as ex:
685 warn(f"Could not copy script file to temp directory: {ex}")
686
687 if BrianLogger.console_handler is not None:
688 logger.removeHandler(BrianLogger.console_handler)
689
690 # create console handler with a higher log level
691 BrianLogger.console_handler = logging.StreamHandler()
692 BrianLogger.console_handler.setLevel(
693 LOG_LEVELS[prefs["logging.console_log_level"]]
694 )
695 BrianLogger.console_handler.setFormatter(
696 logging.Formatter("%(levelname)-10s %(message)s [%(name)s]")
697 )
698
699 # add the handler to the logger
700 logger.addHandler(BrianLogger.console_handler)
701
702 # We want to log all warnings
703 logging.captureWarnings(True) # pylint: disable=E1101
704 # Manually connect to the warnings logger so that the warnings end up in
705 # the log file. Note that connecting to the console handler here means
706 # duplicated warning messages in the ipython notebook, but not doing so
707 # would mean that they are not displayed at all in the standard ipython
708 # interface...
709 warn_logger = logging.getLogger("py.warnings")
710 warn_logger.addHandler(BrianLogger.console_handler)
711
712 # Put some standard info into the log file
713 logger.log(
714 logging.DEBUG,
715 f"Logging to file: {BrianLogger.tmp_log}, copy of main script saved as:"
716 f" {BrianLogger.tmp_script}",
717 )
718 logger.log(logging.DEBUG, f"Python interpreter: {sys.executable}")
719 logger.log(logging.DEBUG, f"Platform: {sys.platform}")
720 version_infos = {
721 "brian": brian2.__version__,
722 "numpy": numpy.__version__,
723 "scipy": scipy.__version__ if scipy else "not installed",
724 "sympy": sympy.__version__,
725 "python": sys.version,
726 }
727 for _name, _version in version_infos.items():
728 logger.log(logging.DEBUG, f"{_name} version is: {str(_version)}")
729 # Handle uncaught exceptions
730 sys.excepthook = brian_excepthook
731
732 BrianLogger.initialized = True
733
734
735 def get_logger(module_name="brian2"):
736 """
737 Get an object that can be used for logging.
738
739 Parameters
740 ----------
741 module_name : str
742 The name used for logging, should normally be the module name as
743 returned by ``__name__``.
744
745 Returns
746 -------
747 logger : `BrianLogger`
748 """
749
750 return BrianLogger(module_name)
751
752
753 class catch_logs:
754 """
755 A context manager for catching log messages. Use this for testing the
756 messages that are logged. Defaults to catching warning/error messages and
757 this is probably the only real use case for testing. Note that while this
758 context manager is active, *all* log messages are suppressed. Using this
759 context manager returns a list of (log level, name, message) tuples.
760
761 Parameters
762 ----------
763 log_level : int or str, optional
764 The log level above which messages are caught.
765 only_from : list, optional
766 A list of module names from which messages are caught. Defaults to
767 the ``brian2`` module.
768 Examples
769 --------
770 >>> logger = get_logger('brian2.logtest')
771 >>> logger.warn('An uncaught warning') # doctest: +SKIP
772 WARNING brian2.logtest: An uncaught warning
773 >>> with catch_logs() as l:
774 ... logger.warn('a caught warning')
775 ... print('l contains: %s' % l)
776 ...
777 l contains: [('WARNING', 'brian2.logtest', 'a caught warning')]
778
779 """
780
781 _entered = False
782
783 def __init__(self, log_level=logging.WARN, only_from=("brian2",)):
784 self.log_list = []
785 self.handler = LogCapture(self.log_list, log_level, only_from=only_from)
786 self._entered = False
787
788 def __enter__(self):
789 if self._entered:
790 raise RuntimeError(f"Cannot enter {self!r} twice")
791 self._entered = True
792 return self.log_list
793
794 def __exit__(self, *exc_info):
795 if not self._entered:
796 raise RuntimeError(f"Cannot exit {self!r} without entering first")
797 self.handler.uninstall()
798
799
800 class LogCapture(logging.Handler):
801 """
802 A class for capturing log warnings. This class is used by
803 `~brian2.utils.logger.catch_logs` to allow testing in a similar
804 way as with `warnings.catch_warnings`.
805 """
806
807 def __init__(self, log_list, log_level=logging.WARN, only_from=("brian2",)):
808 logging.Handler.__init__(self, level=log_level)
809 self.log_list = log_list
810 self.only_from = only_from
811 # make a copy of the previous handlers
812 self.handlers = list(logging.getLogger("brian2").handlers)
813 self.install()
814
815 def emit(self, record):
816 # Append a tuple consisting of (level, name, msg) to the list of
817 # log messages
818 if any(
819 record.name == name or record.name.startswith(name + ".")
820 for name in self.only_from
821 ):
822 self.log_list.append((record.levelname, record.name, record.msg))
823
824 def install(self):
825 """
826 Install this handler to catch all warnings. Temporarily disconnect all
827 other handlers.
828 """
829 the_logger = logging.getLogger("brian2")
830 for handler in self.handlers:
831 the_logger.removeHandler(handler)
832 the_logger.addHandler(self)
833
834 def uninstall(self):
835 """
836 Uninstall this handler and re-connect the previously installed
837 handlers.
838 """
839 the_logger = logging.getLogger("brian2")
840 for handler in self.handlers:
841 the_logger.addHandler(handler)
842
843
844 # See http://stackoverflow.com/questions/26126160/redirecting-standard-out-in-err-back-after-os-dup2
845 # for an explanation of how this function works. Note that 1 and 2 are the file
846 # numbers for stdout and stderr
847 class std_silent:
848 """
849 Context manager that temporarily silences stdout and stderr but keeps the
850 output saved in a temporary file and writes it if an exception is raised.
851 """
852
853 dest_stdout = None
854 dest_stderr = None
855
856 def __init__(self, alwaysprint=False):
857 self.alwaysprint = alwaysprint or not prefs["logging.std_redirection"]
858 self.redirect_to_file = prefs["logging.std_redirection_to_file"]
859 if (
860 not self.alwaysprint
861 and self.redirect_to_file
862 and std_silent.dest_stdout is None
863 ):
864 std_silent.dest_fname_stdout = tempfile.NamedTemporaryFile(
865 prefix="brian_stdout_", suffix=".log", delete=False
866 ).name
867 std_silent.dest_fname_stderr = tempfile.NamedTemporaryFile(
868 prefix="brian_stderr_", suffix=".log", delete=False
869 ).name
870 std_silent.dest_stdout = open(std_silent.dest_fname_stdout, "w")
871 std_silent.dest_stderr = open(std_silent.dest_fname_stderr, "w")
872
873 def __enter__(self):
874 if not self.alwaysprint and self.redirect_to_file:
875 sys.stdout.flush()
876 sys.stderr.flush()
877 self.orig_out_fd = os.dup(1)
878 self.orig_err_fd = os.dup(2)
879 os.dup2(std_silent.dest_stdout.fileno(), 1)
880 os.dup2(std_silent.dest_stderr.fileno(), 2)
881
882 def __exit__(self, exc_type, exc_value, traceback):
883 if not self.alwaysprint and self.redirect_to_file:
884 std_silent.dest_stdout.flush()
885 std_silent.dest_stderr.flush()
886 if exc_type is not None:
887 with open(std_silent.dest_fname_stdout) as f:
888 out = f.read()
889 with open(std_silent.dest_fname_stderr) as f:
890 err = f.read()
891 os.dup2(self.orig_out_fd, 1)
892 os.dup2(self.orig_err_fd, 2)
893 os.close(self.orig_out_fd)
894 os.close(self.orig_err_fd)
895 if exc_type is not None:
896 sys.stdout.write(out)
897 sys.stderr.write(err)
898
899 @classmethod
900 def close(cls):
901 if std_silent.dest_stdout is not None:
902 std_silent.dest_stdout.close()
903 if prefs["logging.delete_log_on_exit"]:
904 try:
905 os.remove(std_silent.dest_fname_stdout)
906 except OSError:
907 # TODO: this happens quite frequently - why?
908 # The file objects are closed as far as Python is concerned,
909 # but maybe Windows is still hanging on to them?
910 pass
911 if std_silent.dest_stderr is not None:
912 std_silent.dest_stderr.close()
913 if prefs["logging.delete_log_on_exit"]:
914 try:
915 os.remove(std_silent.dest_fname_stderr)
916 except OSError:
917 pass