Skip to content

Commit af1cb71

Browse files
jleratJulien Lerat
and
Julien Lerat
authored
Feature/logdict (#17)
* doc: removed bitbucket pipeline [ci-skip] * chore: moved pipeline and created reduced conda env spec * feat: added logging dict functionnality to logger * fix: polished log commit --------- Co-authored-by: Julien Lerat <[email protected]>
1 parent 337b454 commit af1cb71

File tree

4 files changed

+28
-12
lines changed

4 files changed

+28
-12
lines changed

hydrodiy/io/iutils.py

+21-10
Original file line numberDiff line numberDiff line change
@@ -18,12 +18,6 @@
1818
import numpy as np
1919
import pandas as pd
2020

21-
# Configuration of logging messages
22-
LOGGER_NSEPARATORS = 50
23-
LOGGER_SEPARATOR = "-"
24-
LOGGER_NSEPARATORS_CONTEXTUAL = 3
25-
LOGGER_SEPARATOR_CONTEXTUAL = "#"
26-
2721

2822
def script_template(filename, comment,
2923
type="simple",
@@ -129,6 +123,9 @@ def __init__(self, logger):
129123
assert isinstance(logger, logging.Logger), errmess
130124
self._logger = logger
131125

126+
def get_separator(self, nsep, sep):
127+
return sep*nsep
128+
132129
def error(self, msg, *args, **kwargs):
133130
return self._logger.error(msg, *args, **kwargs)
134131

@@ -147,14 +144,29 @@ def handlers(self):
147144

148145
def started(self):
149146
self.info("@@@ Process started @@@")
150-
self.info(LOGGER_SEPARATOR*LOGGER_NSEPARATORS)
147+
self.info(self.get_separator("-", 30))
151148
self.info("")
152149

153150
def completed(self):
154151
self.info("")
155-
self.info(LOGGER_SEPARATOR*LOGGER_NSEPARATORS)
152+
self.info(self.get_separator("-", 30))
156153
self.info("@@@ Process completed @@@")
157154

155+
def log_dict(self, tolog, name="", level="info"):
156+
""" Add log entry for dictionnary (e.g. created from argparse using vars)"""
157+
assert level in ["info", "warning", "critical", "error"]
158+
logfun = getattr(self, level)
159+
sep = self.get_separator("+", 20)
160+
logfun(sep)
161+
if name!="":
162+
logfun(f"{name}:")
163+
for k, v in tolog.items():
164+
logfun(" "*4+f"{k} = {v}")
165+
166+
logfun(sep)
167+
logfun("")
168+
169+
158170

159171
class ContextualLogger(StartedCompletedLogger):
160172
""" Add context to logging messages via the context attribute """
@@ -173,8 +185,7 @@ def context(self, value):
173185
self.info("")
174186
self._context = str(value)
175187
if self._context != "":
176-
sep = LOGGER_SEPARATOR_CONTEXTUAL\
177-
*LOGGER_NSEPARATORS_CONTEXTUAL
188+
sep = self.get_separator("#", 3)
178189
mess = sep+" "+self._context+" "+sep
179190
self.info(mess)
180191

hydrodiy/io/script_template_plot.py

+1
Original file line numberDiff line numberDiff line change
@@ -95,6 +95,7 @@
9595
#------------------------------------------------------------
9696
basename = source_file.stem
9797
LOGGER = iutils.get_logger(basename)
98+
LOGGER.log_dict(vars(args), "Command line arguments")
9899

99100
#------------------------------------------------------------
100101
# @Get data

hydrodiy/io/script_template_simple.py

+1
Original file line numberDiff line numberDiff line change
@@ -74,6 +74,7 @@
7474
flog = froot / "logs" / f"{basename}.log"
7575
flog.parent.mkdir(exist_ok=True)
7676
LOGGER = iutils.get_logger(basename, console=False, contextual=True)
77+
LOGGER.log_dict(vars(args), "Command line arguments")
7778

7879
#----------------------------------------------------------------------
7980
# @Get data

hydrodiy/io/tests/test_hyio_iutils.py

+5-2
Original file line numberDiff line numberDiff line change
@@ -124,6 +124,7 @@ def test_get_logger():
124124
logger1.error("error")
125125
logger1.critical("critical")
126126
logger1.warning("warning")
127+
logger1.log_dict({"a": 1, "b": "asdasd"}, "test", "warning")
127128

128129
assert flog1.exists()
129130

@@ -136,6 +137,8 @@ def test_get_logger():
136137
ck = ck & txt[5].strip().endswith("ERROR | error")
137138
ck = ck & txt[6].strip().endswith("CRITICAL | critical")
138139
ck = ck & txt[7].strip().endswith("WARNING | warning")
140+
ck = ck & txt[9].strip().endswith("WARNING | test:")
141+
ck = ck & txt[10].strip().endswith("WARNING | a = 1")
139142
assert ck
140143

141144
# Test logging with different format
@@ -152,8 +155,8 @@ def test_get_logger():
152155

153156
with open(flog2, "r") as fl:
154157
txt = fl.readlines()
155-
expected = ["@@@ Process started @@@", "-"*50, ""]+mess+\
156-
["", "-"*50, "@@@ Process completed @@@"]
158+
expected = ["@@@ Process started @@@", "-"*30, ""]+mess+\
159+
["", "-"*30, "@@@ Process completed @@@"]
157160
assert expected == [t.strip() for t in txt]
158161

159162
# Close log file handler and delete files

0 commit comments

Comments
 (0)