1 // Package logutils augments the standard log package with levels.
12 // LevelFilter is an io.Writer that can be used with a logger that
13 // will filter out log messages that aren't at least a certain level.
15 // Once the filter is in use somewhere, it is not safe to modify
17 type LevelFilter struct {
18 // Levels is the list of log levels, in increasing order of
19 // severity. Example might be: {"DEBUG", "WARN", "ERROR"}.
22 // MinLevel is the minimum level allowed through
25 // The underlying io.Writer where log messages that pass the filter
29 badLevels map[LogLevel]struct{}
33 // Check will check a given line if it would be included in the level
35 func (f *LevelFilter) Check(line []byte) bool {
38 // Check for a log level
40 x := bytes.IndexByte(line, '[')
42 y := bytes.IndexByte(line[x:], ']')
44 level = LogLevel(line[x+1 : x+y])
48 _, ok := f.badLevels[level]
52 func (f *LevelFilter) Write(p []byte) (n int, err error) {
53 // Note in general that io.Writer can receive any byte sequence
54 // to write, but the "log" package always guarantees that we only
55 // get a single line. We use that as a slight optimization within
56 // this method, assuming we're dealing with a single, complete line
63 return f.Writer.Write(p)
66 // SetMinLevel is used to update the minimum log level
67 func (f *LevelFilter) SetMinLevel(min LogLevel) {
72 func (f *LevelFilter) init() {
73 badLevels := make(map[LogLevel]struct{})
74 for _, level := range f.Levels {
75 if level == f.MinLevel {
78 badLevels[level] = struct{}{}
80 f.badLevels = badLevels