Skip to content

Commit 337b454

Browse files
jleratJulien Lerat
and
Julien Lerat
authored
Feature/loggerclean3 (#16)
* doc: removed bitbucket pipeline [ci-skip] * chore: moved pipeline and created reduced conda env spec * fix: cleaned customised logger classes * doc: added tags to sections of script templates --------- Co-authored-by: Julien Lerat <[email protected]>
1 parent 3d091f5 commit 337b454

File tree

4 files changed

+76
-34
lines changed

4 files changed

+76
-34
lines changed

hydrodiy/io/iutils.py

+50-21
Original file line numberDiff line numberDiff line change
@@ -121,11 +121,29 @@ def script_template(filename, comment,
121121
os.chmod(filename, st.st_mode | stat.S_IEXEC)
122122

123123

124-
class StartedCompletedLogger(logging.Logger):
124+
class StartedCompletedLogger():
125125
""" Add context to logging messages via the context attribute """
126126

127-
def __init__(self, *args, **kwargs):
128-
super(StartedCompletedLogger, self).__init__(*args, **kwargs)
127+
def __init__(self, logger):
128+
errmess = "Expected a logger object"
129+
assert isinstance(logger, logging.Logger), errmess
130+
self._logger = logger
131+
132+
def error(self, msg, *args, **kwargs):
133+
return self._logger.error(msg, *args, **kwargs)
134+
135+
def info(self, msg, *args, **kwargs):
136+
return self._logger.info(msg, *args, **kwargs)
137+
138+
def warning(self, msg, *args, **kwargs):
139+
return self._logger.warning(msg, *args, **kwargs)
140+
141+
def critical(self, msg, *args, **kwargs):
142+
return self._logger.critical(msg, *args, **kwargs)
143+
144+
@property
145+
def handlers(self):
146+
return self._logger.handlers
129147

130148
def started(self):
131149
self.info("@@@ Process started @@@")
@@ -138,37 +156,52 @@ def completed(self):
138156
self.info("@@@ Process completed @@@")
139157

140158

141-
class HydrodiyContextualLogger(StartedCompletedLogger):
159+
class ContextualLogger(StartedCompletedLogger):
142160
""" Add context to logging messages via the context attribute """
143161

144-
def __init__(self, *args, **kwargs):
162+
def __init__(self, logger):
145163
self._context = ""
146-
super(HydrodiyContextualLogger, self).__init__(*args, **kwargs)
164+
super(ContextualLogger, self).__init__(logger)
147165

148166
@property
149167
def context(self):
150168
return self._context
151169

152170
@context.setter
153171
def context(self, value):
172+
self._context = ""
173+
self.info("")
154174
self._context = str(value)
155175
if self._context != "":
156-
self.info("")
157176
sep = LOGGER_SEPARATOR_CONTEXTUAL\
158177
*LOGGER_NSEPARATORS_CONTEXTUAL
159178
mess = sep+" "+self._context+" "+sep
160179
self.info(mess)
161180

162181
def completed(self):
163182
self.context = ""
164-
super(HydrodiyContextualLogger, self).completed()
183+
super(ContextualLogger, self).completed()
165184

166-
def _log(self, level, msg, args, exc_info=None, extra=None):
185+
def get_message(self, msg):
167186
if self.context != "":
168-
msg = "{{ {0} }} {1}".format(self.context, msg)
187+
return "{{ {0} }} {1}".format(self.context, msg)
188+
return msg
189+
190+
def error(self, msg, *args, **kwargs):
191+
msg = self.get_message(msg)
192+
return self._logger.error(msg, *args, **kwargs)
169193

170-
super(HydrodiyContextualLogger, self)._log(\
171-
level, msg, args, exc_info, extra)
194+
def info(self, msg, *args, **kwargs):
195+
msg = self.get_message(msg)
196+
return self._logger.info(msg, *args, **kwargs)
197+
198+
def warning(self, msg, *args, **kwargs):
199+
msg = self.get_message(msg)
200+
return self._logger.warning(msg, *args, **kwargs)
201+
202+
def critical(self, msg, *args, **kwargs):
203+
msg = self.get_message(msg)
204+
return self._logger.critical(msg, *args, **kwargs)
172205

173206

174207
def get_logger(name, level="INFO", \
@@ -271,17 +304,13 @@ def catcherr(exc_type, exc_value, exc_traceback):
271304
# Close all handlers
272305
[h.close() for h in logger.handlers]
273306

274-
# Create the contextual logger
275-
if contextual:
276-
# A bit dangerous, but will do for now
277-
logger.__class__ = HydrodiyContextualLogger
278-
logger.context = ""
279-
else:
280-
logger.__class__ = StartedCompletedLogger
307+
# Create the extended logger
308+
elogger = ContextualLogger(logger) if contextual else \
309+
StartedCompletedLogger(logger)
281310

282311
if start_message:
283-
logger.started()
312+
elogger.started()
284313

285-
return logger
314+
return elogger
286315

287316

hydrodiy/io/script_template_plot.py

+5-5
Original file line numberDiff line numberDiff line change
@@ -41,7 +41,7 @@
4141
#importlib.reload(utils)
4242

4343
#----------------------------------------------------------------------
44-
# Config
44+
# @Config
4545
#----------------------------------------------------------------------
4646

4747
parser = argparse.ArgumentParser(\
@@ -81,7 +81,7 @@
8181
#proj = pyproj.Proj("+init=EPSG:{0}".format(args.projection))
8282
#
8383
#----------------------------------------------------------------------
84-
# Folders
84+
# @Folders
8585
#----------------------------------------------------------------------
8686
source_file = Path(__file__).resolve()
8787

@@ -91,13 +91,13 @@
9191
fimg = [FIMG]
9292

9393
#------------------------------------------------------------
94-
# Logging
94+
# @Logging
9595
#------------------------------------------------------------
9696
basename = source_file.stem
9797
LOGGER = iutils.get_logger(basename)
9898

9999
#------------------------------------------------------------
100-
# Get data
100+
# @Get data
101101
#------------------------------------------------------------
102102
#fd = "%s/data.csv" % FDATA
103103
#data, comment = csv.read_csv(fd)
@@ -108,7 +108,7 @@
108108
LOGGER.info(mess)
109109

110110
#------------------------------------------------------------
111-
# Plot
111+
# @Plot
112112
#------------------------------------------------------------
113113

114114
# To use multipage pdf

hydrodiy/io/script_template_simple.py

+5-5
Original file line numberDiff line numberDiff line change
@@ -24,7 +24,7 @@
2424
#spec.loader.exec_module(foo)
2525

2626
#----------------------------------------------------------------------
27-
# Config
27+
# @Config
2828
#----------------------------------------------------------------------
2929
parser = argparse.ArgumentParser(\
3030
description="[DESCRIPTION]", \
@@ -59,7 +59,7 @@
5959
sitepattern = args.sitepattern
6060

6161
#----------------------------------------------------------------------
62-
# Folders
62+
# @Folders
6363
#----------------------------------------------------------------------
6464
source_file = Path(__file__).resolve()
6565
froot = [FROOT]
@@ -68,15 +68,15 @@
6868
fimg = [FIMG]
6969

7070
#----------------------------------------------------------------------
71-
# Logging
71+
# @Logging
7272
#----------------------------------------------------------------------
7373
basename = source_file.stem
7474
flog = froot / "logs" / f"{basename}.log"
7575
flog.parent.mkdir(exist_ok=True)
7676
LOGGER = iutils.get_logger(basename, console=False, contextual=True)
7777

7878
#----------------------------------------------------------------------
79-
# Get data
79+
# @Get data
8080
#----------------------------------------------------------------------
8181
fs = fdata / "sites.csv"
8282
allsites, _ = csv.read_csv(fs, index_col="siteid")
@@ -92,7 +92,7 @@
9292
sites = allsites.iloc[idx, :]
9393

9494
#----------------------------------------------------------------------
95-
# Process
95+
# @Process
9696
#----------------------------------------------------------------------
9797
nsites = len(sites)
9898
for isite, (siteid, sinfo) in enumerate(sites.iterrows()):

hydrodiy/io/tests/test_hyio_iutils.py

+16-3
Original file line numberDiff line numberDiff line change
@@ -121,6 +121,9 @@ def test_get_logger():
121121
mess = ["flog1 A", "flog1 B"]
122122
logger1.info(mess[0])
123123
logger1.info(mess[1])
124+
logger1.error("error")
125+
logger1.critical("critical")
126+
logger1.warning("warning")
124127

125128
assert flog1.exists()
126129

@@ -130,6 +133,9 @@ def test_get_logger():
130133
ck = txt[0].strip().endswith("INFO | @@@ Process started @@@")
131134
ck = ck & txt[3].strip().endswith("INFO | "+mess[0])
132135
ck = ck & txt[4].strip().endswith("INFO | "+mess[1])
136+
ck = ck & txt[5].strip().endswith("ERROR | error")
137+
ck = ck & txt[6].strip().endswith("CRITICAL | critical")
138+
ck = ck & txt[7].strip().endswith("WARNING | warning")
133139
assert ck
134140

135141
# Test logging with different format
@@ -172,6 +178,10 @@ def test_get_logger_contextual():
172178

173179
logger.context = "context2"
174180
logger.info(mess[1])
181+
logger.error("error")
182+
logger.critical("critical")
183+
logger.warning("warning")
184+
175185
logger.completed()
176186

177187
assert flog.exists()
@@ -180,9 +190,12 @@ def test_get_logger_contextual():
180190
txt = fl.readlines()
181191

182192
ck = bool(re.search("@@@ Process started @@@", txt[0]))
183-
ck &= bool(re.search("\\{ context1 \\}", txt[5]))
184-
ck &= bool(re.search("\\{ context2 \\}", txt[8]))
185-
ck &= bool(re.search("@@@ Process completed @@@", txt[11]))
193+
ck &= bool(re.search("\\{ context1 \\}", txt[4]))
194+
ck &= bool(re.search("\\{ context2 \\}", txt[7]))
195+
ck &= bool(re.search("ERROR . \\{ context2 \\}", txt[9]))
196+
ck &= bool(re.search("CRITICAL . \\{ context2 \\}", txt[10]))
197+
ck &= bool(re.search("WARNING . \\{ context2 \\}", txt[11]))
198+
ck &= bool(re.search("@@@ Process completed @@@", txt[15]))
186199
assert ck
187200

188201
logger.handlers[1].close()

0 commit comments

Comments
 (0)