logger.py 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. import logging
  2. import os
  3. from datetime import datetime
  4. # Configure logging
  5. log_dir = "logs"
  6. if not os.path.exists(log_dir):
  7. os.makedirs(log_dir)
  8. logging.basicConfig(
  9. filename=os.path.join(log_dir, f"{datetime.now().strftime('%Y-%m-%d')}.log"),
  10. level=logging.DEBUG,
  11. format="%(asctime)s - %(levelname)s - %(message)s",
  12. encoding="utf-8",
  13. )
  14. # 创建控制台处理器
  15. console_handler = logging.StreamHandler()
  16. console_handler.setLevel(logging.INFO)
  17. console_handler.setFormatter(logging.Formatter("%(message)s"))
  18. # 将控制台处理器添加到日志记录器
  19. logging.getLogger().addHandler(console_handler)
  20. # 打印日志目录所在路径
  21. logging.info(f"Logger initialized, log directory: {os.path.abspath(log_dir)}")
  22. def main_task():
  23. """
  24. Main task execution function. Simulates a workflow and handles errors.
  25. """
  26. try:
  27. logging.info("Starting the main task...")
  28. # Simulated task and error condition
  29. if some_condition():
  30. raise ValueError("Simulated error occurred.")
  31. logging.info("Main task completed successfully.")
  32. except ValueError as ve:
  33. logging.error(f"ValueError occurred: {ve}", exc_info=True)
  34. except Exception as e:
  35. logging.error(f"Unexpected error occurred: {e}", exc_info=True)
  36. finally:
  37. logging.info("Task execution finished.")
  38. def some_condition():
  39. """
  40. Simulates an error condition. Returns True to trigger an error.
  41. Replace this logic with actual task conditions.
  42. """
  43. return True
  44. if __name__ == "__main__":
  45. # Application workflow
  46. logging.info("Application started.")
  47. main_task()
  48. logging.info("Application exited.")