Skip to content

Commit d2bcd43

Browse files
authored
Merge pull request #666 from OpenEnergyPlatform/feature-657-664-improve-logging
Improve logging
2 parents 4eab04d + 1621734 commit d2bcd43

9 files changed

Lines changed: 231 additions & 138 deletions

File tree

CHANGELOG.md

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,8 @@ and the versioning aims to respect [Semantic Versioning](http://semver.org/spec/
1717
[#636](https://github.com/OpenEnergyPlatform/open-MaStR/pull/636)
1818
- Change print statement about data cleansing
1919
[#650](https://github.com/OpenEnergyPlatform/open-MaStR/pull/650)
20+
- Improve logging
21+
[#666](https://github.com/OpenEnergyPlatform/open-MaStR/pull/666)
2022
- Limit number of parallel CI jobs
2123
[#669](https://github.com/OpenEnergyPlatform/open-MaStR/pull/669)
2224
### Removed

docs/advanced.md

Lines changed: 14 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -63,7 +63,7 @@ The project home directory is structured as follows (files and folders below `da
6363
File names are defined here.
6464
* `logging.yml` <br>
6565
Logging configuration. For changing the log level to increase or decrease details of log
66-
messages, edit the level of the handlers.
66+
messages, edit the level of the handlers. See below for details on logging.
6767
* **data**
6868
* `dataversion-<date>` <br>
6969
Contains exported data as csv files from method [`to_csv`][open_mastr.Mastr.to_csv]
@@ -83,6 +83,19 @@ The project home directory is structured as follows (files and folders below `da
8383
For the download via the API, logs are stored in a single file in `/$HOME/<user>/.open-MaStR/logs/open_mastr.log`.
8484
New logging messages are appended. It is recommended to delete the log file from time to time because of its required disk space.
8585

86+
By default, the log level is set to `INFO`. You can increase or decrease the verbosity by either changing `logging.yml` (see above)
87+
or adjusting it manually in your code. E.g. to enable `DEBUG` messages in `open_mastr.log` you can use the following snippet:
88+
89+
```python
90+
91+
import logging
92+
from open_mastr import Mastr
93+
94+
# Increase to DEBUG to show more details in open_mastr.log
95+
# Must be called after importing open_mastr to have the open-MaStR logger imported
96+
logging.getLogger("open-MaStR").setLevel(logging.DEBUG)
97+
```
98+
8699

87100
### Data
88101

open_mastr/mastr.py

Lines changed: 13 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -92,7 +92,10 @@ def __init__(self, engine="sqlite", connect_to_translated_db=False) -> None:
9292
else:
9393
self.engine = create_database_engine(engine, self._sqlite_folder_path)
9494

95-
print(
95+
log.info(
96+
"\n==================================================\n"
97+
"---------> open-MaStR started <---------\n"
98+
"==================================================\n"
9699
f"Data will be written to the following database: {self.engine.url}\n"
97100
"If you run into problems, try to "
98101
"delete the database and update the package by running "
@@ -239,7 +242,7 @@ def download(
239242

240243
download_xml_Mastr(zipped_xml_file_path, date, data, xml_folder_path)
241244

242-
print(
245+
log.info(
243246
"\nWould you like to speed up the creation of your MaStR database?\n"
244247
"Try our new parallelized processing by setting os.environ['USE_RECOMMENDED_NUMBER_OF_PROCESSES'] = True "
245248
"or configure your own number of processes via os.environ['NUMBER_OF_PROCESSES'] = your_number\n"
@@ -259,8 +262,8 @@ def download(
259262
# Set api_processes to None in order to avoid the malfunctioning usage
260263
if api_processes:
261264
api_processes = None
262-
print(
263-
"Warning: The implementation of parallel processes "
265+
log.warning(
266+
"The implementation of parallel processes "
264267
"is currently under construction. Please let "
265268
"the argument api_processes at the default value None."
266269
)
@@ -429,9 +432,11 @@ def translate(self) -> None:
429432
try:
430433
os.remove(new_path)
431434
except Exception as e:
432-
print(f"An error occurred: {e}")
435+
log.error(
436+
f"An error occurred while removing old translated database: {e}"
437+
)
433438

434-
print("Replacing previous version of the translated database...")
439+
log.info("Replacing previous version of the translated database...")
435440

436441
for table in inspector.get_table_names():
437442
rename_table(table, inspector.get_columns(table), self.engine)
@@ -440,9 +445,9 @@ def translate(self) -> None:
440445

441446
try:
442447
os.rename(old_path, new_path)
443-
print(f"Database '{old_path}' changed to '{new_path}'")
448+
log.info(f"Database '{old_path}' changed to '{new_path}'")
444449
except Exception as e:
445-
print(f"An error occurred: {e}")
450+
log.error(f"An error occurred while renaming database: {e}")
446451

447452
self.engine = create_engine(f"sqlite:///{new_path}")
448453
self.is_translated = True

open_mastr/soap_api/metadata/description.py

Lines changed: 8 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,13 @@
11
from io import BytesIO
2+
import logging
23
import re
34
from urllib.request import urlopen
45
from zipfile import ZipFile
56
import xmltodict
67
from collections import OrderedDict
78

9+
log = logging.getLogger(__name__)
10+
811

912
class DataDescription(object):
1013
"""
@@ -150,9 +153,11 @@ def functions_data_documentation(self):
150153
fcn["sequence"]["element"]["@type"].split(":")[1]
151154
]["sequence"]["element"]
152155
else:
153-
print(type(fcn["sequence"]))
154-
print(fcn["sequence"])
155-
raise ValueError
156+
log.error(f"Unexpected sequence type: {type(fcn['sequence'])}")
157+
log.error(f"Sequence content: {fcn['sequence']}")
158+
raise ValueError(
159+
f"Unexpected sequence structure in function metadata"
160+
)
156161

157162
# Add data for inherited columns from base types
158163
if "@base" in fcn:

open_mastr/utils/config/logging.yml

Lines changed: 6 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,8 @@ disable_existing_loggers: False
44
formatters:
55
standard:
66
format: "%(asctime)s [%(levelname)s] %(message)s"
7+
debug:
8+
format: "%(asctime)s [%(levelname)s] %(name)s:%(funcName)s:%(lineno)d - %(message)s"
79

810
handlers:
911
console:
@@ -12,14 +14,13 @@ handlers:
1214
class: "logging.StreamHandler"
1315
stream: "ext://sys.stdout"
1416
file:
15-
class: "logging.FileHandler"
1617
level: "DEBUG"
17-
formatter: "standard"
18+
formatter: "debug"
19+
class: "logging.FileHandler"
1820
mode: "a"
1921

20-
root:
21-
level: "DEBUG"
22-
2322
loggers:
2423
open-MaStR:
24+
level: "INFO"
2525
handlers: ["console", "file"]
26+
propagate: no

open_mastr/utils/helpers.py

Lines changed: 10 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -343,37 +343,32 @@ def print_api_settings(
343343
api_processes,
344344
api_location_types,
345345
):
346-
print(
346+
log.info(
347347
f"Downloading with soap_API.\n\n -- API settings -- \nunits after date: "
348348
f"{date}\nunit download limit per data: "
349349
f"{api_limit}\nparallel_processes: {api_processes}\nchunksize: "
350350
f"{api_chunksize}\ndata_api: {data}"
351351
)
352352
if "permit" in harmonisation_log:
353-
print(
354-
f"data_types: {api_data_types}\033[31m",
353+
log.warning(
354+
f"data_types: {api_data_types} - "
355355
"Attention, 'permit_data' was automatically set in api_data_types, "
356-
"as you defined 'permit' in parameter data_api.",
357-
"\033[m",
356+
"as you defined 'permit' in parameter data_api."
358357
)
359358

360359
else:
361-
print(f"data_types: {api_data_types}")
360+
log.info(f"data_types: {api_data_types}")
362361

363362
if "location" in harmonisation_log:
364-
print(
365-
"location_types:",
366-
"\033[31m",
367-
"Attention, 'location' is in parameter data. location_types are set to",
368-
"\033[m",
369-
f"{api_location_types}"
370-
"\n If you want to change location_types, please remove 'location' "
363+
log.warning(
364+
f"location_types: {api_location_types} - "
365+
"Attention, 'location' is in parameter data. location_types are set accordingly. "
366+
"If you want to change location_types, please remove 'location' "
371367
"from data_api and specify api_location_types."
372-
"\n ------------------ \n",
373368
)
374369

375370
else:
376-
print(
371+
log.info(
377372
f"location_types: {api_location_types}",
378373
"\n ------------------ \n",
379374
)

0 commit comments

Comments
 (0)