summaryrefslogtreecommitdiff
path: root/internal/logger/logger.go
blob: 3608574a3421b77acdeed61e837439104bb5b78e (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
package logger

import (
	"io/ioutil"
	"log/syslog"
	"os"

	log "github.com/sirupsen/logrus"
	"gitlab.com/gitlab-org/gitlab-shell/internal/config"
)

func configureLogFormat(cfg *config.Config) {
	if cfg.LogFormat == "json" {
		log.SetFormatter(&log.JSONFormatter{})
	}
}

// Configure configures the logging singleton for operation inside a remote TTY (like SSH). In this
// mode an empty LogFile is not accepted and syslog is used as a fallback when LogFile could not be
// opened for writing.
func Configure(cfg *config.Config) {
	logFile, err := os.OpenFile(cfg.LogFile, os.O_WRONLY|os.O_APPEND|os.O_CREATE, 0644)
	if err != nil {
		progName, _ := os.Executable()
		syslogLogger, sysLogErr := syslog.NewLogger(syslog.LOG_ERR|syslog.LOG_USER, 0)
		if sysLogErr != nil {
			syslogLogger.Print(progName + ": Unable to configure logging: " + err.Error())
		}

		// Discard logs since a log file was specified but couldn't be opened
		log.SetOutput(ioutil.Discard)
	}

	log.SetOutput(logFile)

	configureLogFormat(cfg)
}

// ConfigureStandalone configures the logging singleton for standalone operation. In this mode an
// empty LogFile is treated as logging to standard output and standard output is used as a fallback
// when LogFile could not be opened for writing.
func ConfigureStandalone(cfg *config.Config) {
	if cfg.LogFile == "" {
		return
	}

	logFile, err := os.OpenFile(cfg.LogFile, os.O_WRONLY|os.O_APPEND|os.O_CREATE, 0644)
	if err != nil {
		log.Printf("Unable to configure logging, falling back to stdout: %v", err)
		return
	}
	log.SetOutput(logFile)

	configureLogFormat(cfg)
}