Skip to content

Commit

Permalink
Add formatting to log and update get_logger function.
Browse files Browse the repository at this point in the history
  • Loading branch information
rohinb2 committed Aug 27, 2024
1 parent dd2aab3 commit 4205ccb
Showing 1 changed file with 47 additions and 7 deletions.
54 changes: 47 additions & 7 deletions runhouse/logger.py
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

0 comments on commit 4205ccb

Please sign in to comment.