logs.py 1.2 KB

1234567891011121314151617181920212223242526272829303132333435
  1. import logging
  2. import logging.handlers
  3. import sys
  4. class Logger:
  5. def __init__(self, logger):
  6. self.logger = logger
  7. def write(self, message, level=logging.INFO):
  8. message = message.rstrip()
  9. if message != '':
  10. self.logger.log(level, message)
  11. def initLogs(logFile, logLevel=logging.INFO, debug=False):
  12. # Configure logging to log to a file, making a new file at midnight and keeping the last 3 day's data
  13. # Give the logger a unique name (good practice)
  14. logger = logging.getLogger(__name__)
  15. # Set the log level to LOG_LEVEL
  16. logger.setLevel(logLevel)
  17. # Make a handler that writes to a file, making a new file at midnight and keeping 3 backups
  18. handler = logging.handlers.TimedRotatingFileHandler(logFile, when="midnight", backupCount=3)
  19. # Format each log message like this
  20. formatter = logging.Formatter('%(asctime)s %(levelname)-8s %(message)s')
  21. # Attach the formatter to the handler
  22. handler.setFormatter(formatter)
  23. # Attach the handler to the logger
  24. logger.addHandler(handler)
  25. if not debug:
  26. lgr = Logger(logger)
  27. # sys.stdout = MyLogger(logger, logging.INFO)
  28. sys.stdout = lgr
  29. # Replace stderr with logging to file at ERROR level
  30. sys.stderr = lgr