log.py 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. # -*- coding: utf-8 -*-
  2. """
  3. @author: jürgen.pannosch, tanja.zolotareva
  4. """
  5. import sys
  6. import os
  7. import logging
  8. from datetime import datetime
  9. sys.path.append(os.getcwd())
  10. class Log():
  11. '''
  12. '''
  13. pass
  14. def __init__(self, name: str = None,
  15. log_file: str = None,
  16. log_level: str = "ERROR",
  17. stdout_log_level: str = "INFO",
  18. print_to_stdout: bool = True):
  19. """Sets the log level and the path where the log file is stored
  20. :param log_file: Path to the log file.
  21. :param log_level: Log level."""
  22. if name is None:
  23. name = ''
  24. self._logger = logging.getLogger(name)
  25. self._logger.setLevel("DEBUG")
  26. if (self._logger.hasHandlers()):
  27. self._logger.handlers.clear()
  28. if log_file is None:
  29. log_file = os.path.join(".", "logs", str(datetime.today().date()) + ".log")
  30. assert(isinstance(log_file, str)),\
  31. "Parameter 'log_path' must be of string type"
  32. os.makedirs(os.path.dirname(log_file), exist_ok=True)
  33. formatter = logging.Formatter(
  34. '\n %(name)s %(asctime)s %(levelname)s %(message)s')
  35. file_handler = logging.FileHandler(log_file)
  36. file_handler.setFormatter(formatter)
  37. file_handler.setLevel(log_level)
  38. self._logger.addHandler(file_handler)
  39. if print_to_stdout:
  40. stream_handler = logging.StreamHandler(sys.stdout)
  41. stream_handler.setFormatter(formatter)
  42. stream_handler.setLevel(stdout_log_level)
  43. self._logger.addHandler(stream_handler)
  44. # self._logger.setLevel(log_level)
  45. def info(self, message: str):
  46. self._logger.info(message)
  47. def warning(self, message: str):
  48. self._logger.warning(message)
  49. def error(self, message: str):
  50. self._logger.error(message)
  51. def log_and_raise_error(self, message):
  52. '''
  53. '''
  54. self._logger.error(message, exc_info=True)
  55. raise Exception(message)
  56. def log_and_raise_error_stack_info(self, message):
  57. '''
  58. '''
  59. self._logger.error(message, exc_info=True, stack_info=True)
  60. raise Exception(message)
  61. def log_and_raise_warning(self, message):
  62. '''
  63. '''
  64. self._logger.warning(message)
  65. raise Warning(message)