|
| 1 | +import logging |
| 2 | +import sys |
| 3 | + |
| 4 | +from datetime import datetime |
| 5 | +from pathlib import Path |
| 6 | + |
| 7 | + |
| 8 | +class LayupLogger: |
| 9 | + """This logger configures the root-level logger for Layup to emit messages |
| 10 | + to potentially three locations 1) STDERR 2) layup-<datetime>.log and |
| 11 | + 3) layup-<datetime>.err depending on the log level. See the `_prepare_logger` |
| 12 | + method for details about which levels are sent to which handlers. |
| 13 | +
|
| 14 | + LayupLogger is intended to be used in one of two ways in general. Either |
| 15 | + instantiated within the `execute()` function in one of the layup_cmdline verbs |
| 16 | + or as a context manager when calling the API directly. |
| 17 | +
|
| 18 | + Example 1 - LayupLogger in a command line verb |
| 19 | + (See layup_cmdline/log.py for a working example) |
| 20 | + ``` |
| 21 | + def execute(): |
| 22 | + from layup.utilities.layup_logging import LayupLogger |
| 23 | +
|
| 24 | + layup_logger = LayupLogger() |
| 25 | +
|
| 26 | + # Create a child logger. NOTE - that the name starts with "layup.<blah>" |
| 27 | + # Failure to specify a name with that form could result in lost logs. |
| 28 | + logger = layup_logger.get_logger("layup.log_cmdline") |
| 29 | +
|
| 30 | + logger.info("Sending a log message.") # Use the logger |
| 31 | + ``` |
| 32 | +
|
| 33 | + Example 2 - LayupLogger in a context manager |
| 34 | + This would likely be the usage within a Jupyter notebook |
| 35 | + ``` |
| 36 | + from layup.utilities.layup_logging import LayupLogger |
| 37 | +
|
| 38 | + with LayupLogger() as layup_logger: |
| 39 | + # Create a child logger. NOTE - that the name starts with "layup.<blah>" |
| 40 | + # Failure to specify a name with that form could result in lost logs. |
| 41 | + logger = layup_logger.get_logger("layup.interactive") |
| 42 | +
|
| 43 | + logger.info("Sending a log message from a notebook.") |
| 44 | + ``` |
| 45 | + """ |
| 46 | + |
| 47 | + def __init__(self, log_directory="."): |
| 48 | + self._prepare_logger(log_directory) |
| 49 | + |
| 50 | + def get_logger(self, name): |
| 51 | + """Convenience function to return a logger under the top level logger. |
| 52 | + This is identical to calling `logger = logging.getLogger(__name__)` |
| 53 | +
|
| 54 | + Parameters |
| 55 | + ---------- |
| 56 | + name : str |
| 57 | + The name to use when emitting messages using this logger. |
| 58 | +
|
| 59 | + Returns |
| 60 | + ------- |
| 61 | + Logger |
| 62 | + The logger to use to emit message. |
| 63 | + """ |
| 64 | + return logging.getLogger(name) |
| 65 | + |
| 66 | + def __enter__(self): |
| 67 | + """Entry point for using LayupLogger as a context manager |
| 68 | +
|
| 69 | + Returns |
| 70 | + ------- |
| 71 | + self |
| 72 | + An instance of the LayupLogger object |
| 73 | + """ |
| 74 | + return self |
| 75 | + |
| 76 | + def __exit__(self, exc_type, exc_val, exc_tb): |
| 77 | + """Called when the context manager exits. Used only to call _stop_logger |
| 78 | + to terminate the loop in the queue and kill the queue thread. |
| 79 | + """ |
| 80 | + pass |
| 81 | + |
| 82 | + def _prepare_logger(self, log_directory="."): |
| 83 | + """Setup for the primary logger. |
| 84 | +
|
| 85 | + Parameters |
| 86 | + ---------- |
| 87 | + log_directory : str, optional |
| 88 | + The directory to place the log files, by default "." |
| 89 | +
|
| 90 | + Returns |
| 91 | + ------- |
| 92 | + Logger |
| 93 | + The top level logger. |
| 94 | + """ |
| 95 | + |
| 96 | + logger = logging.getLogger("layup") |
| 97 | + |
| 98 | + # This logger handles all messages >= DEBUG |
| 99 | + logger.setLevel(logging.DEBUG) |
| 100 | + |
| 101 | + # The format of the log messages |
| 102 | + formatter = logging.Formatter("%(asctime)s - %(name)s - %(process)d - %(levelname)s - %(message)s") |
| 103 | + |
| 104 | + # Console handler - all messages >= INFO will be recorded to STDERR |
| 105 | + console_handler = logging.StreamHandler(sys.stderr) |
| 106 | + console_handler.setFormatter(formatter) |
| 107 | + console_handler.setLevel(logging.INFO) |
| 108 | + |
| 109 | + # Configure log files |
| 110 | + log_location = Path(log_directory) |
| 111 | + timestamp = datetime.now().strftime("%Y-%m-%d-%H-%M-%S") |
| 112 | + log_file_base_name = f"layup-{timestamp}" |
| 113 | + log_file_info = log_location / f"{log_file_base_name}.log" |
| 114 | + log_file_error = log_location / f"{log_file_base_name}.err" |
| 115 | + |
| 116 | + # File handler that will record all messages >= DEBUG |
| 117 | + file_handler_info = logging.FileHandler(log_file_info) |
| 118 | + file_handler_info.setFormatter(formatter) |
| 119 | + file_handler_info.setLevel(logging.DEBUG) |
| 120 | + |
| 121 | + # File handler that will record all messaged >= ERROR |
| 122 | + file_handler_error = logging.FileHandler(log_file_error) |
| 123 | + file_handler_error.setFormatter(formatter) |
| 124 | + file_handler_error.setLevel(logging.ERROR) |
| 125 | + |
| 126 | + # Add the handlers to the logger |
| 127 | + logger.addHandler(file_handler_info) |
| 128 | + logger.addHandler(file_handler_error) |
| 129 | + logger.addHandler(console_handler) |
| 130 | + |
| 131 | + # Return the top level logger |
| 132 | + return logger |
0 commit comments