github.com/sagernet/gvisor@v0.0.0-20240428053021-e691de28565f/pkg/log/rate_limited.go (about)

     1  // Copyright 2022 The gVisor Authors.
     2  //
     3  // Licensed under the Apache License, Version 2.0 (the "License");
     4  // you may not use this file except in compliance with the License.
     5  // You may obtain a copy of the License at
     6  //
     7  //     http://www.apache.org/licenses/LICENSE-2.0
     8  //
     9  // Unless required by applicable law or agreed to in writing, software
    10  // distributed under the License is distributed on an "AS IS" BASIS,
    11  // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    12  // See the License for the specific language governing permissions and
    13  // limitations under the License.
    14  
    15  package log
    16  
    17  import (
    18  	"time"
    19  
    20  	"golang.org/x/time/rate"
    21  )
    22  
    23  type rateLimitedLogger struct {
    24  	logger Logger
    25  	limit  *rate.Limiter
    26  }
    27  
    28  func (rl *rateLimitedLogger) Debugf(format string, v ...any) {
    29  	if rl.limit.Allow() {
    30  		rl.logger.Debugf(format, v...)
    31  	}
    32  }
    33  
    34  func (rl *rateLimitedLogger) Infof(format string, v ...any) {
    35  	if rl.limit.Allow() {
    36  		rl.logger.Infof(format, v...)
    37  	}
    38  }
    39  
    40  func (rl *rateLimitedLogger) Warningf(format string, v ...any) {
    41  	if rl.limit.Allow() {
    42  		rl.logger.Warningf(format, v...)
    43  	}
    44  }
    45  
    46  func (rl *rateLimitedLogger) IsLogging(level Level) bool {
    47  	return rl.logger.IsLogging(level)
    48  }
    49  
    50  // BasicRateLimitedLogger returns a Logger that logs to the global logger no
    51  // more than once per the provided duration.
    52  func BasicRateLimitedLogger(every time.Duration) Logger {
    53  	return RateLimitedLogger(Log(), every)
    54  }
    55  
    56  // RateLimitedLogger returns a Logger that logs to the provided logger no more
    57  // than once per the provided duration.
    58  func RateLimitedLogger(logger Logger, every time.Duration) Logger {
    59  	return &rateLimitedLogger{
    60  		logger: logger,
    61  		limit:  rate.NewLimiter(rate.Every(every), 1),
    62  	}
    63  }