logger.py 5.0 KB

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