feat(parser/log): log string line by line
This commit is contained in:
parent
e800bc5c2a
commit
91a452e23d
|
|
@ -5,23 +5,37 @@ import (
|
|||
"encoding/json"
|
||||
"fmt"
|
||||
"log/slog"
|
||||
"strings"
|
||||
|
||||
"github.com/joint-online-judge/JOJ3/internal/stage"
|
||||
)
|
||||
|
||||
func (*Log) parse(executorResult stage.ExecutorResult, conf Conf) stage.ParserResult {
|
||||
content := executorResult.Files[conf.Filename]
|
||||
var data map[string]any
|
||||
content, ok := executorResult.Files[conf.Filename]
|
||||
if !ok {
|
||||
slog.Error("file not found for log parser", "filename", conf.Filename)
|
||||
return stage.ParserResult{
|
||||
Score: 0,
|
||||
Comment: fmt.Sprintf("log parser: file %s not found", conf.Filename),
|
||||
}
|
||||
}
|
||||
contentBytes := []byte(content)
|
||||
if json.Valid(contentBytes) {
|
||||
err := json.Unmarshal(contentBytes, &data)
|
||||
if err != nil {
|
||||
slog.Error(conf.Msg, "error", err)
|
||||
return stage.ParserResult{
|
||||
Score: 0,
|
||||
Comment: fmt.Sprintf("Failed to parse content: %s", err),
|
||||
var data map[string]any
|
||||
if err := json.Unmarshal(contentBytes, &data); err != nil {
|
||||
// Not a valid json or failed to unmarshal, log as raw string line by line.
|
||||
for line := range strings.SplitSeq(content, "\n") {
|
||||
if strings.TrimSpace(line) != "" {
|
||||
slog.Default().Log(
|
||||
context.Background(),
|
||||
slog.Level(conf.Level),
|
||||
conf.Msg,
|
||||
"line",
|
||||
line,
|
||||
)
|
||||
}
|
||||
}
|
||||
} else {
|
||||
// Valid json, log as key-value pairs.
|
||||
args := make([]any, 0, len(data)*2)
|
||||
for key, value := range data {
|
||||
args = append(args, key, value)
|
||||
|
|
@ -32,14 +46,6 @@ func (*Log) parse(executorResult stage.ExecutorResult, conf Conf) stage.ParserRe
|
|||
conf.Msg,
|
||||
args...,
|
||||
)
|
||||
} else {
|
||||
slog.Default().Log(
|
||||
context.Background(),
|
||||
slog.Level(conf.Level),
|
||||
conf.Msg,
|
||||
"content",
|
||||
content,
|
||||
)
|
||||
}
|
||||
return stage.ParserResult{
|
||||
Score: 0,
|
||||
|
|
|
|||
Loading…
Reference in New Issue
Block a user