-
Notifications
You must be signed in to change notification settings - Fork 781
/
logging.go
98 lines (81 loc) · 2.6 KB
/
logging.go
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
85
86
87
88
89
90
91
92
93
94
95
96
97
98
package logging
import (
"fmt"
"io"
"io/ioutil"
"log"
"strings"
"time"
gsyslog "github.com/hashicorp/go-syslog"
"github.com/hashicorp/logutils"
)
// Levels are the log levels we respond to=o.
var Levels = []logutils.LogLevel{"TRACE", "DEBUG", "INFO", "WARN", "ERR"}
type logWriter struct {
}
// writer to output date / time in a standard format
func (writer logWriter) Write(bytes []byte) (int, error) {
return fmt.Print(time.Now().Format("2006-01-02T15:04:05.000Z0700") + " " + string(bytes))
}
// Config is the configuration for this log setup.
type Config struct {
// Level is the log level to use.
Level string `json:"level"`
// Syslog and SyslogFacility are the syslog configuration options.
Syslog bool `json:"syslog"`
SyslogFacility string `json:"syslog_facility"`
// SyslogName is the progname as it will appear in syslog output (if enabled).
SyslogName string `json:"name"`
// Writer is the output where logs should go. If syslog is enabled, data will
// be written to writer in addition to syslog.
Writer io.Writer `json:"-"`
}
func Setup(config *Config) error {
var logOutput io.Writer
log.SetFlags(0)
log.SetOutput(new(logWriter))
// Setup the default logging
logFilter := NewLogFilter()
logFilter.MinLevel = logutils.LogLevel(strings.ToUpper(config.Level))
logFilter.Writer = config.Writer
if !ValidateLevelFilter(logFilter.MinLevel, logFilter) {
levels := make([]string, 0, len(logFilter.Levels))
for _, level := range logFilter.Levels {
levels = append(levels, string(level))
}
return fmt.Errorf("invalid log level %q, valid log levels are %s",
config.Level, strings.Join(levels, ", "))
}
// Check if syslog is enabled
if config.Syslog {
log.Printf("[DEBUG] (logging) enabling syslog on %s", config.SyslogFacility)
l, err := gsyslog.NewLogger(gsyslog.LOG_NOTICE, config.SyslogFacility, config.SyslogName)
if err != nil {
return fmt.Errorf("error setting up syslog logger: %s", err)
}
syslog := &SyslogWrapper{l, logFilter}
logOutput = io.MultiWriter(logFilter, syslog)
} else {
logOutput = io.MultiWriter(logFilter)
}
log.SetOutput(logOutput)
return nil
}
// NewLogFilter returns a LevelFilter that is configured with the log levels that
// we use.
func NewLogFilter() *logutils.LevelFilter {
return &logutils.LevelFilter{
Levels: Levels,
MinLevel: "WARN",
Writer: ioutil.Discard,
}
}
// ValidateLevelFilter verifies that the log levels within the filter are valid.
func ValidateLevelFilter(min logutils.LogLevel, filter *logutils.LevelFilter) bool {
for _, level := range filter.Levels {
if level == min {
return true
}
}
return false
}