Skip to content

Commit a60241a

Browse files
logging best practice (#724)
* config: set logging style only if the config value logging.climada_style says so * changelog entry added * fix climada.conf: set logging.climada_style in package config, not test changelog: add PR number * doc install: make logging section more general * fix typos * config: change logging.climada_style -> logging.managed * changelog: new config name outdated
1 parent 5c5f87d commit a60241a

File tree

4 files changed

+36
-20
lines changed

4 files changed

+36
-20
lines changed

CHANGELOG.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -41,6 +41,7 @@ Removed:
4141
- `Exposures.affected_total_value` now takes a hazard intensity threshold as argument. Affected values are only those for which at least one event exceeds the threshold. (previously, all exposures points with an assigned centroid were considered affected). By default the centroids are reassigned. [#702](https://github.com/CLIMADA-project/climada_python/pull/702) [#730](https://github.com/CLIMADA-project/climada_python/pull/730)
4242
- Add option to pass region ID to `LitPop.from_shape` [#720](https://github.com/CLIMADA-project/climada_python/pull/720)
4343
- Slightly improved performance on `LitPop`-internal computations [#720](https://github.com/CLIMADA-project/climada_python/pull/720)
44+
- Users can opt-out of the climada specific logging definitions and freely configure logging to their will, by setting the config value `logging.managed` to `false`. [#724](https://github.com/CLIMADA-project/climada_python/pull/724)
4445
- Add option to read additional variables from IBTrACS when using `TCTracks.from_ibtracs_netcdf` [#728](https://github.com/CLIMADA-project/climada_python/pull/728)
4546

4647
### Fixed

climada/conf/climada.conf

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -57,6 +57,9 @@
5757
}
5858
},
5959
"log_level": "WARNING",
60+
"logging": {
61+
"managed": true
62+
},
6063
"max_matrix_size": 1000000000,
6164
"data_api": {
6265
"url": "https://climada.ethz.ch/data-api/v2/",

climada/util/config.py

Lines changed: 14 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -30,15 +30,6 @@
3030
from pathlib import Path
3131

3232

33-
LOGGER = logging.getLogger('climada')
34-
LOGGER.propagate = False
35-
FORMATTER = logging.Formatter(
36-
"%(asctime)s - %(name)s - %(levelname)s - %(message)s")
37-
CONSOLE = logging.StreamHandler(stream=sys.stdout)
38-
CONSOLE.setFormatter(FORMATTER)
39-
LOGGER.addHandler(CONSOLE)
40-
41-
4233
class Config():
4334
"""Convenience Class. A Config object is a slow JSON object like nested dictonary who's values
4435
can be accessed by their names right away. E.g.: `a.b.c.str()` instead of `a['b']['c']`
@@ -360,6 +351,19 @@ def _fetch_conf(directories, config_name):
360351
Path(Path.home(), '.config'), # ~/.config directory
361352
Path.cwd(), # current working directory
362353
]
354+
363355
CONFIG = Config.from_dict(_fetch_conf(CONFIG_DIRS, CONFIG_NAME))
364356
Config.SOURCE_DIR = SOURCE_DIR
365-
LOGGER.setLevel(getattr(logging, CONFIG.log_level.str()))
357+
358+
359+
# set climada style logging
360+
if CONFIG.logging.managed.bool():
361+
LOGGER = logging.getLogger('climada')
362+
LOGGER.propagate = False
363+
FORMATTER = logging.Formatter(
364+
"%(asctime)s - %(name)s - %(levelname)s - %(message)s")
365+
CONSOLE = logging.StreamHandler(stream=sys.stdout)
366+
CONSOLE.setFormatter(FORMATTER)
367+
LOGGER.addHandler(CONSOLE)
368+
369+
LOGGER.setLevel(getattr(logging, CONFIG.log_level.str()))

doc/guide/install.rst

Lines changed: 18 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -452,35 +452,43 @@ After **each** of the following steps, check if the problem is solved, and only
452452
#. Still no good?
453453
Please raise an `issue on GitHub <https://github.com/CLIMADA-project/climada_python/issues>`_ to get help.
454454

455-
Changing the Logging Level
456-
^^^^^^^^^^^^^^^^^^^^^^^^^^
455+
Logging Configuration
456+
^^^^^^^^^^^^^^^^^^^^^
457457

458-
By default the logging level is set to ``INFO``, which is quite verbose.
459-
You can change this setting in multiple ways:
458+
Climada makes use of the standard `logging <https://docs.python.org/3/howto/logging.html>`_ package.
459+
By default, the "climada"-``Logger`` is detached from ``logging.root``, logging to `stdout` with
460+
the level set to ``WARNING``.
461+
462+
If you prefer another logging configuration, e.g., for using Climada embedded in another application,
463+
you can opt out of the default pre-configuration by setting the config value for
464+
``logging.climada_style`` to ``false`` in the :doc:`configuration file <Guide_Configuration>`
465+
``climada.conf``.
466+
467+
Changing the logging level can be done in multiple ways:
460468

461469
* Adjust the :doc:`configuration file <Guide_Configuration>` ``climada.conf`` by setting a the value of the ``global.log_level`` property.
470+
This only has an effect if the ``logging.climada_style`` is set to ``true`` though.
462471

463472
* Set a global logging level in your Python script:
464473

465474
.. code-block:: python
466475
467-
from climada.util.config import LOGGER
468-
from logging import WARNING
469-
LOGGER.setLevel(WARNING)
476+
import logging
477+
logging.getLogger('climada').setLevel(logging.ERROR) # to silence all warnings
470478
471479
* Set a local logging level in a context manager:
472480

473481
.. code-block:: python
474482
475483
from climada.util import log_level
476-
with log_level(level="WARNING"):
477-
# This code only emits log levels 'WARNING' or higher
484+
with log_level(level="INFO"):
485+
# This also emits all info log messages
478486
foo()
479487
480488
# Default logging level again
481489
bar()
482490
483-
All of these approaches can also be combined.
491+
All three approaches can also be combined.
484492

485493
`Mamba <https://mamba.readthedocs.io/en/latest/>`_ Instead of Anaconda
486494
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

0 commit comments

Comments
 (0)