logger.py 5.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127
  1. # SPDX-FileCopyrightText: 2015-2022 Espressif Systems (Shanghai) CO LTD
  2. # SPDX-License-Identifier: Apache-2.0
  3. import datetime
  4. import os
  5. import re
  6. from typing import BinaryIO, Callable, Optional, Union # noqa: F401
  7. from serial.tools import miniterm # noqa: F401
  8. from .constants import ADDRESS_RE
  9. from .output_helpers import lookup_pc_address, red_print, yellow_print
  10. from .pc_address_matcher import PcAddressMatcher
  11. class Logger:
  12. def __init__(self, elf_file, console, timestamps, timestamp_format, pc_address_buffer, enable_address_decoding,
  13. toolchain_prefix):
  14. # type: (str, miniterm.Console, bool, str, bytes, bool, str) -> None
  15. self.log_file = None # type: Optional[BinaryIO]
  16. self._output_enabled = True # type: bool
  17. self.elf_file = elf_file
  18. self.console = console
  19. self.timestamps = timestamps
  20. self.timestamp_format = timestamp_format
  21. self._pc_address_buffer = pc_address_buffer
  22. self.enable_address_decoding = enable_address_decoding
  23. self.toolchain_prefix = toolchain_prefix
  24. self.pc_address_matcher = PcAddressMatcher(self.elf_file) if enable_address_decoding else None
  25. @property
  26. def pc_address_buffer(self): # type: () -> bytes
  27. return self._pc_address_buffer
  28. @pc_address_buffer.setter
  29. def pc_address_buffer(self, value): # type: (bytes) -> None
  30. self._pc_address_buffer = value
  31. @property
  32. def output_enabled(self): # type: () -> bool
  33. return self._output_enabled
  34. @output_enabled.setter
  35. def output_enabled(self, value): # type: (bool) -> None
  36. self._output_enabled = value
  37. @property
  38. def log_file(self): # type: () -> Optional[BinaryIO]
  39. return self._log_file
  40. @log_file.setter
  41. def log_file(self, value): # type: (Optional[BinaryIO]) -> None
  42. self._log_file = value
  43. def toggle_logging(self): # type: () -> None
  44. if self._log_file:
  45. self.stop_logging()
  46. else:
  47. self.start_logging()
  48. def toggle_timestamps(self): # type: () -> None
  49. self.timestamps = not self.timestamps
  50. def start_logging(self): # type: () -> None
  51. if not self._log_file:
  52. name = 'log.{}.{}.txt'.format(os.path.splitext(os.path.basename(self.elf_file))[0],
  53. datetime.datetime.now().strftime('%Y%m%d%H%M%S'))
  54. try:
  55. self.log_file = open(name, 'wb+')
  56. yellow_print('\nLogging is enabled into file {}'.format(name))
  57. except Exception as e: # noqa
  58. red_print('\nLog file {} cannot be created: {}'.format(name, e))
  59. def stop_logging(self): # type: () -> None
  60. if self._log_file:
  61. try:
  62. name = self._log_file.name
  63. self._log_file.close()
  64. yellow_print('\nLogging is disabled and file {} has been closed'.format(name))
  65. except Exception as e: # noqa
  66. red_print('\nLog file cannot be closed: {}'.format(e))
  67. finally:
  68. self._log_file = None
  69. def print(self, string, console_printer=None): # noqa: E999
  70. # type: (Union[str, bytes], Optional[Callable]) -> None
  71. if console_printer is None:
  72. console_printer = self.console.write_bytes
  73. if self.timestamps and (self._output_enabled or self._log_file):
  74. t = datetime.datetime.now().strftime(self.timestamp_format)
  75. # "string" is not guaranteed to be a full line. Timestamps should be only at the beginning of lines.
  76. if isinstance(string, type(u'')):
  77. search_patt = '\n'
  78. replacement = '\n' + t + ' '
  79. else:
  80. search_patt = b'\n' # type: ignore
  81. replacement = b'\n' + t.encode('ascii') + b' ' # type: ignore
  82. string = string.replace(search_patt, replacement) # type: ignore
  83. if self._output_enabled:
  84. console_printer(string)
  85. if self._log_file:
  86. try:
  87. if isinstance(string, type(u'')):
  88. string = string.encode() # type: ignore
  89. self._log_file.write(string) # type: ignore
  90. except Exception as e:
  91. red_print('\nCannot write to file: {}'.format(e))
  92. # don't fill-up the screen with the previous errors (probably consequent prints would fail also)
  93. self.stop_logging()
  94. def output_toggle(self): # type: () -> None
  95. self.output_enabled = not self.output_enabled
  96. yellow_print('\nToggle output display: {}, Type Ctrl-T Ctrl-Y to show/disable output again.'.format(
  97. self.output_enabled))
  98. def handle_possible_pc_address_in_line(self, line): # type: (bytes) -> None
  99. line = self._pc_address_buffer + line
  100. self._pc_address_buffer = b''
  101. if not self.enable_address_decoding:
  102. return
  103. for m in re.finditer(ADDRESS_RE, line.decode(errors='ignore')):
  104. num = m.group()
  105. if self.pc_address_matcher.is_executable_address(int(num, 16)):
  106. translation = lookup_pc_address(num, self.toolchain_prefix, self.elf_file)
  107. if translation:
  108. self.print(translation, console_printer=yellow_print)