|
1 | 1 | import logging |
2 | 2 | import os |
3 | 3 | import sys |
| 4 | +import tempfile |
4 | 5 | from typing import Any, Optional, Union |
5 | 6 |
|
6 | 7 | # Setup the root logger for the ppafm package. All other loggers will be derived from this one. |
|
15 | 16 | _perf_log_format = "[%(asctime)s - %(name)s] %(message)s" |
16 | 17 | _perf_log_enabled = False |
17 | 18 |
|
| 19 | +lib = None |
| 20 | + |
18 | 21 |
|
19 | 22 | def configure_logging( |
20 | 23 | level: Optional[Union[int, str]] = None, |
@@ -45,7 +48,7 @@ def configure_logging( |
45 | 48 |
|
46 | 49 | if level is None: |
47 | 50 | try: |
48 | | - level = os.environ["PPAFM_LOG_LEVEL"] |
| 51 | + level = os.environ["PPAFM_LOG_LEVEL"].upper() |
49 | 52 | except KeyError: |
50 | 53 | level = logging.INFO |
51 | 54 | _root_logger.setLevel(level) |
@@ -95,9 +98,64 @@ def configure_logging( |
95 | 98 | _log_handler.setFormatter(logging.Formatter(fmt=_log_format)) |
96 | 99 |
|
97 | 100 |
|
98 | | -# This sets the logging level immediately from environment variable or defaults to INFO. |
99 | | -# Also sets the message format. |
100 | | -configure_logging() |
| 101 | +def _init_logging(): |
| 102 | + |
| 103 | + global lib |
| 104 | + if lib is not None: |
| 105 | + return |
| 106 | + |
| 107 | + configure_logging() |
| 108 | + |
| 109 | + # We have to do this import here, or otherwise we get a circular import |
| 110 | + from .cpp_utils import get_cdll |
| 111 | + |
| 112 | + lib = get_cdll("logging") |
| 113 | + lib.set_log_fd(sys.stdout.fileno()) |
| 114 | + |
| 115 | + with CppLogger("test_logger"): |
| 116 | + lib.test_log() |
| 117 | + |
| 118 | + |
| 119 | +def _get_lib(): |
| 120 | + if lib is None: |
| 121 | + raise RuntimeError("Logging not initialized") |
| 122 | + return lib |
| 123 | + |
| 124 | + |
| 125 | +class CppLogger: |
| 126 | + """Context manager for redirecting logging events in C++ to Python logging.""" |
| 127 | + |
| 128 | + def __init__(self, logger_name: str): |
| 129 | + self.logger = get_logger(logger_name) |
| 130 | + self.lib = _get_lib() |
| 131 | + |
| 132 | + def __enter__(self): |
| 133 | + self.log = tempfile.TemporaryFile() |
| 134 | + self.lib.set_log_fd(self.log.fileno()) |
| 135 | + |
| 136 | + def __exit__(self, exc_type, exc_value, exc_traceback): |
| 137 | + self.log.seek(0) |
| 138 | + |
| 139 | + # Read file line-by-line and convert messages to logging events |
| 140 | + log_level = logging.INFO |
| 141 | + msg = "" |
| 142 | + for line in self.log: |
| 143 | + line = line.decode().strip() |
| 144 | + if line.startswith("LOG_ENTRY_"): |
| 145 | + if msg: |
| 146 | + self.logger.log(log_level, msg) |
| 147 | + msg = "" |
| 148 | + line = line.removeprefix("LOG_ENTRY_") |
| 149 | + level_str, msg = line.split(" ", maxsplit=1) |
| 150 | + log_level = getattr(logging, level_str) |
| 151 | + else: |
| 152 | + msg += f"\n{line}" |
| 153 | + if msg: |
| 154 | + self.logger.log(log_level, msg) |
| 155 | + |
| 156 | + self.log.close() |
| 157 | + |
| 158 | + self.lib.set_log_fd(sys.stdout.fileno()) |
101 | 159 |
|
102 | 160 |
|
103 | 161 | def get_logger(name: str) -> logging.Logger: |
|
0 commit comments