TemporaryLogFile#

class caf.toolkit.TemporaryLogFile(logger, log_file, base_log_file=None, **kwargs)[source]#

Add temporary log file to a logger.

This context manager class is designed to temporarily add another log file to an existing logger for any messages in a with statement. When adding a new file handler to an existing logger any previous handlers will remain, so log messages will be written to the new and old log files for example.

Parameters:
  • logger (logging.Logger) – Logger to add FileHandler to.

  • log_file (os.PathLike) – Path to new log file to create.

  • base_log_file (os.PathLike, optional) – Path to base log file, location will be logged in new log file.

  • kwargs (Keyword arguments, optional) – Any arguments to pass to get_file_handler.

See also

LogHelper

for setting up logging for a tool.

Examples

When using Python’s built-in logging functionality a module level logger constant should be used.

>>> import logging
>>>
>>> LOG = logging.getLogger(__name__)

The code below is defining the log file path for testing purposes.

>>> log_file = getfixture('tmp_path') / "test.log"

Setting up a new temporary log file for a single module can be done using the following:

>>> with TemporaryLogFile(LOG, log_file):
...     LOG.info("Message logged to new file")
...     # Includes logging messages from functions which are
...     # in the current module only
>>> LOG.info("Message not in new file")

Logging all messages from the current package to the new file can be done by passing the package logger.

>>> with TemporaryLogFile(logging.getLogger(__package__), log_file):
...     LOG.info("Message logged to new file")
...     # Includes logging messages from functions called here which
...     # are in other modules in the package

Methods

__init__(logger, log_file[, base_log_file])