package telemetry
import (
"context"
"os"
"regexp"
"strings"
"github.com/ic2hrmk/promtail"
ssam "github.com/pancsta/asyncmachine-go/pkg/states"
am "github.com/pancsta/asyncmachine-go/pkg/machine"
)
const (
EnvService = "AM_SERVICE"
EnvLokiAddr = "AM_LOKI_ADDR"
EnvOtelTrace = "AM_OTEL_TRACE"
EnvOtelTraceTxs = "AM_OTEL_TRACE_TXS"
EnvOtelTraceArgs = "AM_OTEL_TRACE_ARGS"
EnvOtelTraceNoauto = "AM_OTEL_TRACE_NOAUTO"
)
func BindLokiLogger (mach am .Api , client promtail .Client ) {
labels := map [string ]string {
"asyncmachine_id" : mach .Id (),
}
mach .SemLogger ().EnableId (false )
amlog := func (level am .LogLevel , msg string , args ...any ) {
if strings .HasPrefix (msg , "[error" ) {
client .LogfWithLabels (promtail .Error , labels , msg , args ...)
} else {
switch level {
case am .LogChanges :
client .LogfWithLabels (promtail .Info , labels , msg , args ...)
case am .LogOps :
client .LogfWithLabels (promtail .Info , labels , msg , args ...)
case am .LogDecisions :
client .LogfWithLabels (promtail .Debug , labels , msg , args ...)
case am .LogEverything :
client .LogfWithLabels (promtail .Debug , labels , msg , args ...)
default :
}
}
}
mach .SemLogger ().SetLogger (amlog )
mach .Log ("[bind] loki logger" )
}
var normalizeRegexp = regexp .MustCompile ("[^a-z_0-9]+" )
func NormalizeId (id string ) string {
return normalizeRegexp .ReplaceAllString (strings .ToLower (id ), "_" )
}
func BindLokiEnv (mach am .Api ) error {
service := os .Getenv (EnvService )
addr := os .Getenv (EnvLokiAddr )
if service == "" || addr == "" {
return nil
}
identifiers := map [string ]string {
"service_name" : NormalizeId (service ),
}
pt , err := promtail .NewJSONv1Client (addr , identifiers )
if err != nil {
return err
}
var dispose am .HandlerDispose = func (id string , _ context .Context ) {
pt .Close ()
}
register := ssam .DisposedStates .RegisterDisposal
if mach .Has1 (register ) {
mach .Add1 (register , am .A {
ssam .DisposedArgHandler : dispose ,
})
} else {
func () {
<-mach .WhenDisposed ()
pt .Close ()
}()
}
BindLokiLogger (mach , pt )
return nil
}
The pages are generated with Golds v0.8.2 . (GOOS=linux GOARCH=amd64)
Golds is a Go 101 project developed by Tapir Liu .
PR and bug reports are welcome and can be submitted to the issue list .
Please follow @zigo_101 (reachable from the left QR code) to get the latest news of Golds .