cloudflare/cloudflared

Public

mirrored from https://github.com/cloudflare/cloudflaredAvailable

CodeCommitsIssuesPull requestsActionsInsightsSecurity
2019.2.0

Branches

Tags

  • No tags available.
0Branches0Tags
Go to file
Add file
Code

Clone

HTTPS

Download ZIP

log/log.go

85lines · modeblame

d06fc520Areg Harutyunyan8 years ago1// this forks the logrus json formatter to rename msg -> message as that's the
2// expected field. Ideally the logger should make it easier for us.
3package log
4
5import (
6"encoding/json"
7"fmt"
8"runtime"
9"time"
10
11"github.com/mattn/go-colorable"
12"github.com/sirupsen/logrus"
13)
14
15var (
a9c8067cAreg Harutyunyan7 years ago16DefaultTimestampFormat = time.RFC3339Nano
d06fc520Areg Harutyunyan8 years ago17)
18
19type JSONFormatter struct {
20// TimestampFormat sets the format used for marshaling timestamps.
21TimestampFormat string
22}
23
24func CreateLogger() *logrus.Logger {
25logger := logrus.New()
26logger.Out = colorable.NewColorableStderr()
27logger.Formatter = &logrus.TextFormatter{ForceColors: runtime.GOOS == "windows"}
28return logger
29}
30
31func (f *JSONFormatter) Format(entry *logrus.Entry) ([]byte, error) {
32data := make(logrus.Fields, len(entry.Data)+3)
33for k, v := range entry.Data {
34switch v := v.(type) {
35case error:
36// Otherwise errors are ignored by `encoding/json`
37// https://github.com/sirupsen/logrus/issues/137
38data[k] = v.Error()
39default:
40data[k] = v
41}
42}
43prefixFieldClashes(data)
44
45timestampFormat := f.TimestampFormat
46if timestampFormat == "" {
47timestampFormat = DefaultTimestampFormat
48}
49
50data["time"] = entry.Time.Format(timestampFormat)
51data["message"] = entry.Message
52data["level"] = entry.Level.String()
53
54serialized, err := json.Marshal(data)
55if err != nil {
56return nil, fmt.Errorf("Failed to marshal fields to JSON, %v", err)
57}
58return append(serialized, '\n'), nil
59}
60
61// This is to not silently overwrite `time`, `msg` and `level` fields when
62// dumping it. If this code wasn't there doing:
63//
64// logrus.WithField("level", 1).Info("hello")
65//
66// Would just silently drop the user provided level. Instead with this code
67// it'll logged as:
68//
69// {"level": "info", "fields.level": 1, "msg": "hello", "time": "..."}
70//
71// It's not exported because it's still using Data in an opinionated way. It's to
72// avoid code duplication between the two default formatters.
73func prefixFieldClashes(data logrus.Fields) {
74if t, ok := data["time"]; ok {
75data["fields.time"] = t
76}
77
78if m, ok := data["msg"]; ok {
79data["fields.msg"] = m
80}
81
82if l, ok := data["level"]; ok {
83data["fields.level"] = l
84}
85}