log_highlighter.py 1.1 KB

12345678910111213141516171819202122232425262728293031323334
  1. # This Python file uses the following encoding: utf-8
  2. # @author runhey
  3. # github https://github.com/runhey
  4. import re
  5. from html import escape
  6. def replace_newline_with_br(input_text):
  7. replaced_text = input_text.replace('\n', '<br>')
  8. return replaced_text
  9. def highlight_text(input_text):
  10. color_mapping = {
  11. r'\d{2}:\d{2}:\d{2}\.\d{3}': 'cyan',
  12. r'\bTrue\b': 'lime',
  13. r'\bFalse\b': 'red',
  14. r'DEBUG': 'cyan',
  15. r'INFO': 'green',
  16. r'WARNING': 'yellow',
  17. r'ERROR': 'red',
  18. r'CRITICAL': 'darkred'
  19. }
  20. for pattern, color in color_mapping.items():
  21. input_text = re.sub(pattern, f'<span style="color: {color}">\\g<0></span>', input_text)
  22. return replace_newline_with_br(input_text)
  23. # 测试
  24. # input_string = 'The time is 13:20:36.411. Is it True or False? DEBUG: This is a debug message. INFO: This is an info message. WARNING: This is a warning message. ERROR: This is an error message. CRITICAL: This is a critical message.'
  25. # highlighted_text = highlight_text(input_string)
  26. # html_text = f'<html><body>{highlighted_text}</body></html>'
  27. # print(html_text)