Skip to content

Commit 2c513a4

Browse files
committed
Fix root logger config to prevent duplicate outputs
1 parent 08a340a commit 2c513a4

File tree

2 files changed

+37
-9
lines changed

2 files changed

+37
-9
lines changed

xcdat/__init__.py

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
"""Top-level package for xcdat."""
22

33
from xcdat import tutorial # noqa: F401
4+
from xcdat._logger import _setup_root_logger
45
from xcdat.axis import ( # noqa: F401
56
center_times,
67
get_coords_by_name,
@@ -25,4 +26,7 @@
2526
from xcdat.temporal import TemporalAccessor # noqa: F401
2627
from xcdat.utils import compare_datasets # noqa: F401
2728

29+
# Initialize root logger once when the package is imported
30+
_setup_root_logger()
31+
2832
__version__ = "0.10.1"

xcdat/_logger.py

Lines changed: 33 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -4,17 +4,41 @@
44
import logging.handlers
55

66
# Logging module setup
7-
log_format = (
7+
LOG_FORMAT = (
88
"%(asctime)s [%(levelname)s]: %(filename)s(%(funcName)s:%(lineno)s) >> %(message)s"
99
)
10-
logging.basicConfig(format=log_format, filemode="w", level=logging.INFO)
11-
12-
# Console handler setup
13-
console_handler = logging.StreamHandler()
14-
console_handler.setLevel(logging.INFO)
15-
logFormatter = logging.Formatter(log_format)
16-
console_handler.setFormatter(logFormatter)
17-
logging.getLogger().addHandler(console_handler)
10+
11+
LOG_LEVEL = logging.INFO
12+
13+
14+
def _setup_root_logger():
15+
"""Configures the root logger.
16+
17+
This function sets up the root logger with a predefined format and log level.
18+
It also enables capturing of warnings issued by the `warnings` module and
19+
redirects them to the logging system.
20+
21+
Notes
22+
-----
23+
- The `force=True` parameter ensures that any existing logging configuration
24+
is overridden.
25+
- The file handler is added dynamically to the root logger later in the
26+
``Run`` class once the log file path is known.
27+
"""
28+
logging.basicConfig(
29+
format=LOG_FORMAT,
30+
level=LOG_LEVEL,
31+
force=True,
32+
)
33+
34+
logging.captureWarnings(True)
35+
36+
# Add a console handler to display warnings in the console. This is useful
37+
# for when other package loggers raise warnings (e.g, NumPy, Xarray).
38+
console_handler = logging.StreamHandler()
39+
console_handler.setLevel(logging.INFO)
40+
console_handler.setFormatter(logging.Formatter(LOG_FORMAT))
41+
logging.getLogger().addHandler(console_handler)
1842

1943

2044
def _setup_custom_logger(name, propagate=True) -> logging.Logger:

0 commit comments

Comments
 (0)