Skip to content

Commit

Permalink
Implement more consistent logging behavior with ixmp4
Browse files Browse the repository at this point in the history
  • Loading branch information
danielhuppmann committed Mar 6, 2024
1 parent dc17880 commit 221f1ce
Show file tree
Hide file tree
Showing 3 changed files with 38 additions and 31 deletions.
32 changes: 2 additions & 30 deletions pyam/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,9 +24,6 @@
from pyam.unfccc import read_unfccc # noqa: F401
from pyam.utils import IAMC_IDX # noqa: F401

logger = logging.getLogger(__name__)

# get version number either from git (preferred) or metadata
try:
__version__ = get_version(root=Path(__file__).parents[1])
except LookupError:
Expand All @@ -36,31 +33,6 @@
except PackageNotFoundError:
__version__ = version("pyam")

# special handling in Jupyter notebooks
try:
from ipykernel.zmqshell import ZMQInteractiveShell
from IPython import get_ipython

shell = get_ipython()
if isinstance(shell, ZMQInteractiveShell):
# harmonize formatting of ixmp4 and pyam logging
ixmp4_logger = logging.getLogger("ixmp4")
ixmp4_logger.removeHandler(ixmp4_logger.handlers[0])

handler = logging.StreamHandler()
handler.setFormatter(logging.Formatter("%(name)s - %(levelname)s: %(message)s"))

for _logger in [logger, ixmp4_logger]:
_logger.addHandler(handler)

# deactivate in-cell scrolling in a Jupyter notebook
shell.run_cell_magic(
"javascript",
"",
"if (typeof IPython !== 'undefined') "
"{ IPython.OutputArea.prototype._should_scroll = function(lines)"
"{ return false; }}",
)

except Exception:
pass
# Set up logging overriding the ixmp4 logging configuration
logging.configure_logging()
29 changes: 29 additions & 0 deletions pyam/logging.conf
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@

[loggers]
keys = root,pyam_core

[handlers]
keys = console

[formatters]
keys = generic

[logger_root]
level = NOTSET
handlers =
qualname =

[logger_pyam_core]
level = INFO
handlers = console
qualname = pyam

[handler_console]
class = StreamHandler
args = (sys.stderr,)
level = NOTSET
formatter = generic

[formatter_generic]
format = [%(levelname)s] %(asctime)s - %(name)s: %(message)s
datefmt = %H:%M:%S
8 changes: 7 additions & 1 deletion pyam/logging.py
Original file line number Diff line number Diff line change
@@ -1,12 +1,18 @@
import warnings
from contextlib import contextmanager
from logging import getLogger
from logging import config, getLogger
from pathlib import Path

import pandas as pd

here = Path(__file__).parent
logger = getLogger(__name__)


def configure_logging():
config.fileConfig(here / "logging.conf", disable_existing_loggers=False)


@contextmanager
def adjust_log_level(logger="pyam", level="ERROR"):
"""Context manager to change log level"""
Expand Down

0 comments on commit 221f1ce

Please sign in to comment.