log_manager.py 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. # Copyright 2020 The Chromium Authors. All rights reserved.
  2. # Use of this source code is governed by a BSD-style license that can be
  3. # found in the LICENSE file.
  4. """Creates and manages log file objects.
  5. Provides an object that handles opening and closing file streams for
  6. logging purposes.
  7. """
  8. import os
  9. class LogManager(object):
  10. def __init__(self, logs_dir):
  11. # A dictionary with the log file path as the key and a file stream as value.
  12. self._logs = {}
  13. self._logs_dir = logs_dir
  14. if self._logs_dir:
  15. if not os.path.isdir(self._logs_dir):
  16. os.makedirs(self._logs_dir)
  17. def IsLoggingEnabled(self):
  18. return self._logs_dir is not None
  19. def GetLogDirectory(self):
  20. """Get the directory logs are placed into."""
  21. return self._logs_dir
  22. def Open(self, log_file_name):
  23. """Open a file stream with log_file_name in the logs directory."""
  24. parent_dir = self.GetLogDirectory()
  25. if not parent_dir:
  26. return open(os.devnull, 'w')
  27. log_file_path = os.path.join(parent_dir, log_file_name)
  28. if log_file_path in self._logs:
  29. return self._logs[log_file_path]
  30. log_file = open(log_file_path, 'w', buffering=1)
  31. self._logs[log_file_path] = log_file
  32. return log_file
  33. def Stop(self):
  34. for log in self._logs.values():
  35. log.close()
  36. def __enter__(self):
  37. return self
  38. def __exit__(self, exc_type, exc_value, traceback):
  39. self.Stop()