Files
fiona-assistant/src/fiona/logging_config.py
T
2026-09-29 16:01:16 +02:00

226 lines
7.9 KiB
Python

"""Shared logging configuration for all Fiona tools (SPEC 7.20).
Diagnostics go through the standard `logging` module with the level
resolved from (highest precedence first):
1. the `LOG_LEVEL` environment variable,
2. `fiona.log_level` in `fiona-settings.json`,
3. `WARNING` (clean runs print only the CLI reports).
CLI-facing reports intentionally stay `print` calls on stdout; log
records go to stderr.
"""
from __future__ import annotations
import ctypes
import json
import logging
import os
import pathlib
import sys
from fiona.paths import llm_wiki_template
# AI/LLM: Windows-only; module-level so PYC001 allows it (SPEC 6.4.2).
if os.name == "nt":
import msvcrt
DEFAULT_LOG_LEVEL = "WARNING"
DEFAULT_SETTINGS_FILE = llm_wiki_template() / "fiona-settings.json"
# Tool package loggers that carry the level explicitly: pymarkdown
# resets the root logger to WARNING mid-run, which would otherwise
# silence tool diagnostics (same pattern as run_sanity, see SPEC 7.20).
TOOL_LOGGER_NAMES = ("fiona",)
LOG_FORMAT = "%(levelname)s %(name)s: %(message)s"
FILE_LOG_FORMAT = "%(asctime)s %(levelname)s %(name)s: %(message)s"
FILE_HANDLER_TAG = "fiona_file_log"
def load_settings(settings_file: str | pathlib.Path | None = None) -> dict:
"""Load a fiona-settings.json file, returning {} when unavailable.
Args:
settings_file: Path to the settings file. Defaults to the
packaged llm-wiki template's fiona-settings.json.
Returns:
The full settings mapping, or {} when the file is missing or
unparseable (a warning is logged for the latter).
"""
if settings_file is None:
settings_file = DEFAULT_SETTINGS_FILE
try:
with open(settings_file, encoding="utf-8") as settings_handle:
return json.load(settings_handle)
except FileNotFoundError:
logging.getLogger(__name__).debug("No settings file at %s", settings_file)
return {}
except (json.JSONDecodeError, OSError) as error:
logging.getLogger(__name__).warning(
"Could not read settings file %s: %s", settings_file, error
)
return {}
def load_log_level(settings: dict | None) -> str:
"""Resolve the effective log level name.
Args:
settings: The full settings mapping (its `fiona.log_level`
key is consulted), or None.
Returns:
The upper-case level name; `LOG_LEVEL` wins over the settings
value, invalid values fall back to WARNING with a warning.
"""
env_level = os.environ.get("LOG_LEVEL")
if env_level:
candidate = env_level
else:
fiona_settings = (settings or {}).get("fiona")
candidate = fiona_settings.get("log_level") if isinstance(fiona_settings, dict) else None
if not isinstance(candidate, str) or candidate.upper() not in logging.getLevelNamesMapping():
if candidate is not None:
logging.getLogger(__name__).warning(
"Invalid log level %r, falling back to %s", candidate, DEFAULT_LOG_LEVEL
)
return DEFAULT_LOG_LEVEL
return candidate.upper()
def _open_shared_append(path: str, encoding: str):
"""Open a log file that Windows can delete while the handle is open.
Generated by AI/LLM: 2026-09-29 - the default open() omits
FILE_SHARE_DELETE, so a temp directory that still has fiona.log
open cannot be removed.
Args:
path: Log file path.
encoding: Text encoding for the stream.
Returns:
A text file object opened for append.
"""
if os.name != "nt":
return open(path, "a", encoding=encoding)
kernel32 = ctypes.WinDLL("kernel32", use_last_error=True)
kernel32.CreateFileW.argtypes = [
ctypes.c_wchar_p,
ctypes.c_uint32,
ctypes.c_uint32,
ctypes.c_void_p,
ctypes.c_uint32,
ctypes.c_uint32,
ctypes.c_void_p,
]
kernel32.CreateFileW.restype = ctypes.c_void_p
kernel32.SetFilePointer.argtypes = [
ctypes.c_void_p,
ctypes.c_long,
ctypes.c_void_p,
ctypes.c_uint32,
]
kernel32.SetFilePointer.restype = ctypes.c_uint32
handle = kernel32.CreateFileW(
path,
0x40000000, # GENERIC_WRITE
0x1 | 0x2 | 0x4, # FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE
None,
4, # OPEN_ALWAYS
0x80, # FILE_ATTRIBUTE_NORMAL
None,
)
invalid = ctypes.c_void_p(-1).value
if handle in (None, invalid):
raise OSError(ctypes.get_last_error(), f"Cannot open log file {path}")
kernel32.SetFilePointer(handle, 0, None, 2) # FILE_END
fd = msvcrt.open_osfhandle(handle, os.O_APPEND)
return os.fdopen(fd, "a", encoding=encoding, closefd=True)
class _SharedFileHandler(logging.FileHandler):
"""File log handler that does not block deletion of its directory.
Generated by AI/LLM: 2026-09-29 - Windows tests and temp wikis remove
the working directory while fiona.log is still attached.
"""
def _open(self):
return _open_shared_append(self.baseFilename, self.encoding or "utf-8")
def _remove_file_handler() -> None:
"""Detach (and close) the managed file log handler, if any."""
for handler in list(logging.getLogger().handlers):
if getattr(handler, FILE_HANDLER_TAG, False):
logging.getLogger().removeHandler(handler)
handler.close()
def _configure_file_log(fiona_settings: dict, console_level: str) -> None:
"""Attach a file handler per `fiona.file_log_location`.
Args:
fiona_settings: The `fiona` settings section.
console_level: The console level name; the fallback for
`file_log_level` when absent or invalid.
A missing or empty `file_log_location` disables file logging; a
relative path resolves against the current working directory. An
unopenable location logs a warning and keeps console logging.
"""
_remove_file_handler()
location = fiona_settings.get("file_log_location")
if not isinstance(location, str) or not location:
return
file_level = fiona_settings.get("file_log_level")
if not isinstance(file_level, str) or file_level.upper() not in logging.getLevelNamesMapping():
if file_level is not None:
logging.getLogger(__name__).warning(
"Invalid file_log_level %r, falling back to %s", file_level, console_level
)
file_level = console_level
try:
handler = _SharedFileHandler(location, encoding="utf-8")
except OSError as error:
logging.getLogger(__name__).warning("Cannot open log file %s: %s", location, error)
return
handler.setLevel(logging.getLevelNamesMapping()[file_level.upper()])
handler.setFormatter(logging.Formatter(FILE_LOG_FORMAT))
setattr(handler, FILE_HANDLER_TAG, True)
logging.getLogger().addHandler(handler)
logging.getLogger(__name__).debug("file logging to %s at %s", location, file_level.upper())
def setup_logging(
settings: dict | None = None,
settings_file: str | pathlib.Path | None = None,
) -> str:
"""Configure logging for every Fiona tool.
Args:
settings: The full settings mapping. When None, the settings
file is loaded (see `settings_file`).
settings_file: Settings file used when `settings` is None;
defaults to the packaged template.
Returns:
The effective level name (e.g. "INFO").
"""
if settings is None:
settings = load_settings(settings_file)
level_name = load_log_level(settings)
level = logging.getLevelNamesMapping()[level_name]
logging.basicConfig(format=LOG_FORMAT, stream=sys.stderr)
for logger_name in TOOL_LOGGER_NAMES:
logging.getLogger(logger_name).setLevel(level)
fiona_settings = settings.get("fiona")
if not isinstance(fiona_settings, dict):
fiona_settings = {}
_configure_file_log(fiona_settings, level_name)
logging.getLogger(__name__).debug("logging configured at %s", level_name)
return level_name