Files
macm1new/logger.py

64 lines
1.7 KiB
Python
Raw Normal View History

2025-01-08 20:16:27 +03:00
import logging
import os
from datetime import datetime
# Configure logging
log_dir = "logs"
if not os.path.exists(log_dir):
os.makedirs(log_dir)
logging.basicConfig(
filename=os.path.join(log_dir, f"{datetime.now().strftime('%Y-%m-%d')}.log"),
level=logging.DEBUG,
format="%(asctime)s - %(levelname)s - %(message)s",
encoding="utf-8",
2025-01-08 20:16:27 +03:00
)
2025-01-09 18:53:34 +08:00
# 创建控制台处理器
console_handler = logging.StreamHandler()
console_handler.setLevel(logging.INFO)
console_handler.setFormatter(logging.Formatter("%(message)s"))
# 将控制台处理器添加到日志记录器
logging.getLogger().addHandler(console_handler)
# 打印日志目录所在路径
logging.info(f"Logger initialized, log directory: {os.path.abspath(log_dir)}")
2025-01-08 20:16:27 +03:00
def main_task():
2025-01-08 20:27:59 +03:00
"""
Main task execution function. Simulates a workflow and handles errors.
"""
2025-01-08 20:16:27 +03:00
try:
logging.info("Starting the main task...")
2025-01-08 20:27:59 +03:00
# Simulated task and error condition
if some_condition():
2025-01-08 20:16:27 +03:00
raise ValueError("Simulated error occurred.")
2025-01-08 20:27:59 +03:00
2025-01-08 20:16:27 +03:00
logging.info("Main task completed successfully.")
2025-01-08 20:27:59 +03:00
2025-01-08 20:16:27 +03:00
except ValueError as ve:
2025-01-08 20:27:59 +03:00
logging.error(f"ValueError occurred: {ve}", exc_info=True)
2025-01-08 20:16:27 +03:00
except Exception as e:
2025-01-08 20:27:59 +03:00
logging.error(f"Unexpected error occurred: {e}", exc_info=True)
2025-01-08 20:16:27 +03:00
finally:
logging.info("Task execution finished.")
2025-01-08 20:16:27 +03:00
def some_condition():
2025-01-08 20:27:59 +03:00
"""
Simulates an error condition. Returns True to trigger an error.
Replace this logic with actual task conditions.
"""
2025-01-08 20:16:27 +03:00
return True
2025-01-08 20:16:27 +03:00
if __name__ == "__main__":
2025-01-08 20:27:59 +03:00
# Application workflow
2025-01-08 20:16:27 +03:00
logging.info("Application started.")
main_task()
logging.info("Application exited.")