code.icb4dc0.de/buildr/wasi-module-sdk-go@v0.0.0-20230524201105-cc52d195017b/logger.go (about)

     1  package sdk
     2  
     3  // #include <stdlib.h>
     4  import "C"
     5  
     6  import (
     7  	"context"
     8  
     9  	"golang.org/x/exp/slog"
    10  
    11  	"code.icb4dc0.de/buildr/wasi-module-sdk-go/mem"
    12  	rpcv1 "code.icb4dc0.de/buildr/wasi-module-sdk-go/protocol/generated/rpc/v1"
    13  )
    14  
    15  var _ slog.Handler = (*WASIHandler)(nil)
    16  
    17  func NewWASIHandler() WASIHandler {
    18  	return WASIHandler{}
    19  }
    20  
    21  type WASIHandler struct {
    22  	Level slog.Level
    23  	attrs []slog.Attr
    24  	group string
    25  }
    26  
    27  func (h WASIHandler) Enabled(_ context.Context, level slog.Level) bool {
    28  	return h.Level <= level
    29  }
    30  
    31  func (h WASIHandler) Handle(ctx context.Context, record slog.Record) error {
    32  	taskLog := rpcv1.TaskLog{
    33  		Time:       record.Time.UnixMicro(),
    34  		Message:    record.Message,
    35  		Level:      int32(record.Level),
    36  		Attributes: make([]*rpcv1.TaskLog_LogAttribute, 0, record.NumAttrs()),
    37  	}
    38  
    39  	record.Attrs(func(attr slog.Attr) bool {
    40  		taskLog.Attributes = append(taskLog.Attributes, &rpcv1.TaskLog_LogAttribute{
    41  			Key:   attr.Key,
    42  			Value: attr.Value.String(),
    43  		})
    44  
    45  		return true
    46  	})
    47  
    48  	data, err := taskLog.MarshalVT()
    49  	if err != nil {
    50  		return err
    51  	}
    52  
    53  	_log_msg(mem.DataToManagedPtr(data))
    54  
    55  	return nil
    56  }
    57  
    58  func (h WASIHandler) WithAttrs(attrs []slog.Attr) slog.Handler {
    59  	newHandler := WASIHandler{
    60  		Level: h.Level,
    61  		attrs: make([]slog.Attr, 0, len(attrs)+len(h.attrs)),
    62  	}
    63  
    64  	newHandler.attrs = append(newHandler.attrs, h.attrs...)
    65  	newHandler.attrs = append(newHandler.attrs, attrs...)
    66  
    67  	return newHandler
    68  }
    69  
    70  func (h WASIHandler) WithGroup(name string) slog.Handler {
    71  	newHandler := WASIHandler{
    72  		Level: h.Level,
    73  		attrs: make([]slog.Attr, len(h.attrs)),
    74  	}
    75  
    76  	copy(newHandler.attrs, h.attrs)
    77  	newHandler.group = name
    78  
    79  	return newHandler
    80  }