talos

Форк
0
/
error_suppress.go 
79 строк · 1.9 Кб
1
// This Source Code Form is subject to the terms of the Mozilla Public
2
// License, v. 2.0. If a copy of the MPL was not distributed with this
3
// file, You can obtain one at http://mozilla.org/MPL/2.0/.
4

5
package logging
6

7
import (
8
	"sync/atomic"
9

10
	"go.uber.org/zap/zapcore"
11
)
12

13
// NewControllerErrorSuppressor creates a new controller error suppressor.
14
//
15
// It suppresses error logs for a given controller unless it logs >= threshold errors.
16
// The idea is that all controllers reconcile errors, so if the error is not transient,
17
// it will be reported enough time to hit the threshold, but transient errors will be
18
// suppressed.
19
//
20
// The suppressor records the controller name by inspecting a log field named "controller"
21
// passed via `logger.With()` call.
22
func NewControllerErrorSuppressor(core zapcore.Core, threshold int64) zapcore.Core {
23
	return &consoleSampler{
24
		Core:      core,
25
		threshold: threshold,
26
	}
27
}
28

29
type consoleSampler struct {
30
	zapcore.Core
31

32
	hits       *atomic.Int64
33
	threshold  int64
34
	controller string
35
}
36

37
var _ zapcore.Core = (*consoleSampler)(nil)
38

39
func (s *consoleSampler) Level() zapcore.Level {
40
	return zapcore.LevelOf(s.Core)
41
}
42

43
func (s *consoleSampler) With(fields []zapcore.Field) zapcore.Core {
44
	controller := s.controller
45
	num := s.hits
46

47
	for _, field := range fields {
48
		if field.Key == "controller" {
49
			if field.String != controller {
50
				controller = field.String
51
				num = new(atomic.Int64)
52
			}
53

54
			break
55
		}
56
	}
57

58
	return &consoleSampler{
59
		threshold:  s.threshold,
60
		controller: controller,
61
		hits:       num,
62
		Core:       s.Core.With(fields),
63
	}
64
}
65

66
func (s *consoleSampler) Check(ent zapcore.Entry, ce *zapcore.CheckedEntry) *zapcore.CheckedEntry {
67
	if !s.Enabled(ent.Level) {
68
		return ce
69
	}
70

71
	if ent.Level == zapcore.ErrorLevel && s.controller != "" {
72
		if s.hits.Add(1) <= s.threshold {
73
			// suppress the log
74
			return ce
75
		}
76
	}
77

78
	return s.Core.Check(ent, ce)
79
}
80

Использование cookies

Мы используем файлы cookie в соответствии с Политикой конфиденциальности и Политикой использования cookies.

Нажимая кнопку «Принимаю», Вы даете АО «СберТех» согласие на обработку Ваших персональных данных в целях совершенствования нашего веб-сайта и Сервиса GitVerse, а также повышения удобства их использования.

Запретить использование cookies Вы можете самостоятельно в настройках Вашего браузера.