summaryrefslogtreecommitdiff
path: root/workhorse/logging.go
blob: 69718e6e834cdd0fbdc5591f0470979f6b13be4f (plain)
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
package main

import (
	"fmt"
	"io"
	"io/ioutil"
	goLog "log"
	"os"

	log "github.com/sirupsen/logrus"
	logkit "gitlab.com/gitlab-org/labkit/log"
)

const (
	jsonLogFormat    = "json"
	textLogFormat    = "text"
	structuredFormat = "structured"
	noneLogType      = "none"
)

func startLogging(file string, format string) (io.Closer, error) {
	// Golog always goes to stderr
	goLog.SetOutput(os.Stderr)

	if file == "" {
		file = "stderr"
	}

	switch format {
	case noneLogType:
		return logkit.Initialize(logkit.WithWriter(ioutil.Discard))
	case jsonLogFormat:
		return logkit.Initialize(
			logkit.WithOutputName(file),
			logkit.WithFormatter("json"),
		)
	case textLogFormat:
		// In this mode, default (non-access) logs will always go to stderr
		return logkit.Initialize(
			logkit.WithOutputName("stderr"),
			logkit.WithFormatter("text"),
		)
	case structuredFormat:
		return logkit.Initialize(
			logkit.WithOutputName(file),
			logkit.WithFormatter("color"),
		)
	}

	return nil, fmt.Errorf("unknown logFormat: %v", format)
}

// In text format, we use a separate logger for access logs
func getAccessLogger(file string, format string) (*log.Logger, io.Closer, error) {
	if format != "text" {
		return log.StandardLogger(), ioutil.NopCloser(nil), nil
	}

	if file == "" {
		file = "stderr"
	}

	accessLogger := log.New()
	accessLogger.SetLevel(log.InfoLevel)
	closer, err := logkit.Initialize(
		logkit.WithLogger(accessLogger),  // Configure `accessLogger`
		logkit.WithFormatter("combined"), // Use the combined formatter
		logkit.WithOutputName(file),
	)

	return accessLogger, closer, err
}