Skip to content

Commit a32485b

Browse files
committed
Merge branch 'master' of github.com:csiro-hydroinformatics/hydrodiy
2 parents 9a285d5 + 90a6d7e commit a32485b

File tree

2 files changed

+82
-31
lines changed

2 files changed

+82
-31
lines changed

hydrodiy/io/iutils.py

+61-23
Original file line numberDiff line numberDiff line change
@@ -118,24 +118,48 @@ def script_template(filename, comment,
118118
class StartedCompletedLogger():
119119
""" Add context to logging messages via the context attribute """
120120

121-
def __init__(self, logger):
121+
def __init__(self, logger, \
122+
separator_charac="-", \
123+
separator_length=50, \
124+
dictseparator_charac="+", \
125+
dictseparator_length=30, \
126+
tab_length=4):
122127
errmess = "Expected a logger object"
123128
assert isinstance(logger, logging.Logger), errmess
124129
self._logger = logger
125130

131+
self.separator_charac = separator_charac
132+
self.separator_length = separator_length
133+
134+
self.dictseparator_charac = dictseparator_charac
135+
self.dictseparator_length = dictseparator_length
136+
137+
self.tab_length = tab_length
138+
126139
def get_separator(self, nsep, sep):
127140
return sep*nsep
128141

129-
def error(self, msg, *args, **kwargs):
142+
def add_tab(self, msg, ntab):
143+
if ntab==0:
144+
return msg
145+
146+
tab_space = " "*self.tab_length*ntab
147+
return tab_space+msg
148+
149+
def error(self, msg, ntab=0, *args, **kwargs):
150+
msg = self.add_tab(msg, ntab)
130151
return self._logger.error(msg, *args, **kwargs)
131152

132-
def info(self, msg, *args, **kwargs):
153+
def info(self, msg, ntab=0, *args, **kwargs):
154+
msg = self.add_tab(msg, ntab)
133155
return self._logger.info(msg, *args, **kwargs)
134156

135-
def warning(self, msg, *args, **kwargs):
157+
def warning(self, msg, ntab=0, *args, **kwargs):
158+
msg = self.add_tab(msg, ntab)
136159
return self._logger.warning(msg, *args, **kwargs)
137160

138-
def critical(self, msg, *args, **kwargs):
161+
def critical(self, msg, ntab=0, *args, **kwargs):
162+
msg = self.add_tab(msg, ntab)
139163
return self._logger.critical(msg, *args, **kwargs)
140164

141165
@property
@@ -144,24 +168,28 @@ def handlers(self):
144168

145169
def started(self):
146170
self.info("@@@ Process started @@@")
147-
self.info(self.get_separator("-", 30))
171+
self.info(self.get_separator(self.separator_charac, \
172+
self.separator_length))
148173
self.info("")
149174

150175
def completed(self):
151176
self.info("")
152-
self.info(self.get_separator("-", 30))
177+
self.info(self.get_separator(self.separator_charac, \
178+
self.separator_length))
153179
self.info("@@@ Process completed @@@")
154180

155181
def log_dict(self, tolog, name="", level="info"):
156182
""" Add log entry for dictionnary (e.g. created from argparse using vars)"""
157183
assert level in ["info", "warning", "critical", "error"]
158184
logfun = getattr(self, level)
159-
sep = self.get_separator("+", 20)
185+
sep = self.get_separator(self.dictseparator_charac, \
186+
self.dictseparator_length)
160187
logfun(sep)
161188
if name!="":
162189
logfun(f"{name}:")
163190
for k, v in tolog.items():
164-
logfun(" "*4+f"{k} = {v}")
191+
msg = self.add_tab(f"{k} = {v}", 1)
192+
logfun(msg)
165193

166194
logfun(sep)
167195
logfun("")
@@ -171,9 +199,17 @@ def log_dict(self, tolog, name="", level="info"):
171199
class ContextualLogger(StartedCompletedLogger):
172200
""" Add context to logging messages via the context attribute """
173201

174-
def __init__(self, logger):
202+
def __init__(self, logger, \
203+
context_hasheader=False, \
204+
context_charac="#", \
205+
context_length=3, \
206+
*args, **kwargs):
175207
self._context = ""
176-
super(ContextualLogger, self).__init__(logger)
208+
self.context_hasheader = context_hasheader
209+
self.context_charac = context_charac
210+
self.context_length = context_length
211+
212+
super(ContextualLogger, self).__init__(logger, *args, **kwargs)
177213

178214
@property
179215
def context(self):
@@ -184,34 +220,36 @@ def context(self, value):
184220
self._context = ""
185221
self.info("")
186222
self._context = str(value)
187-
if self._context != "":
188-
sep = self.get_separator("#", 3)
223+
if self._context != "" and self.context_hasheader:
224+
sep = self.get_separator(self.context_charac, \
225+
self.context_length)
189226
mess = sep+" "+self._context+" "+sep
190227
self.info(mess)
191228

192229
def completed(self):
193230
self.context = ""
194231
super(ContextualLogger, self).completed()
195232

196-
def get_message(self, msg):
233+
def get_message(self, msg, ntab):
197234
if self.context != "":
198-
return "{{ {0} }} {1}".format(self.context, msg)
235+
tab = " "*self.tab_length*ntab if ntab>0 else ""
236+
return "{{ {0} }} {1}{2}".format(self.context, tab, msg)
199237
return msg
200238

201-
def error(self, msg, *args, **kwargs):
202-
msg = self.get_message(msg)
239+
def error(self, msg, ntab=0, *args, **kwargs):
240+
msg = self.get_message(msg, ntab)
203241
return self._logger.error(msg, *args, **kwargs)
204242

205-
def info(self, msg, *args, **kwargs):
206-
msg = self.get_message(msg)
243+
def info(self, msg, ntab=0, *args, **kwargs):
244+
msg = self.get_message(msg, ntab)
207245
return self._logger.info(msg, *args, **kwargs)
208246

209-
def warning(self, msg, *args, **kwargs):
210-
msg = self.get_message(msg)
247+
def warning(self, msg, ntab=0, *args, **kwargs):
248+
msg = self.get_message(msg, ntab)
211249
return self._logger.warning(msg, *args, **kwargs)
212250

213-
def critical(self, msg, *args, **kwargs):
214-
msg = self.get_message(msg)
251+
def critical(self, msg, ntab=0, *args, **kwargs):
252+
msg = self.get_message(msg, ntab)
215253
return self._logger.critical(msg, *args, **kwargs)
216254

217255

hydrodiy/io/tests/test_hyio_iutils.py

+21-8
Original file line numberDiff line numberDiff line change
@@ -121,6 +121,8 @@ def test_get_logger():
121121
mess = ["flog1 A", "flog1 B"]
122122
logger1.info(mess[0])
123123
logger1.info(mess[1])
124+
logger1.info("test tab1", 1)
125+
logger1.info("test tab2", 2)
124126
logger1.error("error")
125127
logger1.critical("critical")
126128
logger1.warning("warning")
@@ -134,11 +136,14 @@ def test_get_logger():
134136
ck = txt[0].strip().endswith("INFO | @@@ Process started @@@")
135137
ck = ck & txt[3].strip().endswith("INFO | "+mess[0])
136138
ck = ck & txt[4].strip().endswith("INFO | "+mess[1])
137-
ck = ck & txt[5].strip().endswith("ERROR | error")
138-
ck = ck & txt[6].strip().endswith("CRITICAL | critical")
139-
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")
139+
ck = ck & txt[5].strip().endswith("INFO | test tab1")
140+
ck = ck & txt[6].strip().endswith("INFO | test tab2")
141+
ck = ck & txt[7].strip().endswith("ERROR | error")
142+
ck = ck & txt[8].strip().endswith("CRITICAL | critical")
143+
ck = ck & txt[9].strip().endswith("WARNING | warning")
144+
ck = ck & txt[11].strip().endswith("WARNING | test:")
145+
ck = ck & txt[12].strip().endswith("WARNING | a = 1")
146+
142147
assert ck
143148

144149
# Test logging with different format
@@ -155,8 +160,13 @@ def test_get_logger():
155160

156161
with open(flog2, "r") as fl:
157162
txt = fl.readlines()
158-
expected = ["@@@ Process started @@@", "-"*30, ""]+mess+\
159-
["", "-"*30, "@@@ Process completed @@@"]
163+
expected = ["@@@ Process started @@@", \
164+
logger2.separator_charac*logger2.separator_length, \
165+
""]+\
166+
mess+\
167+
["", \
168+
logger2.separator_charac*logger2.separator_length, \
169+
"@@@ Process completed @@@"]
160170
assert expected == [t.strip() for t in txt]
161171

162172
# Close log file handler and delete files
@@ -174,6 +184,7 @@ def test_get_logger_contextual():
174184
# Test logging
175185
logger = iutils.get_logger("bidule", flog=flog,\
176186
contextual=True)
187+
logger.context_hasheader = True
177188

178189
mess = ["flog1 A", "flog1 B"]
179190
logger.context = "context1"
@@ -184,6 +195,7 @@ def test_get_logger_contextual():
184195
logger.error("error")
185196
logger.critical("critical")
186197
logger.warning("warning")
198+
logger.info("test tab3", 3)
187199

188200
logger.completed()
189201

@@ -198,7 +210,8 @@ def test_get_logger_contextual():
198210
ck &= bool(re.search("ERROR . \\{ context2 \\}", txt[9]))
199211
ck &= bool(re.search("CRITICAL . \\{ context2 \\}", txt[10]))
200212
ck &= bool(re.search("WARNING . \\{ context2 \\}", txt[11]))
201-
ck &= bool(re.search("@@@ Process completed @@@", txt[15]))
213+
ck &= bool(re.search("INFO . \\{ context2 \\} test tab3", txt[12]))
214+
ck &= bool(re.search("@@@ Process completed @@@", txt[16]))
202215
assert ck
203216

204217
logger.handlers[1].close()

0 commit comments

Comments
 (0)