-
Notifications
You must be signed in to change notification settings - Fork 37
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Add formatting to log and update
get_logger
function.
- Loading branch information
Showing
1 changed file
with
47 additions
and
7 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,15 +1,55 @@ | ||
import logging | ||
import os | ||
import sys | ||
|
||
|
||
def get_logger(name: str = __name__): | ||
def get_logger(name: str = None) -> logging.Logger: | ||
""" | ||
Creates and returns a logger with the specified name. | ||
Ensures a universal logger configuration across the codebase with the format: | ||
"levelname - asctime - filename:lineno - message" | ||
Args: | ||
name (str): Name of the logger. Defaults to None, which gets the root logger. | ||
Returns: | ||
logging.Logger: Configured logger instance. | ||
""" | ||
# Create or retrieve the logger | ||
logger = logging.getLogger(name) | ||
|
||
level = os.getenv("RH_LOG_LEVEL") | ||
if level: | ||
try: | ||
logger.setLevel(getattr(logging, level.upper())) | ||
except AttributeError as e: | ||
raise e | ||
level = os.getenv("RH_LOG_LEVEL") or "INFO" | ||
try: | ||
level = getattr(logging, level.upper()) | ||
except AttributeError as e: | ||
raise e | ||
|
||
# Check if the logger has already been configured to prevent duplicate handlers | ||
if not logger.handlers: | ||
|
||
# Set the level for the new logger | ||
logger.setLevel(level) | ||
|
||
# Create a console handler that outputs to stdout | ||
console_handler = logging.StreamHandler(stream=sys.stdout) | ||
|
||
# Set the level for the handler to capture all log levels | ||
console_handler.setLevel(level) | ||
|
||
# Define the log format | ||
formatter = logging.Formatter( | ||
"%(levelname)s | %(asctime)s | %(filename)s:%(lineno)d | %(message)s", | ||
datefmt="%Y-%m-%d %H:%M:%S", | ||
) | ||
|
||
# Apply the formatter to the handler | ||
console_handler.setFormatter(formatter) | ||
|
||
# Add the handler to the logger | ||
logger.addHandler(console_handler) | ||
|
||
# Prevent log messages from propagating to the root logger | ||
logger.propagate = False | ||
|
||
return logger |