2023-03-28 18:39:22 +00:00
|
|
|
// Copyright (c) HashiCorp, Inc.
|
|
|
|
// SPDX-License-Identifier: MPL-2.0
|
|
|
|
|
2022-12-15 17:52:48 +00:00
|
|
|
package logdrop
|
|
|
|
|
|
|
|
import (
|
|
|
|
"context"
|
2023-01-06 18:33:53 +00:00
|
|
|
|
2022-12-15 17:52:48 +00:00
|
|
|
"github.com/hashicorp/go-hclog"
|
|
|
|
)
|
|
|
|
|
2023-01-06 18:33:53 +00:00
|
|
|
// Logger mimic the interface from hclog.Logger
|
2022-12-15 17:52:48 +00:00
|
|
|
//
|
2023-01-06 18:33:53 +00:00
|
|
|
//go:generate mockery --name Logger --inpackage
|
|
|
|
type Logger interface {
|
|
|
|
Log(level hclog.Level, msg string, args ...interface{})
|
2022-12-15 17:52:48 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
type Log struct {
|
|
|
|
s string
|
|
|
|
i []interface{}
|
|
|
|
l hclog.Level
|
|
|
|
}
|
|
|
|
|
|
|
|
type logDropSink struct {
|
2023-01-06 18:33:53 +00:00
|
|
|
logger Logger
|
2022-12-15 17:52:48 +00:00
|
|
|
logCh chan Log
|
|
|
|
dropFn func(l Log)
|
|
|
|
}
|
|
|
|
|
|
|
|
// Accept consume a log and push it into a channel,
|
|
|
|
// if the channel is filled it will call dropFn
|
2023-01-06 18:33:53 +00:00
|
|
|
func (r *logDropSink) Accept(_ string, level hclog.Level, msg string, args ...interface{}) {
|
|
|
|
r.pushLog(Log{l: level, s: msg, i: args})
|
2022-12-15 17:52:48 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
func (r *logDropSink) pushLog(l Log) {
|
|
|
|
select {
|
|
|
|
case r.logCh <- l:
|
|
|
|
default:
|
|
|
|
r.dropFn(l)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
func (r *logDropSink) logConsumer(ctx context.Context) {
|
|
|
|
for {
|
|
|
|
select {
|
|
|
|
case l := <-r.logCh:
|
2023-01-06 18:33:53 +00:00
|
|
|
r.logger.Log(l.l, l.s, l.i...)
|
2022-12-15 17:52:48 +00:00
|
|
|
case <-ctx.Done():
|
|
|
|
return
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2023-01-06 18:33:53 +00:00
|
|
|
// NewLogDropSink create a log Logger that wrap another Logger
|
2022-12-15 17:52:48 +00:00
|
|
|
// It also create a go routine for consuming logs, the given context need to be canceled
|
2023-01-06 18:33:53 +00:00
|
|
|
// to properly deallocate the Logger.
|
|
|
|
func NewLogDropSink(ctx context.Context, depth int, logger Logger, dropFn func(l Log)) hclog.SinkAdapter {
|
2022-12-15 17:52:48 +00:00
|
|
|
r := &logDropSink{
|
2023-01-06 18:33:53 +00:00
|
|
|
logger: logger,
|
2022-12-15 17:52:48 +00:00
|
|
|
logCh: make(chan Log, depth),
|
|
|
|
dropFn: dropFn,
|
|
|
|
}
|
|
|
|
go r.logConsumer(ctx)
|
|
|
|
return r
|
|
|
|
}
|