-
Notifications
You must be signed in to change notification settings - Fork 0
/
redactrus.go
67 lines (56 loc) · 1.97 KB
/
redactrus.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
package redactrus
import (
"github.com/sirupsen/logrus"
)
// RedactionFunc type for functions that redact sensitive information
type RedactionFunc func(string, string) string
// RedactingFormatter struct that embeds logrus.Formatter and includes redaction functions
type RedactingFormatter struct {
InnerFormatter logrus.Formatter
Redactors []RedactionFunc
RedactWith string
}
// NewRedactingFormatter creates a new RedactingFormatter
func NewRedactingFormatter(innerFormatter logrus.Formatter) *RedactingFormatter {
return &RedactingFormatter{
InnerFormatter: innerFormatter,
Redactors: []RedactionFunc{},
RedactWith: "",
}
}
// defaultRedactors creates a new RedactingFormatter with default redactors
func NewDefaultRedactingFormatter(innerFormatter logrus.Formatter) *RedactingFormatter {
return &RedactingFormatter{
InnerFormatter: innerFormatter,
Redactors: defaultRedactors(),
RedactWith: "[REDACTED]",
}
}
// AddRedactor adds a new redaction function to the RedactingFormatter
func (f *RedactingFormatter) AddRedactor(redactor RedactionFunc) *RedactingFormatter {
f.Redactors = append(f.Redactors, redactor)
return f
}
// AddRedactors adds multiple redaction functions to the RedactingFormatter
func (f *RedactingFormatter) AddRedactors(redactors ...RedactionFunc) *RedactingFormatter {
f.Redactors = append(f.Redactors, redactors...)
return f
}
// Format method for RedactingFormatter
func (f *RedactingFormatter) Format(entry *logrus.Entry) ([]byte, error) {
originalBytes, err := f.InnerFormatter.Format(entry)
if err != nil {
return nil, err
}
originalMsg := string(originalBytes)
// Apply each redaction function to the log message
for _, redactor := range f.Redactors {
originalMsg = redactor(originalMsg, f.RedactWith)
}
return []byte(originalMsg), nil
}
// SetRedactWith sets the string to redact sensitive information with
func (f *RedactingFormatter) SetRedactWith(r string) *RedactingFormatter {
f.RedactWith = r
return f
}