Sublime Text 用于自定义 Python 日志格式的语法高亮

huangapple go评论65阅读模式
英文:

Sublime Syntax Highlighting for Custom Python Logging Formatter

问题

I want to highlight my python log outputs with sublime syntax definitions according to my custom python logging formatter. I try below syntax definition but it did not work. I can't see this highlight on my sublime highlight list. Below is my python CustomFormatter class, sublime syntax definitions and example log. Can you give me any solution?

我的目标是使用Sublime的语法定义来突出显示我的Python日志输出,根据我的自定义Python日志格式化程序。我尝试了下面的语法定义,但它没有起作用。我无法在Sublime的高亮列表中看到此突出显示。下面是我的Python CustomFormatter类、Sublime的语法定义和示例日志。你能给我任何解决方案吗?

My syntax definition is:

我的语法定义如下:

%YAML 1.2
---
# See http://www.sublimetext.com/docs/syntax.html
name: TBLog
file_extensions:
  - tblog
scope: source.tblog
contexts:
  main:
    - match: '^\[.*\].*'
      captures:
        '0': { name: string.timestamp.tblog }
        '1': { name: string.loglevel.tblog }
      push: log_message

  log_message:
    - match: '$'
      pop: true
    - include: string.quoted.double
    - include: string.quoted.single
    - include: keyword.control
    - include: constant.numeric
    - include: string.timestamp

  string.timestamp:
    - match: '\[\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}\]'
      scope: string.timestamp.tblog

  string.quoted.double:
    - match: '"'
      scope: punctuation.definition.string.begin.tblog
      push:
        - meta_scope: string.quoted.double.tblog
        - match: '\\.'
          scope: constant.character.escape.tblog
        - match: '"'
          scope: punctuation.definition.string.end.tblog
          pop: true

  string.quoted.single:
    - match: '"'
      scope: punctuation.definition.string.begin.tblog
      push:
        - meta_scope: string.quoted.single.tblog
        - match: '\\.'
          scope: constant.character.escape.tblog
        - match: '"'
          scope: punctuation.definition.string.end.tblog
          pop: true

  keyword.control:
    - match: '\b(if|else|for|while)\b'
      scope: keyword.control.tblog

  constant.numeric:
    - match: '\b(-)?[0-9.]+\b'
      scope: constant.numeric.tblog

  string.loglevel:
    - match: '\[(WARNING|ERROR|CRITICAL|DEBUG|INFO)\]'
      captures:
        '0': { name: string.loglevel.tblog }
      scope: meta.loglevel.tblog
      push: log_message

  meta_scope:
    string.loglevel.tblog: 'meta.loglevel.tblog'

My custom python formatter is:

我的自定义Python格式化程序如下:

class ColorFormatter(logging.Formatter):
    COLORS = {
        'WARNING': colorama.Fore.YELLOW + colorama.Style.BRIGHT,
        'ERROR': colorama.Fore.RED + colorama.Style.BRIGHT,
        'CRITICAL': colorama.Fore.WHITE + colorama.Style.BRIGHT + colorama.Back.RED,
        'DEBUG': colorama.Fore.BLUE + colorama.Style.BRIGHT,
        'INFO': colorama.Fore.GREEN + colorama.Style.BRIGHT,
        'DEFAULT': colorama.Fore.WHITE,
    }

    def __init__(self, fmt="[%(asctime)s][%(levelname).1s]%(message)s", datefmt="%Y-%m-%d %H:%M:%S"):
        logging.Formatter.__init__(self, fmt, datefmt)

    def format(self, record):
        color = self.COLORS.get(record.levelname, self.COLORS['DEFAULT'])
        message = logging.Formatter.format(self, record)
        return f"{color}{message}\033[0m"

Example log is:

示例日志如下:

[2023-02-23 22:58:25,226][I]TC] Initializing the bot!
[2023-02-23 22:58:25,241][D]EX] Creating exchange client.
[2023-02-23 22:58:25,678][D]EX] Exchange client has been created!
[2023-02-23 22:58:25,709][I]TC] Preparing bot to start trading!
[2023-02-23 22:58:25,725][D]TC] Variables has been reset!
[2023-02-23 22:58:26,023][D]TC] Server time has been updated! [ST (ms): 1677182307137]
[2023-02-23 22:58:26,038][D]TC] Time difference has been updated! [TD (ms): 1114]
[2023-02-23 22:58:26,337][D]TC] Account order asset balance has been updated! [B: 64.94 BUSD]
[2023-02-23 22:58:26,353][D]TC] Buy order size has been updated! [BOS: 64 BUSD]
[2023-02-23 22:58:26,385][I]TC] Scanning for potential entry opportunities!
英文:

I want to highlight my python log outputs with sublime syntax definitions according to my custom python logging formatter. I try below syntax definition but it did not work. I can't see this highlight on my sublime highlight list. Below is my python CustomFormatter class, sublime syntax definitions and example log. Can you give me any solution?

My syntax definition is:

%YAML 1.2
---
# See http://www.sublimetext.com/docs/syntax.html
name: TBLog
file_extensions:
  - tblog
scope: source.tblog
contexts:
  main:
    - match: '^\[.*\].*'
      captures:
        '0': { name: string.timestamp.tblog }
        '1': { name: string.loglevel.tblog }
      push: log_message

  log_message:
    - match: '$'
      pop: true
    - include: string.quoted.double
    - include: string.quoted.single
    - include: keyword.control
    - include: constant.numeric
    - include: string.timestamp

  string.timestamp:
    - match: '\[\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}\]'
      scope: string.timestamp.tblog

  string.quoted.double:
    - match: '"'
      scope: punctuation.definition.string.begin.tblog
      push:
        - meta_scope: string.quoted.double.tblog
        - match: '\\.'
          scope: constant.character.escape.tblog
        - match: '"'
          scope: punctuation.definition.string.end.tblog
          pop: true

  string.quoted.single:
    - match: "'"
      scope: punctuation.definition.string.begin.tblog
      push:
        - meta_scope: string.quoted.single.tblog
        - match: '\\.'
          scope: constant.character.escape.tblog
        - match: "'"
          scope: punctuation.definition.string.end.tblog
          pop: true

  keyword.control:
    - match: '\b(if|else|for|while)\b'
      scope: keyword.control.tblog

  constant.numeric:
    - match: '\b(-)?[0-9.]+\b'
      scope: constant.numeric.tblog

  string.loglevel:
    - match: '\[(WARNING|ERROR|CRITICAL|DEBUG|INFO)\]'
      captures:
        '0': { name: string.loglevel.tblog }
      scope: meta.loglevel.tblog
      push: log_message

  meta_scope:
    string.loglevel.tblog: 'meta.loglevel.tblog'

My custom python formatter is:

class ColorFormatter(logging.Formatter):
    COLORS = {
        'WARNING': colorama.Fore.YELLOW + colorama.Style.BRIGHT,
        'ERROR': colorama.Fore.RED + colorama.Style.BRIGHT,
        'CRITICAL': colorama.Fore.WHITE + colorama.Style.BRIGHT + colorama.Back.RED,
        'DEBUG': colorama.Fore.BLUE + colorama.Style.BRIGHT,
        'INFO': colorama.Fore.GREEN + colorama.Style.BRIGHT,
        'DEFAULT': colorama.Fore.WHITE,
    }

    def __init__(self, fmt="[%(asctime)s][%(levelname).1s]%(message)s", datefmt="%Y-%m-%d %H:%M:%S"):
        logging.Formatter.__init__(self, fmt, datefmt)

    def format(self, record):
        color = self.COLORS.get(record.levelname, self.COLORS['DEFAULT'])
        message = logging.Formatter.format(self, record)
        return f"{color}{message}\033[0m"

Example log is:

[2023-02-23 22:58:25,226][I]TC] Initializing the bot!
[2023-02-23 22:58:25,241][D]EX] Creating exchange client.
[2023-02-23 22:58:25,678][D]EX] Exchange client has been created!
[2023-02-23 22:58:25,709][I]TC] Preparing bot to start trading!
[2023-02-23 22:58:25,725][D]TC] Variables has been reset!
[2023-02-23 22:58:26,023][D]TC] Server time has been updated! [ST (ms): 1677182307137]
[2023-02-23 22:58:26,038][D]TC] Time difference has been updated! [TD (ms): 1114]
[2023-02-23 22:58:26,337][D]TC] Account order asset balance has been updated! [B: 64.94 BUSD]
[2023-02-23 22:58:26,353][D]TC] Buy order size has been updated! [BOS: 64 BUSD]
[2023-02-23 22:58:26,385][I]TC] Scanning for potential entry opportunities!

答案1

得分: 1

不要回答我要翻译的问题。以下是要翻译的内容:

如果你打开Sublime Text控制台(视图菜单 -> 显示控制台),当你保存你的sublime-syntax文件时,你会看到一个错误消息:

> error parsing lexer: Packages/User/tblog.sublime-syntax: patterns must be a vector at line 67 column 5

第67行是在你的meta_scope上下文下面的那一行。

移除那个上下文,因为它没有被任何地方引用,会得到以下错误:

> error parsing lexer: Packages/User/tblog.sublime-syntax: capture scope must be a string at line 10 column 7

如果你查看文档中的示例捕获,你会看到它说明了你不应该在捕获组数字上使用字符串引号,它期望一个普通字符串而不是一个包含name:的映射。

修复了所有这些问题之后,它仍然不会像你期望的那样高亮显示,因为在main上下文中你在第一个匹配模式的末尾有一个.*。移除它会得到以下内容:

%YAML 1.2
---
# 详见http://www.sublimetext.com/docs/syntax.html
name: TBLog
file_extensions:
  - tblog
scope: source.tblog
contexts:
  main:
    - match: '^\[.*\]'
      captures:
        0: string.timestamp.tblog
        1: string.loglevel.tblog
      push: log_message

  log_message:
    - match: '$'
      pop: true
    - include: string.quoted.double
    - include: string.quoted.single
    - include: keyword.control
    - include: constant.numeric
    - include: string.timestamp

  string.timestamp:
    - match: '\[\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}\]'
      scope: string.timestamp.tblog

  string.quoted.double:
    - match: '"'
      scope: punctuation.definition.string.begin.tblog
      push:
        - meta_scope: string.quoted.double.tblog
        - match: '\\.'
          scope: constant.character.escape.tblog
        - match: '"'
          scope: punctuation.definition.string.end.tblog
          pop: true

  string.quoted.single:
    - match: "'"
      scope: punctuation.definition.string.begin.tblog
      push:
        - meta_scope: string.quoted.single.tblog
        - match: '\\.'
          scope: constant.character.escape.tblog
        - match: "'"
          scope: punctuation.definition.string.end.tblog
          pop: true

  keyword.control:
    - match: '\b(if|else|for|while)\b'
      scope: keyword.control.tblog

  constant.numeric:
    - match: '\b(-)?[0-9.]+\b'
      scope: constant.numeric.tblog

  string.loglevel:
    - match: '\[(WARNING|ERROR|CRITICAL|DEBUG|INFO)\]'
      captures:
        '0': string.loglevel.tblog
      scope: meta.loglevel.tblog
      push: log_message

然后在启用了TBLog语法的情况下,你的文本在Sublime Text中会看起来像这样:Sublime Text 用于自定义 Python 日志格式的语法高亮

英文:

If you open the Sublime Text console (View menu -> Show Console), you will see an error when you save your sublime-syntax file:

> error parsing lexer: Packages/User/tblog.sublime-syntax: patterns must be a vector at line 67 column 5

Line 67 is the line under your meta_scope context.

Removing that context, as it isn't referenced anywhere, gives us:

> error parsing lexer: Packages/User/tblog.sublime-syntax: capture scope must be a string at line 10 column 7

If you look at the example captures in the documentation, you'll see how you shouldn't string quote the capture group numbers and it expects a plain string instead of a map with a name:.

After fixing all that, it still won't highlight the way you might expect because of the .* you have at the end of your first match pattern in the main context. Removing that gives:

%YAML 1.2
---
# See http://www.sublimetext.com/docs/syntax.html
name: TBLog
file_extensions:
  - tblog
scope: source.tblog
contexts:
  main:
    - match: '^\[.*\]'
      captures:
        0: string.timestamp.tblog
        1: string.loglevel.tblog
      push: log_message

  log_message:
    - match: '$'
      pop: true
    - include: string.quoted.double
    - include: string.quoted.single
    - include: keyword.control
    - include: constant.numeric
    - include: string.timestamp

  string.timestamp:
    - match: '\[\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}\]'
      scope: string.timestamp.tblog

  string.quoted.double:
    - match: '"'
      scope: punctuation.definition.string.begin.tblog
      push:
        - meta_scope: string.quoted.double.tblog
        - match: '\\.'
          scope: constant.character.escape.tblog
        - match: '"'
          scope: punctuation.definition.string.end.tblog
          pop: true

  string.quoted.single:
    - match: "'"
      scope: punctuation.definition.string.begin.tblog
      push:
        - meta_scope: string.quoted.single.tblog
        - match: '\\.'
          scope: constant.character.escape.tblog
        - match: "'"
          scope: punctuation.definition.string.end.tblog
          pop: true

  keyword.control:
    - match: '\b(if|else|for|while)\b'
      scope: keyword.control.tblog

  constant.numeric:
    - match: '\b(-)?[0-9.]+\b'
      scope: constant.numeric.tblog

  string.loglevel:
    - match: '\[(WARNING|ERROR|CRITICAL|DEBUG|INFO)\]'
      captures:
        '0': string.loglevel.tblog
      scope: meta.loglevel.tblog
      push: log_message

and then your text looks like this in ST with your TBLog syntax enabled:
Sublime Text 用于自定义 Python 日志格式的语法高亮

答案2

得分: 0

I used below YAML syntax code.

And below tmTheme.xml for colors.

And below is how its look like.

https://i.stack.imgur.com/T8iL7.jpg

英文:

I used below YAML syntax code.

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-html -->

%YAML 1.2
---
# See http://www.sublimetext.com/docs/syntax.html
name: TBLog
file_extensions:
- tblog
scope: tb
contexts:
log_line:
# data
- match: &#39;\[([^\[\]]+)\]&#39;
scope: tb.data
push: log_line
- match: &#39;$&#39;
pop: true
main:
# debug
- match: &#39;\[(\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2})\]\[D\]&#39;
scope: tb.debug
push: log_line
# info
- match: &#39;\[(\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2})\]\[I\]&#39;
scope: tb.info
push: log_line
# warning
- match: &#39;\[(\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2})\]\[W\]&#39;
scope: tb.warning
push: log_line
# error
- match: &#39;\[(\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2})\]\[E\]&#39;
scope: tb.error
push: log_line
# critical
- match: &#39;\[(\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2})\]\[C\]&#39;
scope: tb.critical
push: log_line
# datetime
- match: &#39;\[(\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2})\]&#39;
scope: tb.datetime
push:
- match: &#39;\[D\]&#39;
scope: tb.debug
pop: true
- match: &#39;\[I\]&#39;
scope: tb.info
pop: true
- match: &#39;\[W\]&#39;
scope: tb.warning
pop: true
- match: &#39;\[E\]&#39;
scope: tb.error
pop: true
- match: &#39;\[C\]&#39;
scope: tb.critical
pop: true

<!-- end snippet -->

And below tmTheme.xml for colors.

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-html -->

&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt;
&lt;!DOCTYPE plist PUBLIC &quot;-//Apple//DTD PLIST 1.0//EN&quot; &quot;http://www.apple.com/DTDs/PropertyList-1.0.dtd&quot;&gt;
&lt;plist version=&quot;1.0&quot;&gt;
&lt;dict&gt;
&lt;key&gt;name&lt;/key&gt;
&lt;string&gt;TBLog&lt;/string&gt;
&lt;key&gt;settings&lt;/key&gt;
&lt;array&gt;
&lt;dict&gt;
&lt;key&gt;settings&lt;/key&gt;
&lt;dict&gt;
&lt;key&gt;background&lt;/key&gt;
&lt;string&gt;#272822&lt;/string&gt;
&lt;key&gt;caret&lt;/key&gt;
&lt;string&gt;#F8F8F0&lt;/string&gt;   
&lt;key&gt;foreground&lt;/key&gt;
&lt;string&gt;#F8F8F2&lt;/string&gt;
&lt;key&gt;invisibles&lt;/key&gt;
&lt;string&gt;#5E5E5E&lt;/string&gt;
&lt;key&gt;line_highlight&lt;/key&gt;
&lt;string&gt;#3E3D32&lt;/string&gt;
&lt;key&gt;selection&lt;/key&gt;
&lt;string&gt;#49483E&lt;/string&gt;
&lt;key&gt;findHighlightForeground&lt;/key&gt;
&lt;string&gt;#000000&lt;/string&gt;
&lt;key&gt;selectionBorder&lt;/key&gt;
&lt;string&gt;#222218&lt;/string&gt;
&lt;key&gt;activeGuide&lt;/key&gt;
&lt;string&gt;#9D550FB0&lt;/string&gt;
&lt;key&gt;bracketsForeground&lt;/key&gt;
&lt;string&gt;#F8F8F2A5&lt;/string&gt;
&lt;key&gt;bracketsOptions&lt;/key&gt;
&lt;string&gt;underline&lt;/string&gt;
&lt;key&gt;bracketsContentsForeground&lt;/key&gt;
&lt;string&gt;#F8F8F2A5&lt;/string&gt;
&lt;key&gt;bracketsContentsOptions&lt;/key&gt;
&lt;string&gt;underline&lt;/string&gt;
&lt;key&gt;tagsOptions&lt;/key&gt;
&lt;string&gt;stippled_underline&lt;/string&gt;
&lt;/dict&gt;
&lt;/dict&gt;
&lt;dict&gt;
&lt;key&gt;name&lt;/key&gt;    
&lt;string&gt;Datetime&lt;/string&gt;
&lt;key&gt;scope&lt;/key&gt;    
&lt;string&gt;tb.datetime&lt;/string&gt;     
&lt;key&gt;settings&lt;/key&gt;    
&lt;dict&gt;
&lt;key&gt;foreground&lt;/key&gt;
&lt;string&gt;#00B764&lt;/string&gt;
&lt;/dict&gt;
&lt;/dict&gt;
&lt;dict&gt;
&lt;key&gt;name&lt;/key&gt;    
&lt;string&gt;Data&lt;/string&gt;
&lt;key&gt;scope&lt;/key&gt;    
&lt;string&gt;tb.data&lt;/string&gt;     
&lt;key&gt;settings&lt;/key&gt;    
&lt;dict&gt;
&lt;key&gt;foreground&lt;/key&gt;
&lt;string&gt;#FFA500&lt;/string&gt;
&lt;/dict&gt;
&lt;/dict&gt;
&lt;dict&gt;
&lt;key&gt;name&lt;/key&gt;    
&lt;string&gt;Debug&lt;/string&gt;
&lt;key&gt;scope&lt;/key&gt;    
&lt;string&gt;tb.debug&lt;/string&gt;     
&lt;key&gt;settings&lt;/key&gt;    
&lt;dict&gt;
&lt;key&gt;foreground&lt;/key&gt;
&lt;string&gt;#16ACBA&lt;/string&gt;
&lt;/dict&gt;
&lt;/dict&gt;
&lt;dict&gt;
&lt;key&gt;name&lt;/key&gt;    
&lt;string&gt;Info&lt;/string&gt;
&lt;key&gt;scope&lt;/key&gt;    
&lt;string&gt;tb.info&lt;/string&gt;     
&lt;key&gt;settings&lt;/key&gt;    
&lt;dict&gt;
&lt;key&gt;foreground&lt;/key&gt;
&lt;string&gt;#00B764&lt;/string&gt;
&lt;/dict&gt;
&lt;/dict&gt;
&lt;dict&gt;
&lt;key&gt;name&lt;/key&gt;    
&lt;string&gt;Warning&lt;/string&gt;
&lt;key&gt;scope&lt;/key&gt;    
&lt;string&gt;tb.warning&lt;/string&gt;     
&lt;key&gt;settings&lt;/key&gt;    
&lt;dict&gt;
&lt;key&gt;foreground&lt;/key&gt;
&lt;string&gt;#EDD436&lt;/string&gt;
&lt;/dict&gt;
&lt;/dict&gt;
&lt;dict&gt;
&lt;key&gt;name&lt;/key&gt;    
&lt;string&gt;Error&lt;/string&gt;
&lt;key&gt;scope&lt;/key&gt;    
&lt;string&gt;tb.error&lt;/string&gt;     
&lt;key&gt;settings&lt;/key&gt;    
&lt;dict&gt;
&lt;key&gt;background&lt;/key&gt;
&lt;string&gt;#FF0000&lt;/string&gt;
&lt;key&gt;foreground&lt;/key&gt;
&lt;string&gt;#FFFFFF&lt;/string&gt;
&lt;/dict&gt;
&lt;/dict&gt;
&lt;dict&gt;
&lt;key&gt;name&lt;/key&gt;    
&lt;string&gt;Critical&lt;/string&gt;
&lt;key&gt;scope&lt;/key&gt;    
&lt;string&gt;tb.critical&lt;/string&gt;     
&lt;key&gt;settings&lt;/key&gt;    
&lt;dict&gt;
&lt;key&gt;background&lt;/key&gt;
&lt;string&gt;#FF0000&lt;/string&gt;
&lt;key&gt;foreground&lt;/key&gt;
&lt;string&gt;#FFFFFF&lt;/string&gt;
&lt;/dict&gt;
&lt;/dict&gt;
&lt;/array&gt;
&lt;/dict&gt;
&lt;/plist&gt;

<!-- end snippet -->

And below is how its look like.

https://i.stack.imgur.com/T8iL7.jpg

huangapple
  • 本文由 发表于 2023年2月24日 05:06:50
  • 转载请务必保留本文链接:https://go.coder-hub.com/75550334.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定