runner_formatter.go 2.15 KB
Newer Older
1
package log
2 3 4 5 6 7

import (
	"bytes"
	"fmt"
	"sort"

8
	"github.com/sirupsen/logrus"
9

10
	"gitlab.com/gitlab-org/gitlab-runner/helpers"
11 12 13 14 15 16 17 18 19 20 21 22 23
)

type RunnerTextFormatter struct {
	// Force disabling colors.
	DisableColors bool

	// The fields are sorted by default for a consistent output. For applications
	// that log extremely frequently and don't use the JSON formatter this may not
	// be desired.
	DisableSorting bool
}

func (f *RunnerTextFormatter) Format(entry *logrus.Entry) ([]byte, error) {
24 25
	b := new(bytes.Buffer)
	f.printColored(b, entry)
26
	b.WriteByte('\n')
27

28 29 30
	return b.Bytes(), nil
}

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
func (f *RunnerTextFormatter) printColored(b *bytes.Buffer, entry *logrus.Entry) {
	levelColor, resetColor, levelPrefix := f.getColorsAndPrefix(entry)
	indentLength := 50 - len(levelPrefix)

	fmt.Fprintf(b, "%s%s%-*s%s ", levelColor, levelPrefix, indentLength, entry.Message, resetColor)
	for _, k := range f.prepareKeys(entry) {
		v := entry.Data[k]
		fmt.Fprintf(b, " %s%s%s=%v", levelColor, k, resetColor, v)
	}
}

func (f *RunnerTextFormatter) getColorsAndPrefix(entry *logrus.Entry) (string, string, string) {
	definitions := map[logrus.Level]struct {
		color  string
		prefix string
	}{
		logrus.DebugLevel: {
			color: helpers.ANSI_BOLD_WHITE,
		},
		logrus.WarnLevel: {
			color:  helpers.ANSI_YELLOW,
			prefix: "WARNING: ",
		},
		logrus.ErrorLevel: {
			color:  helpers.ANSI_BOLD_RED,
			prefix: "ERROR: ",
		},
		logrus.FatalLevel: {
			color:  helpers.ANSI_BOLD_RED,
			prefix: "FATAL: ",
		},
		logrus.PanicLevel: {
			color:  helpers.ANSI_BOLD_RED,
			prefix: "PANIC: ",
		},
66 67
	}

68 69 70 71 72 73 74 75 76 77 78 79 80
	color := ""
	prefix := ""

	definition, ok := definitions[entry.Level]
	if ok {
		if definition.color != "" {
			color = definition.color
		}

		if definition.prefix != "" {
			prefix = definition.prefix
		}
	}
81 82

	if f.DisableColors {
83
		return "", "", prefix
84 85
	}

86 87
	return color, helpers.ANSI_RESET, prefix
}
88

89 90 91 92 93
func (f *RunnerTextFormatter) prepareKeys(entry *logrus.Entry) []string {
	keys := make([]string, 0, len(entry.Data))

	for k := range entry.Data {
		keys = append(keys, k)
94
	}
95 96 97 98 99 100

	if !f.DisableSorting {
		sort.Strings(keys)
	}

	return keys
101 102 103
}

func SetRunnerFormatter() {
104
	logrus.SetFormatter(new(RunnerTextFormatter))
105
}