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.

98 lines
2.5 KiB

10 years ago
10 years ago
10 years ago
9 years ago
9 years ago
10 years ago
9 years ago
10 years ago
10 years ago
10 years ago
9 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 (
  8. os_path_exists,
  9. get_encoding,
  10. check_path
  11. )
  12. class LogManager(object):
  13. """Simple log manager for youtube-dl.
  14. This class is mainly used to log the youtube-dl STDERR.
  15. Attributes:
  16. LOG_FILENAME (string): Filename of the log file.
  17. TIME_TEMPLATE (string): Custom template to log the time.
  18. MAX_LOGSIZE (int): Maximum size(Bytes) of the log file.
  19. Args:
  20. config_path (string): Absolute path where LogManager should
  21. store the log file.
  22. add_time (boolean): If True LogManager will also log the time.
  23. """
  24. LOG_FILENAME = "log"
  25. TIME_TEMPLATE = "[{time}] {error_msg}"
  26. MAX_LOGSIZE = 524288 # Bytes
  27. def __init__(self, config_path, add_time=False):
  28. self.config_path = config_path
  29. self.add_time = add_time
  30. self.log_file = os.path.join(config_path, self.LOG_FILENAME)
  31. self._encoding = get_encoding()
  32. self._init_log()
  33. self._auto_clear_log()
  34. def log_size(self):
  35. """Return log file size in Bytes. """
  36. if not os_path_exists(self.log_file):
  37. return 0
  38. return os.path.getsize(self.log_file)
  39. def clear(self):
  40. """Clear log file. """
  41. self._write('', 'w')
  42. def log(self, data):
  43. """Log data to the log file.
  44. Args:
  45. data (string): String to write to the log file.
  46. """
  47. if isinstance(data, basestring):
  48. self._write(data + '\n', 'a')
  49. def _write(self, data, mode):
  50. """Write data to the log file.
  51. That's the main method for writing to the log file.
  52. Args:
  53. data (string): String to write on the log file.
  54. mode (string): Can be any IO mode supported by python.
  55. """
  56. check_path(self.config_path)
  57. with open(self.log_file, mode) as log:
  58. if mode == 'a' and self.add_time:
  59. msg = self.TIME_TEMPLATE.format(time=strftime('%c'), error_msg=data)
  60. else:
  61. msg = data
  62. log.write(msg.encode(self._encoding, 'ignore'))
  63. def _init_log(self):
  64. """Initialize the log file if not exist. """
  65. if not os_path_exists(self.log_file):
  66. self._write('', 'w')
  67. def _auto_clear_log(self):
  68. """Auto clear the log file. """
  69. if self.log_size() > self.MAX_LOGSIZE:
  70. self.clear()