stogger.core¶
Core logging functionality for stogger.
Attributes¶
Classes¶
Render event_dict nicely aligned, in colors, and ordered with |
|
JSON renderer for structured logging output. |
|
Processor that selects a string from the dict returned by ConsoleFileRenderer. |
|
Stub factory for systemd journal logger integration. |
|
Render structlog events as systemd journal fields. |
|
Render event_dict into a column dict for PostgreSQL INSERT. |
|
Renderer for command output file logging. |
|
Calls multiple renderers with a shallow copy of the event dict and collects |
|
Factory that creates |
|
Distribute log messages to multiple sub-loggers by target name. |
Functions¶
|
Add a prefix to each line of a multi-line string. |
|
|
|
|
|
|
|
Renders exc_info if it's present. |
|
Bridge structlog events to Python's standard library logging module. |
|
Initialize full structured logging with console, file, and journal targets. |
|
Initialize minimal structured logging before full setup. |
|
Add a command output file logger to the active multi-logger factory. |
Close and delete the command output log file. |
|
Check whether structured logging has been configured. |
Module Contents¶
- stogger.core.log¶
- class stogger.core.PartialFormatter(missing='<missing>', bad_format='<bad format>')[source]¶
Bases:
string.Formatter- missing = '<missing>'¶
- bad_format = '<bad format>'¶
- class stogger.core.ConsoleFileRenderer(format_config=None, min_level=None, show_caller_info=None)[source]¶
Render event_dict nicely aligned, in colors, and ordered with specific knowledge about stogger structures.
- LEVELS: ClassVar[list[str]] = ['alert', 'critical', 'error', 'exception', 'warn', 'warning', 'info', 'debug', 'trace']¶
- format_config = None¶
- min_level¶
- show_caller_info¶
- pad_event¶
- show_logger_brackets = False¶
- show_pid = False¶
- timestamp_format¶
- class stogger.core.JSONRenderer(min_level='info')[source]¶
JSON renderer for structured logging output.
- min_level_idx¶
- stogger.core.format_exc_info(_logger, _name, event_dict)[source]¶
Renders exc_info if it’s present. Expects the tuple format returned by sys.exc_info(). Compared to structlog’s format_exc_info(), this renders the exception information separately which is better for structured logging targets.
- class stogger.core.SelectRenderedString(key='console')[source]¶
Processor that selects a string from the dict returned by ConsoleFileRenderer.
This ensures that structlog.stdlib.ProcessorFormatter receives a string as required, avoiding RuntimeWarnings.
- Parameters:
key (str)
- key = 'console'¶
- stogger.core.log_to_stdlib(_logger, _name, event_dict)[source]¶
Bridge structlog events to Python’s standard library logging module.
This processor forwards every structlog event to
logging.log()so that tools relying on stdlib handlers (e.g.pytest caplog) can capture them.Do NOT add this to the default processor pipeline. Stogger configures its own renderers and file handlers. Adding this processor causes every event to appear twice — once via stogger’s
MultiRendererand once via the stdlib root logger.Use cases where this is useful:
Legacy code that reads from stdlib
logginghandlersAd-hoc debugging with
logging.basicConfig()
For test assertions, prefer
pytest-structlogwhich captures events directly from the structlog pipeline without needing a stdlib bridge.- Args:
_logger: The structlog logger (unused). _name: The log method name (unused). event_dict: The structured event dictionary.
- Returns:
The unmodified
event_dict(pass-through processor).
- stogger.core.init_logging(*, logdir=None, log_cmd_output=False, log_to_console=True, syslog_identifier=None, verbose=None, show_caller_info=None)[source]¶
Initialize full structured logging with console, file, and journal targets.
Configures structlog with a multi-target rendering pipeline: systemd journal, optional command output file, and a colorized console/file renderer. Sets up processors for PID, log level, exception formatting, timestamps, and caller info.
- Args:
- logdir: Directory for log files. A
{syslog_identifier}.logfile is created here when writable. Required if
log_cmd_outputis True.- log_cmd_output: Enable separate command output logging to a dedicated file
in
logdir. Requireslogdirto be set.- log_to_console: Log to stderr. Disabled automatically when running under
systemd journal (detected via
JOURNAL_STREAMenv var).- syslog_identifier: Identifier string for syslog/journal entries. Also used
as the main log file name (
{syslog_identifier}.log). When None (default), uses the value from settings (syslog_identifierin[tool.stogger]config).- verbose: When True, sets the console log level to
"debug". When None (default), uses the level from settings (typically
"info").- show_caller_info: Whether to display code location (file, function, line)
in console output. When None (default), uses the setting from
FormatConfig.show_code_info.
- logdir: Directory for log files. A
- Raises:
ValueError: If
log_cmd_outputis True butlogdiris not set.
- stogger.core.init_early_logging(*, verbose=False)[source]¶
Initialize minimal structured logging before full setup.
Configures a lightweight structlog pipeline (timestamp, level, console renderer) so that early startup messages are properly formatted instead of appearing as raw dicts. No-op if structlog is already configured. Errors during setup are suppressed to avoid crashing during early initialization, but logged at debug level.
- Args:
- verbose: When
True, emit debug messages showing the caller that invoked this function. Also enabled when the
STOGGER_DEBUGenvironment variable is set.
- verbose: When
- Parameters:
verbose (bool)
- Return type:
None
- class stogger.core.JournalLoggerFactory[source]¶
Stub factory for systemd journal logger integration.
Returns
Noneby default. Actual systemd journal support is provided by thestogger-systemdpackage, which replaces this factory with a real journal writer. Use this as a placeholder so logging pipelines work without the systemd extra installed.
- stogger.core.JOURNAL_LEVELS¶
- stogger.core.KEYS_TO_SKIP_IN_JOURNAL_MESSAGE = ['_output', '_raw_output', '_raw_output_prefix', '_replace_msg', 'code_file', 'code_func',...¶
- class stogger.core.SystemdJournalRenderer(syslog_identifier, syslog_facility=syslog.LOG_LOCAL0)[source]¶
Render structlog events as systemd journal fields.
Transforms event dicts into journal-compatible key-value pairs with uppercased field names, syslog priority/facility, and a human-readable message string. Strings are kept un-JSON-encoded to preserve line breaks in
journalctloutput.- Args:
syslog_identifier: Identifier string for SYSLOG_IDENTIFIER field. syslog_facility: Syslog facility code (default:
syslog.LOG_LOCAL0).
- syslog_identifier¶
- syslog_facility = 128¶
- class stogger.core.PostgresRenderer[source]¶
Render event_dict into a column dict for PostgreSQL INSERT.
Extracts known columns (timestamp, level, event, func, scope) and packs remaining fields into JSONB data.
- KNOWN_FIELDS¶
- class stogger.core.MultiRenderer(**renderers)[source]¶
Calls multiple renderers with a shallow copy of the event dict and collects their messages in a dict with the renderer names as keys and their rendered output as values. It doesn’t care about the rendered messages so different logger types can get different types of messages. Normally, this should be placed last in the processors chain. Errors in renderers are ignored silently.
- renderers¶
- class stogger.core.MultiOptimisticLoggerFactory(context, factories)[source]¶
Factory that creates
MultiOptimisticLoggerinstances.Holds shared context (e.g.
logdir) and a dict of sub-logger factories (e.g."console"→PrintLoggerFactory,"file"→PrintLoggerFactory). Each factory is called once perMultiOptimisticLoggerinstantiation.- Args:
context: Shared context dict available to all created loggers. factories: Dict mapping target names to structlog logger factory callables.
- context¶
- factories¶
- class stogger.core.MultiOptimisticLogger(loggers)[source]¶
Distribute log messages to multiple sub-loggers by target name.
Receives a dict of rendered outputs keyed by target name (e.g.
"console","file","journal") and dispatches each to the corresponding sub-logger. Targets not present in the message are skipped. Errors in individual sub-loggers are caught and reported to stdlib logging to prevent one failing target from affecting others.- Args:
loggers: Dict mapping target names to structlog logger instances.
- loggers¶
- stogger.core.init_command_logging(log, logdir=None)[source]¶
Add a command output file logger to the active multi-logger factory.
Opens (or overwrites) a dedicated log file for capturing subprocess command output separately from the main log. When running under systemd (detected via
INVOCATION_IDenv var), the filename includes a timestamp and invocation ID for uniqueness.- Args:
log: A structlog BoundLogger instance (typically from
structlog.get_logger()). logdir: Directory for the command output file. Falls back to thelogdirstored in the currentMultiOptimisticLoggerFactorycontext.
- Return type:
None
- stogger.core.drop_cmd_output_logfile(log)[source]¶
Close and delete the command output log file.
Removes the file created by
init_command_logging. Use this when no meaningful command output was produced to avoid leaving empty log files.- Args:
log: A structlog BoundLogger instance for diagnostic messages.
- Raises:
- KeyError: If the
cmd_output_filefactory is not present in the active
MultiOptimisticLoggerFactory(i.e.init_command_loggingwas never called).
- KeyError: If the
- Return type:
None