Skip to content

Commit 6f9502c

Browse files
authored
Merge pull request #7 from mlcommons/add-fq-caller-info
Add fully-qualified caller information, if so desired
2 parents 3518488 + b452d43 commit 6f9502c

7 files changed

Lines changed: 346 additions & 43 deletions

File tree

‎README.md‎

Lines changed: 37 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -6,15 +6,14 @@ The airrlogger package provides a standardized logging configuration for AIRR ap
66

77
Install in a poetry project: `poetry add airrlogger`
88

9-
Near the top of any file where you want to log, do something like:
9+
Near the top of any module where you want to log, do something like:
1010

1111
```python
1212
from airrlogger.log_config import get_logger
1313
logger = get_logger(__name__)
1414
```
1515

16-
Then as early as possible in your program's startup, tell it how to
17-
handle the logging:
16+
Then as early as possible in your program's startup, tell it how to handle the logging:
1817

1918
```python
2019
import logging
@@ -23,8 +22,8 @@ from airrlogger.log_config import configure_logging
2322
configure_logging(app_name="myapp", level=logging.INFO)
2423
```
2524

25+
You can then log like this:
2626

27-
You can then log like this
2827
```python
2928
logger.info("some info logging")
3029
```
@@ -35,28 +34,57 @@ The default output looks like this:
3534
2026-01-09T21:14:13Z - myapp - __main__ - INFO - some info logging
3635
```
3736

38-
3937
### DefaultFormatter
4038

4139
A class that formats log messages with UTC timestamps and optional ANSI color codes for console output.
4240

43-
### configure_logging
41+
### DebuggingFormatter
42+
43+
A class that formats log messages mostly like `DefaultFormatter`, adding the fully-qualified scope and lined number
44+
where the logging event happens.
45+
46+
To use it:
47+
48+
```python
49+
import logging
4450

45-
A function that configure the root logger with console and optional file output.
51+
from log_config import DebuggingFormatter, configure_logging, get_logger
52+
logger = get_logger("my app")
53+
configure_logging("test_module", logging.DEBUG, formatter=DebuggingFormatter)
54+
```
4655

56+
The output looks like this:
57+
58+
```
59+
2026-03-24T20:43:13Z - test_module - my app - ERROR - test:8 - calling from top-level scope before everything else
60+
2026-03-24T20:43:13Z - test_module - my app - ERROR - test:25 - calling from main block in top-level scope
61+
2026-03-24T20:43:13Z - test_module - my app - ERROR - test.MyClass.my_method:13 - calling from my_method
62+
2026-03-24T20:43:13Z - test_module - my app - ERROR - test.MyClass.my_static_method:17 - calling from my_static_method
4763
```
64+
65+
This formatter is independent of the log level. You can use it even if your log level is not `logging.DEBUG`.
66+
67+
There is some performance overhead with this method you should keep in mind in a production environment.
68+
69+
### configure_logging
70+
71+
A function that configure the root logger with console and optional file output. You can call it multiple times
72+
with different loggers or formatters and they will be added to the root logger's log handlers.
73+
74+
```python
4875
from airrlogger.log_config import configure_logging
4976

5077
logger = configure_logging(app_name="modelrunner-api", file="./app.log", level=logging.DEBUG)
5178
```
5279

5380
### get_config_dict
5481

55-
Generates logging configuration dictionaries for use with logging.config.dictConfig. By default, the app name is derived from the package name, but that can be overridden.
82+
Generates logging configuration dictionaries for use with `logging.config.dictConfig`. By default, the app name
83+
is derived from the package name, but that can be overridden.
5684

5785
This is particularly useful for FastAPI applications, which can adopt this logger by using something like:
5886

59-
```
87+
```python
6088
run(app, host="0.0.0.0", port=port, log_config=get_config_dict(app_name="modelrunner-api"))
6189
```
6290

‎airrlogger/log_config.py‎

Lines changed: 102 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,25 @@
1+
import inspect
12
import logging
3+
import os
24
import sys
35
import time
46
from typing import Any, Dict, Optional
57

68

7-
class DefaultFormatter(logging.Formatter):
9+
class VariantFormatter(logging.Formatter):
10+
"""This allows us to pass arbitrary arguments to our Formatter class
11+
without breaking compatibility with the base Formatter class."""
12+
13+
def __init__(self, *args, **kwargs):
14+
fmt = kwargs.get("fmt", None)
15+
datefmt = kwargs.get("datefmt", None)
16+
style = kwargs.get("style", "%")
17+
validate = kwargs.get("validate", True)
18+
defaults = kwargs.get("defaults", None)
19+
super().__init__(fmt, datefmt, style, validate, defaults=defaults)
20+
21+
22+
class DefaultFormatter(VariantFormatter):
823
converter = time.gmtime # type: ignore
924
COLORS = {
1025
"DEBUG": "\x1b[38;21m",
@@ -14,14 +29,12 @@ class DefaultFormatter(logging.Formatter):
1429
"CRITICAL": "\x1b[31;1m",
1530
"RESET": "\x1b[0m",
1631
}
32+
base_format = "%(asctime)s - {app_name} - %(name)s - %(levelname)s - %(message)s"
1733

1834
def __init__(self, app_name: str = ".", include_colors: bool = True):
1935
super().__init__()
2036
self.app_name = app_name
2137
self.include_colors = include_colors
22-
self.base_format = (
23-
"%(asctime)s - {app_name} - %(name)s - %(levelname)s - %(message)s"
24-
)
2538

2639
def format(self, record: logging.LogRecord) -> str:
2740
date_format = "%Y-%m-%dT%H:%M:%SZ"
@@ -36,16 +49,52 @@ def format(self, record: logging.LogRecord) -> str:
3649
return formatter.format(record)
3750

3851

52+
class CallStackFilter(logging.Filter):
53+
"""This filter finds and returns the fully-qualified call stack
54+
where the logger.debug|info|error (etc) call happened."""
55+
56+
def filter(self, record: logging.LogRecord) -> bool:
57+
frame = inspect.currentframe()
58+
while frame is not None:
59+
if (
60+
frame.f_code.co_filename == record.pathname
61+
and frame.f_lineno == record.lineno
62+
):
63+
chunks = []
64+
65+
module = os.path.splitext(os.path.basename(record.pathname))[0]
66+
if module != "<module>":
67+
chunks.append(module)
68+
69+
qualname = frame.f_code.co_qualname
70+
if qualname != "<module>":
71+
chunks.append(qualname)
72+
73+
record.caller = ".".join(chunks) # type: ignore[attr-defined]
74+
break
75+
76+
frame = frame.f_back
77+
else:
78+
record.caller = f"{record.module}.{record.funcName}" # type: ignore[attr-defined]
79+
return True
80+
81+
82+
class DebuggingFormatter(DefaultFormatter):
83+
base_format = "%(asctime)s - {app_name} - %(name)s - %(levelname)s - %(caller)s:%(lineno)d - %(message)s"
84+
85+
def format(self, record: logging.LogRecord) -> str:
86+
CallStackFilter().filter(record)
87+
return super().format(record)
88+
89+
3990
def configure_logging(
4091
app_name: str = ".",
4192
level: int = logging.INFO,
4293
log_file: Optional[str] = None,
94+
formatter: type[VariantFormatter] = DefaultFormatter,
4395
) -> None:
4496
"""Configures the root logger. Preserves existing handlers (if any).
4597
46-
NOTE: if you call this function multiple times, you may end up with
47-
duplicate log messages, since each call adds new handlers to the root logger.
48-
4998
Args:
5099
app_name: Name of the application to include in log messages.
51100
level: Logging level to set.
@@ -54,13 +103,32 @@ def configure_logging(
54103
logger = logging.getLogger()
55104
logger.setLevel(level)
56105

106+
# Prevent dupe file handlers
107+
# This allows you to add handlers by calling the function again,
108+
# without getting duplicate entries in your existing logs.
57109
if log_file:
110+
for h in logger.handlers:
111+
if (
112+
isinstance(h, logging.FileHandler)
113+
and h.baseFilename == os.path.abspath(log_file)
114+
and isinstance(h.formatter, formatter)
115+
):
116+
return
58117
file_handler = logging.FileHandler(log_file)
59-
file_handler.setFormatter(DefaultFormatter(app_name, include_colors=False))
118+
file_handler.setFormatter(formatter(app_name, include_colors=False))
60119
logger.addHandler(file_handler)
61120
else:
121+
# prevent dupe stream handlers too
122+
for h in logger.handlers:
123+
if (
124+
isinstance(h, logging.StreamHandler)
125+
and not isinstance(h, logging.FileHandler)
126+
and h.stream is sys.stderr
127+
and isinstance(h.formatter, formatter)
128+
):
129+
return
62130
console_handler = logging.StreamHandler(stream=sys.stderr)
63-
console_handler.setFormatter(DefaultFormatter(app_name, include_colors=True))
131+
console_handler.setFormatter(formatter(app_name, include_colors=True))
64132
logger.addHandler(console_handler)
65133

66134

@@ -110,3 +178,28 @@ def get_config_dict(
110178
config["root"]["handlers"].append("file")
111179

112180
return config
181+
182+
183+
def redacted(value):
184+
if isinstance(value, str):
185+
return _redact(value)
186+
if isinstance(value, dict):
187+
return {k: redacted(v) for k, v in value.items()}
188+
if isinstance(value, list):
189+
return [redacted(v) for v in value]
190+
if isinstance(value, tuple):
191+
return tuple(
192+
redacted(v) for v in value
193+
) # explicit cast to return a tuple, not a generator, to compare w/ tuples
194+
return value
195+
196+
197+
def _redact(value: str) -> str:
198+
if not isinstance(value, str):
199+
return value
200+
l = len(value)
201+
if l <= 2:
202+
return "xx"
203+
if l <= 4:
204+
return f"{value[0]}...{value[-1]}"
205+
return f"{value[:2]}...{value[-2:]}"

‎poetry.lock‎

Lines changed: 59 additions & 18 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

‎pyproject.toml‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
[tool.poetry]
22
name = "airrlogger"
3-
version = "0.1.0"
3+
version = "0.1.1"
44
description = "Python logging configuration library for MLCommons AIRR applications."
55
authors = ["Daniel Hosterman <daniel@mlcommons.org>"]
66
readme = "README.md"

0 commit comments

Comments
 (0)