File: gokit.go

package info (click to toggle)
golang-golang-x-exp 0.0~git20231006.7918f67-2
  • links: PTS, VCS
  • area: main
  • in suites: experimental, forky, sid, trixie
  • size: 6,492 kB
  • sloc: ansic: 1,900; objc: 276; sh: 272; asm: 48; makefile: 27
file content (53 lines) | stat: -rw-r--r-- 1,223 bytes parent folder | download | duplicates (4)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
// Copyright 2021 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

// Package gokit provides a go-kit logger for events.
package gokit

import (
	"context"
	"fmt"

	"github.com/go-kit/kit/log"
	"golang.org/x/exp/event"
)

type logger struct {
}

// NewLogger returns a logger.
func NewLogger() log.Logger {
	return &logger{}
}

// Log writes a structured log message.
// If the first argument is a context.Context, it is used
// to find the exporter to which to deliver the message.
// Otherwise, the default exporter is used.
func (l *logger) Log(keyvals ...interface{}) error {
	ctx := context.Background()
	if len(keyvals) > 0 {
		if c, ok := keyvals[0].(context.Context); ok {
			ctx = c
			keyvals = keyvals[1:]
		}
	}
	ev := event.New(ctx, event.LogKind)
	if ev == nil {
		return nil
	}
	var msg string
	for i := 0; i < len(keyvals); i += 2 {
		key := keyvals[i].(string)
		value := keyvals[i+1]
		if key == "msg" || key == "message" {
			msg = fmt.Sprint(value)
		} else {
			ev.Labels = append(ev.Labels, event.Value(key, value))
		}
	}
	ev.Labels = append(ev.Labels, event.String("msg", msg))
	ev.Deliver()
	return nil
}