increase_level.go 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  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. package zapcore
  21. import "fmt"
  22. type levelFilterCore struct {
  23. core Core
  24. level LevelEnabler
  25. }
  26. // NewIncreaseLevelCore creates a core that can be used to increase the level of
  27. // an existing Core. It cannot be used to decrease the logging level, as it acts
  28. // as a filter before calling the underlying core. If level decreases the log level,
  29. // an error is returned.
  30. func NewIncreaseLevelCore(core Core, level LevelEnabler) (Core, error) {
  31. for l := _maxLevel; l >= _minLevel; l-- {
  32. if !core.Enabled(l) && level.Enabled(l) {
  33. return nil, fmt.Errorf("invalid increase level, as level %q is allowed by increased level, but not by existing core", l)
  34. }
  35. }
  36. return &levelFilterCore{core, level}, nil
  37. }
  38. func (c *levelFilterCore) Enabled(lvl Level) bool {
  39. return c.level.Enabled(lvl)
  40. }
  41. func (c *levelFilterCore) With(fields []Field) Core {
  42. return &levelFilterCore{c.core.With(fields), c.level}
  43. }
  44. func (c *levelFilterCore) Check(ent Entry, ce *CheckedEntry) *CheckedEntry {
  45. if !c.Enabled(ent.Level) {
  46. return ce
  47. }
  48. return c.core.Check(ent, ce)
  49. }
  50. func (c *levelFilterCore) Write(ent Entry, fields []Field) error {
  51. return c.core.Write(ent, fields)
  52. }
  53. func (c *levelFilterCore) Sync() error {
  54. return c.core.Sync()
  55. }