[docs]defcleanup_old_logs(log_directory:str,max_logs:int=10)->None:"""Keep only the 10 most recent log files in the directory."""path:Path=Path(log_directory)ifnotpath.is_dir():return# Not a directory or doesn't exist, nothing to clean# List all log files, sorted by modification time, oldest firstlogs:list[Path]=sorted(path.glob("app_*.log"),key=os.path.getmtime)# If there are more than max_logs, remove the oldest onesiflen(logs)>max_logs:forlog_fileinlogs[:-max_logs]:# Keep the last max_logs fileslog_file.unlink()# Delete the file
[docs]defsetup_logger()->None:"""Setup the logger configuration for the application"""log_directory:str="logs"log_file_path:str=f"{log_directory}/app_{{time}}.log"# Remove default logger configurationlogger.remove()# Add a handler for console logging with rich formattinglogger.add(sys.stderr,format=rich_formatter,level="INFO",colorize=True)# type: ignore# Add a handler for file logging with rotationlogger.add(log_file_path,rotation="1 week",level="DEBUG")# Cleanup old logscleanup_old_logs(log_directory)"""Setup the logger configuration for the application"""# Remove default logger configurationlogger.remove()# Add a handler for console logging with rich formattinglogger.add(sys.stderr,format=rich_formatter,level="INFO",colorize=True)# type: ignore# Add a handler for file logginglogger.add("logs/app_{time}.log",rotation="1 week",level="DEBUG")# Cleanup old logscleanup_old_logs(log_directory)
setup_logger()# Example log messages:# @logger.catch# def divide(a, b):# a / b# divide(1, 0)# logger.info("This is an info message")# logger.debug("This is a debug message")# logger.warning("This is a warning message")# logger.error("This is an error message")# logger.critical("This is a critical message")