80 lines
1.6 KiB
Go
80 lines
1.6 KiB
Go
package sdk
|
|
|
|
// #include <stdlib.h>
|
|
import "C"
|
|
|
|
import (
|
|
"context"
|
|
|
|
"golang.org/x/exp/slog"
|
|
|
|
"code.icb4dc0.de/buildr/wasi-module-sdk/mem"
|
|
rpcv1 "code.icb4dc0.de/buildr/wasi-module-sdk/protocol/generated/rpc/v1"
|
|
)
|
|
|
|
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(ctx context.Context, record slog.Record) error {
|
|
taskLog := rpcv1.TaskLog{
|
|
Time: record.Time.UnixMicro(),
|
|
Message: record.Message,
|
|
Level: int32(record.Level),
|
|
Attributes: make([]*rpcv1.TaskLog_LogAttribute, 0, record.NumAttrs()),
|
|
}
|
|
|
|
record.Attrs(func(attr slog.Attr) bool {
|
|
taskLog.Attributes = append(taskLog.Attributes, &rpcv1.TaskLog_LogAttribute{
|
|
Key: attr.Key,
|
|
Value: attr.Value.String(),
|
|
})
|
|
|
|
return true
|
|
})
|
|
|
|
data, err := taskLog.MarshalVT()
|
|
if err != nil {
|
|
return err
|
|
}
|
|
|
|
_log_msg(mem.DataToManagedPtr(data))
|
|
|
|
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
|
|
}
|