khenaidoo | 106c61a | 2021-08-11 18:05:46 -0400 | [diff] [blame] | 1 | // Copyright (c) 2020 Uber Technologies, Inc. |
| 2 | // |
| 3 | // Permission is hereby granted, free of charge, to any person obtaining a copy |
| 4 | // of this software and associated documentation files (the "Software"), to deal |
| 5 | // in the Software without restriction, including without limitation the rights |
| 6 | // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell |
| 7 | // copies of the Software, and to permit persons to whom the Software is |
| 8 | // furnished to do so, subject to the following conditions: |
| 9 | // |
| 10 | // The above copyright notice and this permission notice shall be included in |
| 11 | // all copies or substantial portions of the Software. |
| 12 | // |
| 13 | // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR |
| 14 | // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, |
| 15 | // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE |
| 16 | // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER |
| 17 | // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, |
| 18 | // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN |
| 19 | // THE SOFTWARE. |
| 20 | |
| 21 | package zapcore |
| 22 | |
| 23 | import "fmt" |
| 24 | |
| 25 | type levelFilterCore struct { |
| 26 | core Core |
| 27 | level LevelEnabler |
| 28 | } |
| 29 | |
| 30 | // NewIncreaseLevelCore creates a core that can be used to increase the level of |
| 31 | // an existing Core. It cannot be used to decrease the logging level, as it acts |
| 32 | // as a filter before calling the underlying core. If level decreases the log level, |
| 33 | // an error is returned. |
| 34 | func NewIncreaseLevelCore(core Core, level LevelEnabler) (Core, error) { |
| 35 | for l := _maxLevel; l >= _minLevel; l-- { |
| 36 | if !core.Enabled(l) && level.Enabled(l) { |
| 37 | return nil, fmt.Errorf("invalid increase level, as level %q is allowed by increased level, but not by existing core", l) |
| 38 | } |
| 39 | } |
| 40 | |
| 41 | return &levelFilterCore{core, level}, nil |
| 42 | } |
| 43 | |
| 44 | func (c *levelFilterCore) Enabled(lvl Level) bool { |
| 45 | return c.level.Enabled(lvl) |
| 46 | } |
| 47 | |
| 48 | func (c *levelFilterCore) With(fields []Field) Core { |
| 49 | return &levelFilterCore{c.core.With(fields), c.level} |
| 50 | } |
| 51 | |
| 52 | func (c *levelFilterCore) Check(ent Entry, ce *CheckedEntry) *CheckedEntry { |
| 53 | if !c.Enabled(ent.Level) { |
| 54 | return ce |
| 55 | } |
| 56 | |
| 57 | return c.core.Check(ent, ce) |
| 58 | } |
| 59 | |
| 60 | func (c *levelFilterCore) Write(ent Entry, fields []Field) error { |
| 61 | return c.core.Write(ent, fields) |
| 62 | } |
| 63 | |
| 64 | func (c *levelFilterCore) Sync() error { |
| 65 | return c.core.Sync() |
| 66 | } |