logger.py 1.3 KB

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