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.

91 lines
2.4 KiB

10 years ago
10 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
10 years ago
10 years ago
10 years ago
9 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 (
  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. self._write(data + '\n', 'a')
  44. def _write(self, data, mode):
  45. """Write data to the log file.
  46. That's the main method for writing to the log file.
  47. Args:
  48. data (string): String to write on the log file.
  49. mode (string): Can be any IO mode supported by python.
  50. """
  51. check_path(self.config_path)
  52. with open(self.log_file, mode) as log:
  53. if mode == 'a' and self.add_time:
  54. msg = self.TIME_TEMPLATE.format(time=strftime('%c'), error_msg=data)
  55. else:
  56. msg = data
  57. log.write(msg.encode(self._encoding, 'ignore'))
  58. def _init_log(self):
  59. """Initialize the log file if not exist. """
  60. if not os.path.exists(self.log_file):
  61. self._write('', 'w')
  62. def _auto_clear_log(self):
  63. """Auto clear the log file. """
  64. if self.log_size() > self.MAX_LOGSIZE:
  65. self.clear()