File: logrus.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 (84 lines) | stat: -rw-r--r-- 2,266 bytes parent folder | download | duplicates (2)
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
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
// 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.

//go:build !disable_events

// Package logrus provides a logrus Formatter for events.
// To use for the global logger:
//
//	logrus.SetFormatter(elogrus.NewFormatter(exporter))
//	logrus.SetOutput(io.Discard)
//
// and for a Logger instance:
//
//	logger.SetFormatter(elogrus.NewFormatter(exporter))
//	logger.SetOutput(io.Discard)
//
// If you call elogging.SetExporter, then you can pass nil
// for the exporter above and it will use the global one.
package logrus

import (
	"context"

	"github.com/sirupsen/logrus"
	"golang.org/x/exp/event"
	"golang.org/x/exp/event/severity"
)

type formatter struct{}

func NewFormatter() logrus.Formatter {
	return &formatter{}
}

var _ logrus.Formatter = (*formatter)(nil)

// Format writes an entry to an event.Exporter. It always returns nil (see below).
// If e.Context is non-nil, Format gets the exporter from the context. Otherwise
// it uses the default exporter.
//
// Logrus first calls the Formatter to get a []byte, then writes that to the
// output. That doesn't work for events, so we subvert it by having the
// Formatter export the event (and thereby write it). That is why the logrus
// Output io.Writer should be set to io.Discard.
func (f *formatter) Format(e *logrus.Entry) ([]byte, error) {
	ctx := e.Context
	if ctx == nil {
		ctx = context.Background()
	}
	ev := event.New(ctx, event.LogKind)
	if ev == nil {
		return nil, nil
	}
	ev.At = e.Time
	ev.Labels = append(ev.Labels, convertLevel(e.Level).Label())
	for k, v := range e.Data {
		ev.Labels = append(ev.Labels, event.Value(k, v))
	}
	ev.Labels = append(ev.Labels, event.String("msg", e.Message))
	ev.Deliver()
	return nil, nil
}

func convertLevel(level logrus.Level) severity.Level {
	switch level {
	case logrus.PanicLevel:
		return severity.Fatal + 1
	case logrus.FatalLevel:
		return severity.Fatal
	case logrus.ErrorLevel:
		return severity.Error
	case logrus.WarnLevel:
		return severity.Warning
	case logrus.InfoLevel:
		return severity.Info
	case logrus.DebugLevel:
		return severity.Debug
	case logrus.TraceLevel:
		return severity.Trace
	default:
		return severity.Trace
	}
}