logger.py 5.4 KB

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