Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 14 additions & 0 deletions .golangci.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,20 @@ linters:
- path: ".*\\.pb\\.go$"
linters:
- lll
- path: '^log/slog\.go$'
linters:
- revive
text: '^(package-comments: should have a package comment|exported: exported function NewPluginLogger should have comment or be unexported)$'
- path: '^log/slog_test\.go$'
linters:
- gosec
text: '^G204: Subprocess launched with variable$'
source: '^\s*cmd := exec\.Command\(executable, "-test\.run=\^TestPluginLoggerProcess\$"\)$'
- path: '^log/slog_test\.go$'
linters:
- gosec
text: '^G204: Subprocess launched with variable$'
source: '^\s*cmd := exec\.Command\(executable, "-test\.run=\^TestReservedAttributeCollisions\$"\)$'
settings:
cyclop:
max-complexity: 8
Expand Down
17 changes: 17 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,23 @@ API 1.1: `remote_user` owns workspaces; `user` selects the process user. API 1.2

[runtime.proto](proto/devsy/runtime/v1/runtime.proto) specifies RPCs.

## Plugin logging

Use `log.NewPluginLogger` to write structured provider diagnostics to stderr:

```go
import pluginlog "github.com/devsy-org/devsy-runtime-sdk/log"

logger := pluginlog.NewPluginLogger("example")
logger.Info("workspace started", "workspace_id", workspaceID)
```

The logger uses newline-delimited JSON with `ts`, `level`, and `msg` fields by default. It adds `component=provider` and the supplied provider name. `DEVSY_LOG_LEVEL` accepts `error`, `warn`, `info`, `debug`, or `trace`, and defaults to `info`. `DEVSY_LOG_FORMAT` accepts `json`, `text`, `plain`, or `auto`. Empty and `auto` select JSON. Invalid values fall back to the defaults and produce a warning without including the invalid value. Configuration is read when each logger is constructed.

At the root, caller attributes and group names `ts`, `time`, `level`, `msg`, `message`, `component`, and `provider` receive a `user_` prefix. This also applies to attributes in inline groups. Nested named groups retain their original keys. Reserve the `user_` prefix for collision escaping to avoid duplicate keys.

The logger does not redact application-provided values. Avoid logging secrets. Host-side redaction remains necessary. Logging a fatal severity does not terminate the process.

## Test and develop

Pass `Connect`, `Workspace`, and `Command` to `conformance.Run`. `Command` returns `*runtimev1.ExecStart` with matching `workspace_id`, `tty=false`, and nonempty argv. Map scenarios:
Expand Down
199 changes: 199 additions & 0 deletions log/slog.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,199 @@
package log

import (
"context"
"log/slog"
"os"
"strings"
"time"
)

func NewPluginLogger(providerName string) *slog.Logger {
level, invalidLevel := pluginLevel(os.Getenv("DEVSY_LOG_LEVEL"))
format := strings.ToLower(os.Getenv("DEVSY_LOG_FORMAT"))
invalidFormat := false
var handler slog.Handler
options := &slog.HandlerOptions{Level: level, ReplaceAttr: replaceEnvelopeAttr}
switch format {
case "", "auto", "json":
handler = slog.NewJSONHandler(os.Stderr, options)
case "text", "plain":
handler = slog.NewTextHandler(os.Stderr, options)
default:
invalidFormat = true
handler = slog.NewJSONHandler(os.Stderr, options)
}
handler = handler.WithAttrs(
[]slog.Attr{slog.String("component", "provider"), slog.String("provider", providerName)},
)
logger := slog.New(&pluginHandler{handler: handler, root: true})
if invalidLevel {
_ = logger.Handler().
Handle(context.Background(), slog.NewRecord(time.Now(), slog.LevelWarn, "invalid DEVSY_LOG_LEVEL; using info", 0))
}
if invalidFormat {
_ = logger.Handler().
Handle(context.Background(), slog.NewRecord(time.Now(), slog.LevelWarn, "invalid DEVSY_LOG_FORMAT; using json", 0))
}
return logger
}

func pluginLevel(value string) (slog.Level, bool) {
switch strings.ToLower(value) {
case "", "info":
return slog.LevelInfo, false
case "error":
return slog.LevelError, false
case "warn":
return slog.LevelWarn, false
case "debug":
return slog.LevelDebug, false
case "trace":
return slog.Level(-8), false
default:
return slog.LevelInfo, true
}
}

func replaceEnvelopeAttr(groups []string, attr slog.Attr) slog.Attr {
if len(groups) != 0 {
return attr
}
switch attr.Key {
case slog.TimeKey:
if attr.Value.Kind() == slog.KindTime {
return slog.String("ts", attr.Value.Time().Format("2006-01-02T15:04:05.000Z0700"))
}
case slog.LevelKey:
return replaceLevelAttr(attr)
}
return attr
}

func replaceLevelAttr(attr slog.Attr) slog.Attr {
level, ok := attr.Value.Any().(slog.Level)
if !ok {
return attr
}
switch level {
case -8:
return slog.String("level", "trace")
case 12:
return slog.String("level", "fatal")
default:
return slog.String("level", strings.ToLower(level.String()))
}
}

type pluginHandler struct {
handler slog.Handler
root bool
}

func (h *pluginHandler) Enabled(ctx context.Context, level slog.Level) bool {
return h.handler.Enabled(ctx, level)
}

func (h *pluginHandler) Handle(ctx context.Context, record slog.Record) error {
if !h.root {
return h.handler.Handle(ctx, record)
}
var replacement slog.Record
changed := false
index := 0
record.Attrs(func(attr slog.Attr) bool {
escaped, modified := escapeRootAttr(attr)
if modified && !changed {
replacement = slog.NewRecord(record.Time, record.Level, record.Message, record.PC)
copyRecordPrefix(&replacement, record, index)
changed = true
}
if changed {
replacement.AddAttrs(escaped)
}
index++
return true
})
if changed {
return h.handler.Handle(ctx, replacement)
}
return h.handler.Handle(ctx, record)
}

func copyRecordPrefix(dst *slog.Record, src slog.Record, count int) {
src.Attrs(func(attr slog.Attr) bool {
if count == 0 {
return false
}
dst.AddAttrs(attr)
count--
return true
})
}

func (h *pluginHandler) WithAttrs(attrs []slog.Attr) slog.Handler {
if h.root {
attrs, _ = escapeRootAttrs(attrs)
}
return &pluginHandler{handler: h.handler.WithAttrs(attrs), root: h.root}
}

func (h *pluginHandler) WithGroup(name string) slog.Handler {
if name == "" {
return h
}
if h.root {
name = escapeRootKey(name)
}
return &pluginHandler{handler: h.handler.WithGroup(name)}
}

func escapeRootKey(key string) string {
switch key {
case "ts", "time", "level", "msg", "message", "component", "provider":
return "user_" + key
default:
return key
}
}

func escapeRootAttrs(attrs []slog.Attr) ([]slog.Attr, bool) {
var escaped []slog.Attr
for i, attr := range attrs {
value, modified := escapeRootAttr(attr)
if modified && escaped == nil {
escaped = make([]slog.Attr, len(attrs))
copy(escaped, attrs[:i])
}
if escaped != nil {
escaped[i] = value
}
}
if escaped == nil {
return attrs, false
}
return escaped, true
}

func escapeRootAttr(attr slog.Attr) (slog.Attr, bool) {
if attr.Key != "" {
key := escapeRootKey(attr.Key)
if key != attr.Key {
attr.Key = key
return attr, true
}
return attr, false
}
modified := attr.Value.Kind() == slog.KindLogValuer
if modified {
attr.Value = attr.Value.Resolve()
}
if attr.Value.Kind() != slog.KindGroup {
return attr, modified
}
attrs, escaped := escapeRootAttrs(attr.Value.Group())
if escaped {
attr.Value = slog.GroupValue(attrs...)
}
return attr, modified || escaped
}
Loading
Loading