-
Notifications
You must be signed in to change notification settings - Fork 18
/
formatencoder.go
172 lines (154 loc) · 5.11 KB
/
formatencoder.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
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
// Copyright 2015 Matthew Holt and The Caddy Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package transformencoder
import (
"fmt"
"strings"
"github.com/buger/jsonparser"
"github.com/caddyserver/caddy/v2"
"github.com/caddyserver/caddy/v2/modules/logging"
"go.uber.org/zap/buffer"
"go.uber.org/zap/zapcore"
)
func init() {
caddy.RegisterModule(TransformEncoder{})
caddy.RegisterModule(compat{})
}
const (
// commonLogFormat is the common log format. https://en.wikipedia.org/wiki/Common_Log_Format
commonLogEmptyValue = "-"
commonLogFormat = `{request>remote_ip} ` + commonLogEmptyValue + ` {user_id} [{ts}] "{request>method} {request>uri} {request>proto}" {status} {size}`
commonLogTimeFormat = "02/Jan/2006:15:04:05 -0700"
commonLogFormatShortcut = `{common_log}`
)
// FormattedEncoder alias is kept for backward compatibility
type FormattedEncoder = TransformEncoder
type compat struct {
TransformEncoder
}
func (we compat) CaddyModule() caddy.ModuleInfo {
return caddy.ModuleInfo{
ID: "caddy.logging.encoders.formatted",
New: func() caddy.Module {
return &TransformEncoder{
Encoder: new(logging.JSONEncoder),
}
},
}
}
// TransformEncoder allows the user to provide custom template for log prints. The
// encoder builds atop the json encoder, thus it follows its message structure. The placeholders
// are namespaced by the name of the app logging the message.
type TransformEncoder struct {
logging.LogEncoderConfig
zapcore.Encoder `json:"-"`
Template string `json:"template,omitempty"`
Placeholder string `json:"placeholder,omitempty"`
UnescapeStrings bool `json:"unescape_strings,omitempty"`
}
func (TransformEncoder) CaddyModule() caddy.ModuleInfo {
return caddy.ModuleInfo{
ID: "caddy.logging.encoders.transform",
New: func() caddy.Module {
return &TransformEncoder{
Encoder: new(logging.JSONEncoder),
}
},
}
}
// Provision sets up the encoder.
func (se *TransformEncoder) Provision(ctx caddy.Context) error {
if se.Template == "" {
return fmt.Errorf("missing template for formatted log encoder")
}
if se.Template == commonLogFormatShortcut {
se.Template = commonLogFormat
}
if se.Template == commonLogFormat {
se.TimeFormat = commonLogTimeFormat
}
if se.Placeholder == "" {
se.Placeholder = commonLogEmptyValue
}
se.Encoder = zapcore.NewJSONEncoder(se.ZapcoreEncoderConfig())
return nil
}
// Clone wraps the underlying encoder's Clone. This is
// necessary because we implement our own EncodeEntry,
// and if we simply let the embedded encoder's Clone
// be promoted, it would return a clone of that, and
// we'd lose our TransformEncoder's EncodeEntry.
func (se TransformEncoder) Clone() zapcore.Encoder {
return TransformEncoder{
LogEncoderConfig: se.LogEncoderConfig,
Encoder: se.Encoder.Clone(),
Template: se.Template,
Placeholder: se.Placeholder,
UnescapeStrings: se.UnescapeStrings,
}
}
// EncodeEntry partially implements the zapcore.Encoder interface.
func (se TransformEncoder) EncodeEntry(ent zapcore.Entry, fields []zapcore.Field) (*buffer.Buffer, error) {
repl := caddy.NewReplacer()
buf, err := se.Encoder.EncodeEntry(ent, fields)
if err != nil {
return buf, err
}
repl.Map(func(key string) (interface{}, bool) {
if strings.Contains(key, ":") {
for _, slice := range strings.Split(key, ":") {
val, found := getValue(buf, slice, se.UnescapeStrings)
if found {
return val, found
}
}
// No match found.
return nil, false
}
return getValue(buf, key, se.UnescapeStrings)
})
out := repl.ReplaceAll(se.Template, se.Placeholder)
// The buffer is only used to find the values of placeholders.
// The content has served its purpose. It's time for it to go to repurpose the buffer.
buf.Reset()
// Unescape escaped quotes
buf.AppendString(strings.Replace(out, `\"`, `"`, -1))
if !strings.HasSuffix(out, "\n") {
buf.AppendByte('\n')
}
return buf, err
}
func getValue(buf *buffer.Buffer, key string, unescapeStrings bool) (interface{}, bool) {
path := strings.Split(key, ">")
value, dataType, _, err := jsonparser.Get(buf.Bytes(), path...)
if err != nil {
return nil, false
}
switch dataType {
case jsonparser.NotExist:
return nil, false
case jsonparser.String:
if !unescapeStrings {
return value, true
}
str, _ := jsonparser.ParseString(value)
return str, true
case jsonparser.Array, jsonparser.Boolean, jsonparser.Null, jsonparser.Number, jsonparser.Object, jsonparser.Unknown:
// if a value exists, return it as is. A byte is a byte is a byte. The replacer handles them just fine.
return value, true
default:
return nil, false
}
}
var _ caddy.Module = (*TransformEncoder)(nil)