Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Redirect errors/tracebacks to the right logging stream #114

Merged
merged 1 commit into from
Mar 13, 2025
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
35 changes: 35 additions & 0 deletions workflow/src/legenddataflow/log.py
Original file line number Diff line number Diff line change
@@ -1,10 +1,28 @@
import logging
import sys
import traceback
from logging.config import dictConfig
from pathlib import Path

from dbetto import Props


class StreamToLogger:
"""File-like stream object that redirects writes to a logger instance."""

def __init__(self, logger, log_level=logging.ERROR):
self.logger = logger
self.log_level = log_level
self.linebuf = ""

def write(self, buf):
for line in buf.rstrip().splitlines():
self.logger.log(self.log_level, line.rstrip())

def flush(self):
pass


def build_log(
config_dict: dict, log_file: str | None = None, fallback: str = "prod"
) -> logging.Logger:
Expand Down Expand Up @@ -37,4 +55,21 @@ def build_log(

log = logging.getLogger(fallback)

# Redirect stderr to the logger (using the error level)
sys.stderr = StreamToLogger(log, logging.ERROR)

# Extract the stream from the logger's file handler.
log_stream = None
for handler in log.handlers:
if hasattr(handler, "stream"):
log_stream = handler.stream
break
if log_stream is None:
log_stream = sys.stdout

def excepthook(exc_type, exc_value, exc_traceback):
traceback.print_exception(exc_type, exc_value, exc_traceback, file=log_stream)

sys.excepthook = excepthook

return log
Loading