-
Notifications
You must be signed in to change notification settings - Fork 22
/
Copy pathutil_logger.py
83 lines (63 loc) · 2.75 KB
/
util_logger.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
"""
Purpose: Set up logging once and reuse it.
Author: Denise Case
This file automatically records your work so you don't have to.
Analysts and data scientists will work hard once, to be lazy later.
You should be able to reuse this code without modification.
You're also welcome to use it as a template for your own logging.
"""
import logging
import pathlib
import platform
import sys
import os
import datetime
def get_source_directory_path(current_file):
"""Returns the absolute path to this source directory."""
dir = os.path.dirname(os.path.abspath(current_file))
return dir
def setup_logger(current_file):
"""Setup a logger to automatically log useful information.
@param current_file: the name of the file requesting a logger.
@returns: the logger object and the name of the logfile.
"""
logs_dir = pathlib.Path("logs")
logs_dir.mkdir(exist_ok=True)
module_name = pathlib.Path(current_file).stem
log_file_name = logs_dir.joinpath(module_name + ".log")
logger = logging.getLogger(module_name)
logger.setLevel(logging.DEBUG) # Set the root logger level.
# Create file handler which logs even debug messages.
file_handler = logging.FileHandler(log_file_name, "w")
file_handler.setLevel(logging.DEBUG)
# Create console handler with a higher log level.
console_handler = logging.StreamHandler()
console_handler.setLevel(logging.INFO)
# Create formatter and add it to the handlers.
formatter = logging.Formatter("%(asctime)s.%(name)s.%(levelname)s %(message)s")
file_handler.setFormatter(formatter)
console_handler.setFormatter(formatter)
# Add the handlers to the logger.
logger.addHandler(file_handler)
logger.addHandler(console_handler)
divider_string = "============================================================="
python_version_string = platform.python_version()
today = datetime.date.today()
logger.info(divider_string)
logger.info(f"Today is {today} at {datetime.datetime.now().strftime('%I:%M %p')}")
logger.info(
f"This file is running on: {os.name} {platform.system()} {platform.release()}"
)
logger.info(f"The Python version is: {python_version_string}")
logger.info(f"The active environment path is: {sys.prefix}")
logger.info(f"The current working directory is: {os.getcwd()}")
logger.info(divider_string)
return logger, log_file_name
if __name__ == "__main__":
logger, logname = setup_logger(__file__)
logger.info("Starting util_logger.py")
logger.info(f"Information is logged to: logs/{logname}")
logger.info("Ending util_logger.py")
# Use built-in open() function to read log file and print it to the terminal
with open(logname, "r") as file_wrapper:
print(file_wrapper.read())