wasi-module-sdk-go/logger.go

93 lines
1.9 KiB
Go

package sdk
// #include <stdlib.h>
import "C"
import (
"context"
"log/slog"
remotev1 "code.icb4dc0.de/buildr/api/generated/remote/v1"
"code.icb4dc0.de/buildr/wasi-module-sdk-go/mem"
)
var _ slog.Handler = (*WASIHandler)(nil)
func NewWASIHandler() WASIHandler {
return WASIHandler{}
}
type WASIHandler struct {
Level slog.Level
attrs []slog.Attr
group string
}
func (h WASIHandler) Enabled(_ context.Context, level slog.Level) bool {
return h.Level <= level
}
func (h WASIHandler) Handle(_ context.Context, record slog.Record) error {
taskLog := remotev1.TaskLog{
Time: record.Time.UnixMicro(),
Message: record.Message,
Level: int32(record.Level),
Attributes: make([]*remotev1.TaskLog_LogAttribute, 0, record.NumAttrs()),
}
record.Attrs(func(attr slog.Attr) bool {
taskLog.Attributes = append(taskLog.Attributes, &remotev1.TaskLog_LogAttribute{
Key: attr.Key,
Value: attr.Value.String(),
})
return true
})
if _, err := LogMsg(&taskLog); err != nil {
return err
}
return nil
}
func (h WASIHandler) WithAttrs(attrs []slog.Attr) slog.Handler {
newHandler := WASIHandler{
Level: h.Level,
attrs: make([]slog.Attr, 0, len(attrs)+len(h.attrs)),
}
newHandler.attrs = append(newHandler.attrs, h.attrs...)
newHandler.attrs = append(newHandler.attrs, attrs...)
return newHandler
}
func (h WASIHandler) WithGroup(name string) slog.Handler {
newHandler := WASIHandler{
Level: h.Level,
attrs: make([]slog.Attr, len(h.attrs)),
}
copy(newHandler.attrs, h.attrs)
newHandler.group = name
return newHandler
}
func LogMsg(taskLog *remotev1.TaskLog) (*remotev1.Result, error) {
data, err := taskLog.MarshalVT()
if err != nil {
return nil, err
}
resultPtr := _log_msg(mem.DataToManagedPtr(data))
data = mem.PtrToData(mem.UnifiedPtrToSizePtr(resultPtr))
resp := new(remotev1.Result)
if err := resp.UnmarshalVT(data); err != nil {
return nil, err
}
return resp, nil
}