Skip to content

Commit

Permalink
feat: adds more levels parsing like [ error] with spaces (#2441)
Browse files Browse the repository at this point in the history
  • Loading branch information
amir20 authored Oct 23, 2023
1 parent caa3bb1 commit 78c1d72
Show file tree
Hide file tree
Showing 2 changed files with 53 additions and 8 deletions.
24 changes: 16 additions & 8 deletions docker/level_guesser.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,22 +7,30 @@ import (

var KEY_VALUE_REGEX = regexp.MustCompile(`level=(\w+)`)
var ANSI_COLOR_REGEX = regexp.MustCompile(`\x1b\[[0-9;]*m`)
var LOG_LEVELS = []string{"error", "warn", "warning", "info", "debug", "trace", "fatal"}
var LOG_LEVELS_PLAIN = map[string]*regexp.Regexp{}
var LOG_LEVEL_BRACKET = map[string]*regexp.Regexp{}

func init() {
for _, level := range LOG_LEVELS {
LOG_LEVELS_PLAIN[level] = regexp.MustCompile("(?i)^" + level + "[^a-z]")
}

for _, level := range LOG_LEVELS {
LOG_LEVEL_BRACKET[level] = regexp.MustCompile("(?i)^\\[ ?" + level + " ?\\]")
}
}

func guessLogLevel(logEvent *LogEvent) string {
switch value := logEvent.Message.(type) {
case string:
levels := []string{"error", "warn", "warning", "info", "debug", "trace", "fatal"}
stripped := ANSI_COLOR_REGEX.ReplaceAllString(value, "") // remove ansi color codes
for _, level := range levels {
if match, _ := regexp.MatchString("(?i)^"+level+"[^a-z]", stripped); match {
return level
}

if strings.Contains(value, "["+strings.ToUpper(level)+"]") {
for _, level := range LOG_LEVELS {
if LOG_LEVELS_PLAIN[level].MatchString(stripped) {
return level
}

if strings.Contains(value, "["+strings.ToLower(level)+"]") {
if LOG_LEVEL_BRACKET[level].MatchString(stripped) {
return level
}

Expand Down
37 changes: 37 additions & 0 deletions docker/level_guesser_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
package docker

import (
"testing"
)

func TestGuessLogLevel(t *testing.T) {
tests := []struct {
input string
expected string
}{
{"ERROR: Something went wrong", "error"},
{"WARN: Something might be wrong", "warn"},
{"INFO: Something happened", "info"},
{"debug: Something happened", "debug"},
{"debug Something happened", "debug"},
{"TRACE: Something happened", "trace"},
{"FATAL: Something happened", "fatal"},
{"level=error Something went wrong", "error"},
{"[ERROR] Something went wrong", "error"},
{"[error] Something went wrong", "error"},
{"[ ERROR ] Something went wrong", "error"},
{"[error] Something went wrong", "error"},
{"123 ERROR Something went wrong", "error"},
{"123 Something went wrong", ""},
}

for _, test := range tests {
logEvent := &LogEvent{
Message: test.input,
}
if level := guessLogLevel(logEvent); level != test.expected {
t.Errorf("guessLogLevel(%s) = %s, want %s", test.input, level, test.expected)
}
}

}

0 comments on commit 78c1d72

Please sign in to comment.