Skip to content

Commit

Permalink
Added exception logging with stack trace (#93)
Browse files Browse the repository at this point in the history
- Added logException method to capture exceptions, including their
`stack` traces and optional messages.
- Exceptions are logged to both console and file using existing
`logToStdOut` and `logToFile` methods.
  • Loading branch information
Abhinavcode13 authored May 26, 2024
1 parent acfbd7f commit 70fbbe8
Showing 1 changed file with 13 additions and 0 deletions.
13 changes: 13 additions & 0 deletions src/polyphy/utils/logger.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,8 @@
from datetime import datetime
import logging
import time
import traceback
from logging.handlers import RotatingFileHandler


class Logger:
Expand Down Expand Up @@ -45,6 +47,7 @@ def logToStdOut(level, *msg) -> None:
# FILE:
file_logger = logging.getLogger("file")
file_handler = logging.FileHandler("polyphy.log")
file_handler = RotatingFileHandler("polyphy.log", maxBytes=1024*1024, backupCount=3)
file_formatter = logging.Formatter("%(asctime)s - %(levelname)s - %(message)s")
file_handler.setFormatter(file_formatter)
file_logger.addHandler(file_handler)
Expand All @@ -61,3 +64,13 @@ def logToFile(level, *msg) -> None:
Logger.file_logger.setLevel(Logger.log_level.get(level, logging.INFO))
res = " ".join(map(str, msg))
Logger.file_log_functions.get(level, Logger.file_logger.info)(res)

@staticmethod
def logException(level, exception, *msg) -> None:
log_msg = " ".join(map(str, msg))
log_msg += f"\nException: {repr(exception)}"
log_msg += f"\nStack Trace: {traceback.format_exc()}"
# Log to console
Logger.logToStdOut(level, log_msg)
# Log to file
Logger.logToFile(level, log_msg)

0 comments on commit 70fbbe8

Please sign in to comment.