Files
act_runner/act/runner/logger_json.go
Lunny Xiao de961b91eb refactor(logging): add a logging abstraction and move the job logger onto it (#1295)
Add `act/common/logging`: a printf-style `Logger` on a slog-shaped `Handler`, with a logrus-backed handler as the only backend, plus a `logtest` handler for tests. Move the job logger onto it: `common.Logger` returns `*logging.Logger`, the job log formatters and the `Reporter` hook become handlers, and composite step IDs travel in the context.

Logging is tightly coupled to logrus types (hooks, formatters, `Entry.Data`). Going through our own interface first lets the remaining call sites move over with unchanged behavior, and lets the backend be swapped for `log/slog` in one place afterwards. The global process logger and its masking formatter stay on logrus for now.

Assisted-by: Codet
Co-authored-by: bircni <bircni@icloud.com>
Reviewed-on: https://gitea.com/gitea/runner/pulls/1295
Reviewed-by: bircni <bircni@icloud.com>
2026-10-11 23:26:00 +00:00

53 lines
1.2 KiB
Go

// Copyright 2026 The Gitea Authors. All rights reserved.
// SPDX-License-Identifier: MIT
package runner
import (
"encoding/json"
"fmt"
"io"
"sync"
"time"
"gitea.com/gitea/runner/act/common/logging"
)
// newJobLogJSONHandler writes one JSON object per record, in the shape of logrus's JSONFormatter.
func newJobLogJSONHandler(w io.Writer) *jobLogHandler {
return &jobLogHandler{w: w, mu: &sync.Mutex{}, format: formatJSON}
}
func formatJSON(r logging.Record) ([]byte, error) {
data := make(map[string]any, len(r.Attrs)+3)
for _, a := range r.Attrs {
switch v := a.Value.(type) {
case error:
data[a.Key] = v.Error() // an error marshals to {}
default:
data[a.Key] = v
}
}
for _, key := range []string{"time", "msg", "level"} {
if v, ok := data[key]; ok { // keep the fixed keys from being overwritten
data["fields."+key] = v
}
}
data["time"] = r.Time.Format(time.RFC3339)
data["msg"] = r.Message
data["level"] = jsonLevel(r.Level)
line, err := json.Marshal(data)
if err != nil {
return nil, fmt.Errorf("failed to marshal fields to JSON, %w", err)
}
return append(line, '\n'), nil
}
func jsonLevel(l logging.Level) string {
if l.String() == "warn" {
return "warning" // what logrus calls it
}
return l.String()
}