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.

97 lines
2.5 KiB

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