Browse Source

Display timestamp in log and allow logging to file

Brendan Abolivier 7 years ago
parent
commit
a2a4945542
Signed by: Brendan Abolivier <contact@brendanabolivier.com> GPG key ID: 8EF1500759F70623
2 changed files with 47 additions and 0 deletions
  1. 42
    0
      src/metrics-alerting/log.go
  2. 5
    0
      src/metrics-alerting/main.go

+ 42
- 0
src/metrics-alerting/log.go View File

1
+package main
2
+
3
+import (
4
+	"os"
5
+
6
+	"github.com/sirupsen/logrus"
7
+)
8
+
9
+type utcFormatter struct {
10
+	logrus.Formatter
11
+}
12
+
13
+func (f utcFormatter) Format(entry *logrus.Entry) ([]byte, error) {
14
+	entry.Time = entry.Time.UTC()
15
+	return f.Formatter.Format(entry)
16
+}
17
+
18
+func logConfig() error {
19
+	var disableColors = false
20
+
21
+	if len(*logFile) > 0 {
22
+		f, err := os.OpenFile(*logFile, os.O_WRONLY|os.O_CREATE, 0755)
23
+		if err != nil {
24
+			return err
25
+		}
26
+		logrus.SetOutput(f)
27
+
28
+		disableColors = true
29
+	}
30
+
31
+	logrus.SetFormatter(&utcFormatter{
32
+		&logrus.TextFormatter{
33
+			TimestampFormat:  "2006-01-02T15:04:05.000000000Z07:00",
34
+			FullTimestamp:    true,
35
+			DisableColors:    disableColors,
36
+			DisableTimestamp: false,
37
+			DisableSorting:   false,
38
+		},
39
+	})
40
+
41
+	return nil
42
+}

+ 5
- 0
src/metrics-alerting/main.go View File

14
 
14
 
15
 var (
15
 var (
16
 	configPath = flag.String("config", "config.yaml", "The path to the config file. For more information, see the config file in this repository.")
16
 	configPath = flag.String("config", "config.yaml", "The path to the config file. For more information, see the config file in this repository.")
17
+	logFile    = flag.String("log-file", "", "The path to the file logs should be directed to. If empty or not provided, logs will be output through standard output.")
17
 )
18
 )
18
 
19
 
19
 func main() {
20
 func main() {
20
 	flag.Parse()
21
 	flag.Parse()
21
 
22
 
23
+	if err := logConfig(); err != nil {
24
+		logrus.Warn(err)
25
+	}
26
+
22
 	cfg := config.Config{}
27
 	cfg := config.Config{}
23
 	if err := cfg.Load(*configPath); err != nil {
28
 	if err := cfg.Load(*configPath); err != nil {
24
 		logrus.Panic(err)
29
 		logrus.Panic(err)