瀏覽代碼

Display timestamp in log and allow logging to file

Brendan Abolivier 7 年之前
父節點
當前提交
a2a4945542
簽署人: Brendan Abolivier <contact@brendanabolivier.com> GPG 金鑰 ID: 8EF1500759F70623
共有 2 個檔案被更改,包括 47 行新增0 行删除
  1. 42
    0
      src/metrics-alerting/log.go
  2. 5
    0
      src/metrics-alerting/main.go

+ 42
- 0
src/metrics-alerting/log.go 查看文件

@@ -0,0 +1,42 @@
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 查看文件

@@ -14,11 +14,16 @@ import (
14 14
 
15 15
 var (
16 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 20
 func main() {
20 21
 	flag.Parse()
21 22
 
23
+	if err := logConfig(); err != nil {
24
+		logrus.Warn(err)
25
+	}
26
+
22 27
 	cfg := config.Config{}
23 28
 	if err := cfg.Load(*configPath); err != nil {
24 29
 		logrus.Panic(err)