Skip to content

Commit 4f91e27

Browse files
Clean up the logger setup (#276)
* Simplify logger setup * setup_logging has been removed * changes for coping with removed setup_logging * skip setting log level * InputVar.ent and ent_fut have changed parameters Co-authored-by: emanuel-schmid <[email protected]>
1 parent 83b251b commit 4f91e27

File tree

10 files changed

+24
-83
lines changed

10 files changed

+24
-83
lines changed

climada/__init__.py

Lines changed: 2 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -21,12 +21,10 @@
2121
from shutil import copyfile
2222
from pathlib import Path
2323

24-
from .util.config import CONFIG, setup_logging
24+
from .util.config import CONFIG
2525
from .util.constants import *
2626

2727

28-
__all__ = ['init']
29-
3028
GSDP_DIR = SYSTEM_DIR.joinpath('GSDP')
3129

3230
REPO_DATA = {
@@ -75,10 +73,4 @@ def setup_climada_data(reload=False):
7573
src = Path(__file__).parent.parent.joinpath(src_dir, path.name)
7674
copyfile(src, path)
7775

78-
79-
def init():
80-
setup_climada_data()
81-
setup_logging(CONFIG.log_level.str())
82-
83-
84-
init()
76+
setup_climada_data()

climada/engine/uncertainty_quantification/calc_base.py

Lines changed: 5 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -28,11 +28,9 @@
2828
import numpy as np
2929

3030
from climada.util.value_representation import sig_dig as u_sig_dig
31-
from climada.util.config import setup_logging as u_setup_logging
3231
from climada.engine.uncertainty_quantification import UncOutput
3332

3433
LOGGER = logging.getLogger(__name__)
35-
u_setup_logging()
3634

3735

3836
class Calc():
@@ -69,15 +67,15 @@ def check_distr(self):
6967
x = np.linspace(func.ppf(0.01), func.ppf(0.99), 100)
7068
if not np.all(func.pdf(x) == input_param_func.pdf(x)):
7169
raise ValueError(
72-
"The input parameter %s" %input_param_name +
73-
" is shared amond two input variables with "
74-
"different distributions."
70+
f"The input parameter {input_param_name}"
71+
" is shared amond two input variables with"
72+
" different distributions."
7573
)
7674
LOGGER.warning(
77-
"\n\nThe input parameter %s is shared " %input_param_name +
75+
"\n\nThe input parameter %s is shared " +
7876
"among at least 2 input variables. Their uncertainty is " +
7977
"thus computed with the same samples for this " +
80-
"input paramter.\n\n"
78+
"input paramter.\n\n", input_param_name
8179
)
8280
distr_dict[input_param_name] = input_param_func
8381
return True

climada/engine/uncertainty_quantification/calc_cost_benefit.py

Lines changed: 0 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -30,10 +30,8 @@
3030
from climada.engine.cost_benefit import CostBenefit
3131
from climada.engine.uncertainty_quantification import Calc, InputVar, UncCostBenefitOutput
3232
from climada.util import log_level
33-
from climada.util.config import setup_logging as u_setup_logging
3433

3534
LOGGER = logging.getLogger(__name__)
36-
u_setup_logging()
3735

3836
# Future planed features:
3937
# - Add 'efc' (frequency curve) to UncCostBenenfit

climada/engine/uncertainty_quantification/calc_impact.py

Lines changed: 0 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -31,10 +31,7 @@
3131
from climada.engine.uncertainty_quantification import Calc, InputVar, UncImpactOutput
3232
from climada.util import log_level
3333

34-
from climada.util.config import setup_logging as u_setup_logging
35-
3634
LOGGER = logging.getLogger(__name__)
37-
u_setup_logging()
3835

3936

4037
class CalcImpact(Calc):

climada/engine/uncertainty_quantification/input_var.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -487,7 +487,7 @@ def ent(impf_set, disc_rate, exp, meas_set, haz_id_dict= None,
487487
kwargs['EN'] = None
488488

489489
if haz_id_dict is None:
490-
{'TC': [1]}
490+
haz_id_dict = {'TC': [1]}
491491

492492
return InputVar(
493493
partial(_ent_unc_func, impf_set=impf_set, haz_id_dict=haz_id_dict,
@@ -593,7 +593,7 @@ def entfut(impf_set, exp, meas_set, haz_id_dict=None,
593593
kwargs['EN'] = None
594594

595595
if haz_id_dict is None:
596-
{'TC': [1]}
596+
haz_id_dict = {'TC': [1]}
597597

598598
return InputVar(
599599
partial(_entfut_unc_func, haz_id_dict=haz_id_dict,

climada/engine/uncertainty_quantification/unc_output.py

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -37,11 +37,9 @@
3737

3838
from climada.util.value_representation import value_to_monetary_unit as u_vtm
3939
from climada.util import plot as u_plot
40-
from climada.util.config import setup_logging as u_setup_logging
4140
import climada.util.hdf5_handler as u_hdf5
4241

4342
LOGGER = logging.getLogger(__name__)
44-
u_setup_logging()
4543

4644
# Metrics that are multi-dimensional
4745
METRICS_2D = ['eai_exp', 'at_event']
@@ -62,6 +60,7 @@
6260
'ff' : ['ff'],
6361
}
6462

63+
6564
class UncOutput():
6665
"""
6766
Class to store and plot uncertainty and sensitivity analysis output data

climada/util/config.py

Lines changed: 1 addition & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -21,7 +21,6 @@
2121

2222
__all__ = [
2323
'CONFIG',
24-
'setup_logging',
2524
]
2625

2726
import sys
@@ -31,31 +30,14 @@
3130
from pathlib import Path
3231

3332

34-
def remove_handlers(logger):
35-
"""Remove logger handlers."""
36-
if logger.hasHandlers():
37-
for handler in logger.handlers:
38-
logger.removeHandler(handler)
39-
4033
LOGGER = logging.getLogger('climada')
41-
LOGGER.setLevel(logging.DEBUG)
42-
LOGGER.propagate = False
43-
remove_handlers(LOGGER)
4434
FORMATTER = logging.Formatter(
4535
"%(asctime)s - %(name)s - %(levelname)s - %(message)s")
4636
CONSOLE = logging.StreamHandler(stream=sys.stdout)
4737
CONSOLE.setFormatter(FORMATTER)
4838
LOGGER.addHandler(CONSOLE)
4939

5040

51-
def setup_logging(log_level='DEBUG'):
52-
"""Setup logging configuration"""
53-
remove_handlers(LOGGER)
54-
LOGGER.propagate = False
55-
LOGGER.setLevel(getattr(logging, log_level))
56-
LOGGER.addHandler(CONSOLE)
57-
58-
5941
class Config():
6042
"""Convenience Class. A Config object is a slow JSON object like nested dictonary who's values
6143
can be accessed by their names right away. E.g.: `a.b.c.str()` instead of `a['b']['c']`
@@ -321,3 +303,4 @@ def _fetch_conf(directories, config_name):
321303
Path(Path.home(), '.config'), # ~/.config directory
322304
Path.cwd(), # current working directory
323305
], CONFIG_NAME))
306+
LOGGER.setLevel(getattr(logging, CONFIG.log_level.str()))

doc/guide/Guide_Installation.ipynb

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,6 @@
22
"cells": [
33
{
44
"cell_type": "markdown",
5-
"metadata": {},
65
"source": [
76
"# Installation\r\n",
87
"\r\n",
@@ -95,12 +94,13 @@
9594
"* No 'impf\\_TC' column in GeoDataFrame: This may happen when a demo file from CLIMADA was not updated after the change in the impact function naming pattern from 'if\\_' to 'impf\\_' ([climada v2.2.0](https://github.com/CLIMADA-project/climada_python/releases/tag/v2.2.0)).\r\n",
9695
" To solve it, run `python -c 'import climada; climada.setup_climada_data(reload=True)` in a terminal.\r\n",
9796
"\r\n",
98-
"* How to change the log level: By default the logging level is set to ``'INFO'``. This can be changed\r\n",
97+
"* How to change the log level: By default the logging level is set to ``'INFO'``, which is quite verbose. This can be changed\r\n",
9998
"\r\n",
100-
" * programmatically, in a script or interactive python environment (Spyder, Jupyter, IPython) by executing e.g., ``CLIMADA.util.config.setup_logging('DEBUG')``, \r\n",
99+
" * programmatically, in a script or interactive python environment (Spyder, Jupyter, IPython) by executing e.g., ``from climada.util.config import LOGGER; from logging import WARNING; LOGGER.setLevel(WARNING)``, \r\n",
101100
" \r\n",
102101
" * through configuration, by editing the config file ``CLIMADA/conf/defaults.conf`` and setting the value of the ``global.log_level`` property.\r\n"
103-
]
102+
],
103+
"metadata": {}
104104
}
105105
],
106106
"metadata": {

doc/guide/Guide_PythonDos-n-Donts.ipynb

Lines changed: 6 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -939,12 +939,12 @@
939939
}
940940
},
941941
"source": [
942-
"You can set the level of the LOGGER using `util.config.setup_logging(\"level\")`. This way you can for instance 'turn-off' info messages when you are making an application. For example, setting the logger to the \"ERROR\" level, use:"
942+
"You can set the level of the LOGGER using `climada.util.config.LOGGER.setLevel(logging.XXX)`. This way you can for instance 'turn-off' info messages when you are making an application. For example, setting the logger to the \"ERROR\" level, use:"
943943
]
944944
},
945945
{
946946
"cell_type": "code",
947-
"execution_count": 1,
947+
"execution_count": null,
948948
"metadata": {
949949
"ExecuteTime": {
950950
"end_time": "2021-01-15T17:57:29.203374Z",
@@ -954,18 +954,11 @@
954954
"slide_type": "slide"
955955
}
956956
},
957-
"outputs": [
958-
{
959-
"name": "stdout",
960-
"output_type": "stream",
961-
"text": [
962-
"2021-01-15 18:57:27,342 - climada - DEBUG - Loading default config file: /Users/ckropf/Documents/Climada/climada_python/climada/conf/defaults.conf\n"
963-
]
964-
}
965-
],
957+
"outputs": [],
966958
"source": [
967-
"from climada import util\n",
968-
"util.config.setup_logging(\"ERROR\")"
959+
"import logging\n",
960+
"from climada.util.config import LOGGER\n",
961+
"LOGGER.setLevel(logging.ERROR)"
969962
]
970963
},
971964
{

doc/tutorial/climada_engine_uncertainty.ipynb

Lines changed: 3 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -14,23 +14,6 @@
1414
"This is a tutorial for the uncertainty quantification package in CLIMADA."
1515
]
1616
},
17-
{
18-
"cell_type": "code",
19-
"execution_count": 1,
20-
"metadata": {
21-
"ExecuteTime": {
22-
"end_time": "2021-09-29T08:17:07.260649Z",
23-
"start_time": "2021-09-29T08:17:03.552693Z"
24-
}
25-
},
26-
"outputs": [],
27-
"source": [
28-
"#Run this cell to set the logger to level error for this notebook and \n",
29-
"#reduce the number of warnings and info given by the CLIMADA methods.\n",
30-
"from climada import util\n",
31-
"util.config.setup_logging(\"ERROR\")"
32-
]
33-
},
3417
{
3518
"cell_type": "markdown",
3619
"metadata": {
@@ -12264,7 +12247,7 @@
1226412247
" bounds_impfi=bounds_impfi,\n",
1226512248
" bounds_mdd=bounds_mdd,\n",
1226612249
" bounds_paa=bounds_paa,\n",
12267-
" haz_id_dict = {'TC': [1]})"
12250+
" haz_id_dict={'TC': [1]})"
1226812251
]
1226912252
},
1227012253
{
@@ -12390,8 +12373,7 @@
1239012373
" bounds_mdd=[0.9, 1.05],\n",
1239112374
" bounds_paa=None,\n",
1239212375
" bounds_impfi=[-2, 5],\n",
12393-
" haz_type='TC',\n",
12394-
" fun_id=1\n",
12376+
" haz_id_dict={'TC': [1]}\n",
1239512377
" )"
1239612378
]
1239712379
},
@@ -12512,8 +12494,7 @@
1251212494
" bounds_noise=None,\n",
1251312495
" bounds_mdd=[0.7, 0.9],\n",
1251412496
" bounds_paa=[1.3, 2],\n",
12515-
" haz_type='TC',\n",
12516-
" fun_id=1\n",
12497+
" haz_id_dict={'TC': [1]}\n",
1251712498
" )"
1251812499
]
1251912500
},

0 commit comments

Comments
 (0)