This repository has been archived by the owner on Dec 2, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 2
/
app_logger.py
73 lines (60 loc) · 2.19 KB
/
app_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
# Description: Setup for logging used throughout the application
import config
import logging
import os
# If it does not exist already, create a directory where we will store disk
# logs generated by the logging module
log_dir = os.path.join(os.path.dirname(os.path.abspath(__file__)), "logs")
if not os.path.exists(log_dir):
os.mkdir(log_dir)
log_file_name = "NBC_Primary.log"
log_file_path = os.path.join(log_dir, log_file_name)
log_format = "%(asctime)s [%(levelname)s] [%(name)s] [%(filename)s/%(funcName)s(%(lineno)d)] :: %(message)s"
# Fetch logger level defined (as string) in our config file
level_text = config.LOG_LEVEL.upper()
# Define logging levels that correspond with level_text
logging_levels = {
"CRITICAL": logging.CRITICAL,
"ERROR": logging.ERROR,
"WARNING": logging.WARNING,
"INFO": logging.INFO,
"DEBUG": logging.DEBUG,
}
# Convert level_text string to a level interpreted by the logging module,
# if the string does not match any defined in logging_levels then use
# INFO as a fallback
log_level = logging_levels.get(level_text)
if log_level is None:
level_text = "INFO"
log_level = logging.INFO
def get_file_handler():
# RotatingFileHandler was producing WinError 32 (PermissionError)
# It seems that my intended use-case is not applicable to multiple
# Rotating Handlers (at least on Windows)
# TODO: Will need to do more testing on Linux-based system
file_handler = logging.FileHandler(
filename=log_file_path,
encoding="utf-8",
mode="a", # Append new logs to existing file
)
# Individual handlers can be set to listen only to specific level or above
# Useful if ever plan to add a StreamHandler for example
file_handler.setLevel(logging.DEBUG)
file_handler.setFormatter(logging.Formatter(log_format))
return file_handler
def get_logger(name):
logger = logging.getLogger(name)
logger.setLevel(log_level)
logger.addHandler(get_file_handler())
return logger
logger = get_logger(__name__)
logger.info(
f"Sucessfully configured {__name__} with the "
"following parameters:"
)
logger.info(
f"> Logging Level: {level_text}"
)
logger.info(
f"> File Path: {log_file_path}"
)