logger.py 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  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. def main_task():
  21. """
  22. Main task execution function. Simulates a workflow and handles errors.
  23. """
  24. try:
  25. logging.info("Starting the main task...")
  26. # Simulated task and error condition
  27. if some_condition():
  28. raise ValueError("Simulated error occurred.")
  29. logging.info("Main task completed successfully.")
  30. except ValueError as ve:
  31. logging.error(f"ValueError occurred: {ve}", exc_info=True)
  32. except Exception as e:
  33. logging.error(f"Unexpected error occurred: {e}", exc_info=True)
  34. finally:
  35. logging.info("Task execution finished.")
  36. def some_condition():
  37. """
  38. Simulates an error condition. Returns True to trigger an error.
  39. Replace this logic with actual task conditions.
  40. """
  41. return True
  42. if __name__ == "__main__":
  43. # Application workflow
  44. logging.info("Application started.")
  45. main_task()
  46. logging.info("Application exited.")