You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

87 lines
2.3 KiB

10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
  1. #!/usr/bin/env python2
  2. # -*- coding: utf-8 -*-
  3. """Youtubedlg module responsible for handling the log stuff. """
  4. from __future__ import unicode_literals
  5. import os.path
  6. from time import strftime
  7. from .utils import check_path
  8. class LogManager(object):
  9. """Simple log manager for youtube-dl.
  10. This class is mainly used to log the youtube-dl STDERR.
  11. Attributes:
  12. LOG_FILENAME (string): Filename of the log file.
  13. TIME_TEMPLATE (string): Custom template to log the time.
  14. MAX_LOGSIZE (int): Maximum size(Bytes) of the log file.
  15. Args:
  16. config_path (string): Absolute path where LogManager should
  17. store the log file.
  18. add_time (boolean): If True LogManager will also log the time.
  19. """
  20. LOG_FILENAME = "log"
  21. TIME_TEMPLATE = "[{time}] {error_msg}"
  22. MAX_LOGSIZE = 524288
  23. def __init__(self, config_path, add_time=False):
  24. self.config_path = config_path
  25. self.add_time = add_time
  26. self.log_file = os.path.join(config_path, self.LOG_FILENAME)
  27. self._init_log()
  28. self._auto_clear_log()
  29. def log_size(self):
  30. """Return log file size in Bytes. """
  31. if not os.path.exists(self.log_file):
  32. return 0
  33. return os.path.getsize(self.log_file)
  34. def clear(self):
  35. """Clear log file. """
  36. self._write('', 'w')
  37. def log(self, data):
  38. """Log data to the log file. """
  39. self._write(data + '\n', 'a')
  40. def _write(self, data, mode):
  41. """Write data to the log file.
  42. That's the main method for writing to the log file.
  43. Args:
  44. data (string): String to write on the log file.
  45. mode (string): Can be any IO mode supported by python.
  46. """
  47. check_path(self.config_path)
  48. with open(self.log_file, mode) as log:
  49. if mode == 'a' and self.add_time:
  50. msg = self.TIME_TEMPLATE.format(time=strftime('%c'), error_msg=data)
  51. else:
  52. msg = data
  53. log.write(msg)
  54. def _init_log(self):
  55. """Initialize the log file if not exist. """
  56. if not os.path.exists(self.log_file):
  57. self._write('', 'w')
  58. def _auto_clear_log(self):
  59. """Auto clear the log file. """
  60. if self.log_size() > self.MAX_LOGSIZE:
  61. self.clear()