Skip to content

Commit c8e0d2c

Browse files
committed
added a rate limited writer for klog (#17)
1 parent d604eef commit c8e0d2c

File tree

3 files changed

+18
-1
lines changed

3 files changed

+18
-1
lines changed

go.mod

+1-1
Original file line numberDiff line numberDiff line change
@@ -138,7 +138,7 @@ require (
138138
golang.org/x/exp v0.0.0-20221106115401-f9659909a136 // indirect
139139
golang.org/x/sync v0.1.0 // indirect
140140
golang.org/x/text v0.7.0 // indirect
141-
golang.org/x/time v0.2.0 // indirect
141+
golang.org/x/time v0.3.0 // indirect
142142
google.golang.org/genproto v0.0.0-20230110181048-76db0878b65f // indirect
143143
google.golang.org/grpc v1.53.0 // indirect
144144
google.golang.org/protobuf v1.28.1 // indirect

go.sum

+2
Original file line numberDiff line numberDiff line change
@@ -1211,6 +1211,8 @@ golang.org/x/time v0.0.0-20191024005414-555d28b269f0/go.mod h1:tRJNPiyCQ0inRvYxb
12111211
golang.org/x/time v0.0.0-20200630173020-3af7569d3a1e/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ=
12121212
golang.org/x/time v0.2.0 h1:52I/1L54xyEQAYdtcSuxtiT84KGYTBGXwayxmIpNJhE=
12131213
golang.org/x/time v0.2.0/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ=
1214+
golang.org/x/time v0.3.0 h1:rg5rLMjNzMS1RkNLzCG38eapWhnYLFYXDXj2gOlr8j4=
1215+
golang.org/x/time v0.3.0/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ=
12141216
golang.org/x/tools v0.0.0-20180221164845-07fd8470d635/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
12151217
golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
12161218
golang.org/x/tools v0.0.0-20181030221726-6c7e314b6563/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=

main.go

+15
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@ import (
1111
"github.com/prometheus/client_golang/prometheus/promhttp"
1212
"golang.org/x/mod/semver"
1313
"golang.org/x/sys/unix"
14+
"golang.org/x/time/rate"
1415
"k8s.io/klog/v2"
1516
"net/http"
1617
_ "net/http/pprof"
@@ -74,6 +75,9 @@ func machineID() string {
7475
}
7576

7677
func main() {
78+
klog.LogToStderr(false)
79+
klog.SetOutput(&RateLimitedLogOutput{limiter: rate.NewLimiter(10, 100)})
80+
7781
klog.Infoln("agent version:", version)
7882

7983
hostname, kv, err := uname()
@@ -128,3 +132,14 @@ type logger struct{}
128132
func (l logger) Println(v ...interface{}) {
129133
klog.Errorln(v...)
130134
}
135+
136+
type RateLimitedLogOutput struct {
137+
limiter *rate.Limiter
138+
}
139+
140+
func (o *RateLimitedLogOutput) Write(data []byte) (int, error) {
141+
if !o.limiter.Allow() {
142+
return len(data), nil
143+
}
144+
return os.Stderr.Write(data)
145+
}

0 commit comments

Comments
 (0)