Advertisement
DrAungWinHtut

myconnection.py

Jan 5th, 2024
815
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.33 KB | None | 0 0
  1. # mysqldb.py need this file
  2. import logging
  3. import time
  4. import mysql.connector
  5. # pip install mysql-connector-python
  6.  
  7. # Set up logger
  8. logger = logging.getLogger(__name__)
  9. logger.setLevel(logging.INFO)
  10. formatter = logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s")
  11.  
  12. # Log to console
  13. handler = logging.StreamHandler()
  14. handler.setFormatter(formatter)
  15. logger.addHandler(handler)
  16.  
  17. # Also log to a file
  18. file_handler = logging.FileHandler("cpy-errors.log")
  19. file_handler.setFormatter(formatter)
  20. logger.addHandler(file_handler)
  21.  
  22. def connect_to_mysql(config, attempts=3, delay=2):
  23.     attempt = 1
  24.     # Implement a reconnection routine
  25.     while attempt < attempts + 1:
  26.         try:
  27.             return mysql.connector.connect(**config)
  28.         except (mysql.connector.Error, IOError) as err:
  29.             if (attempts is attempt):
  30.                 # Attempts to reconnect failed; returning None
  31.                 logger.info("Failed to connect, exiting without a connection: %s", err)
  32.                 return None
  33.             logger.info(
  34.                 "Connection failed: %s. Retrying (%d/%d)...",
  35.                 err,
  36.                 attempt,
  37.                 attempts-1,
  38.             )
  39.             # progressive reconnect delay
  40.             time.sleep(delay ** attempt)
  41.             attempt += 1
  42.     return None
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement