liuxiaolong
2020-09-16 4501e38ca66f09b35aaaf43fa5a316554930fcf4
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
// Package logutils augments the standard log package with levels.
package logutils
 
import (
    "bytes"
    "io"
    "sync"
)
 
type LogLevel string
 
// LevelFilter is an io.Writer that can be used with a logger that
// will filter out log messages that aren't at least a certain level.
//
// Once the filter is in use somewhere, it is not safe to modify
// the structure.
type LevelFilter struct {
    // Levels is the list of log levels, in increasing order of
    // severity. Example might be: {"DEBUG", "WARN", "ERROR"}.
    Levels []LogLevel
 
    // MinLevel is the minimum level allowed through
    MinLevel LogLevel
 
    // The underlying io.Writer where log messages that pass the filter
    // will be set.
    Writer io.Writer
 
    badLevels map[LogLevel]struct{}
    once      sync.Once
}
 
// Check will check a given line if it would be included in the level
// filter.
func (f *LevelFilter) Check(line []byte) bool {
    f.once.Do(f.init)
 
    // Check for a log level
    var level LogLevel
    x := bytes.IndexByte(line, '[')
    if x >= 0 {
        y := bytes.IndexByte(line[x:], ']')
        if y >= 0 {
            level = LogLevel(line[x+1 : x+y])
        }
    }
 
    _, ok := f.badLevels[level]
    return !ok
}
 
func (f *LevelFilter) Write(p []byte) (n int, err error) {
    // Note in general that io.Writer can receive any byte sequence
    // to write, but the "log" package always guarantees that we only
    // get a single line. We use that as a slight optimization within
    // this method, assuming we're dealing with a single, complete line
    // of log data.
 
    if !f.Check(p) {
        return len(p), nil
    }
 
    return f.Writer.Write(p)
}
 
// SetMinLevel is used to update the minimum log level
func (f *LevelFilter) SetMinLevel(min LogLevel) {
    f.MinLevel = min
    f.init()
}
 
func (f *LevelFilter) init() {
    badLevels := make(map[LogLevel]struct{})
    for _, level := range f.Levels {
        if level == f.MinLevel {
            break
        }
        badLevels[level] = struct{}{}
    }
    f.badLevels = badLevels
}