2 回答
TA贡献1840条经验 获得超5个赞
您可以添加一个挂钩。为每个日志记录事件评估挂钩
https://go.dev/play/p/Q7doafJGaeE
package main
import (
"os"
"github.com/rs/zerolog"
)
type IntHook struct {
Count int
}
func (h *IntHook) Run(e *zerolog.Event, l zerolog.Level, msg string) {
e.Int("count", h.Count)
h.Count++
}
func main() {
var intHook IntHook
log := zerolog.New(os.Stdout).Hook(&intHook)
log.Info().Msg("hello world")
log.Info().Msg("hello world one more time")
}
输出是
{"level":"info","count":0,"message":"hello world"}
{"level":"info","count":1,"message":"hello world one more time"}
需要Count在调用之间保存指针Hook.Run
可能对你HookFunc来说更好一些。它是为每个事件调用的无状态函数。以下是为每条消息调用 PRNG 的函数挂钩示例:https ://go.dev/play/p/xu6aXpUmE0v
package main
import (
"math/rand"
"os"
"github.com/rs/zerolog"
)
func RandomHook(e *zerolog.Event, l zerolog.Level, msg string) {
e.Int("random", rand.Intn(100))
}
func main() {
var randomHook zerolog.HookFunc = RandomHook
log := zerolog.New(os.Stdout).Hook(randomHook)
log.Info().Msg("hello world")
log.Info().Msg("hello world one more time")
}
输出
{"level":"info","random":81,"message":"hello world"}
{"level":"info","random":87,"message":"hello world one more time"}
TA贡献2039条经验 获得超7个赞
您可以使用zerolog Hook来实现这一点。挂钩是带有Run方法的接口,该方法在将事件数据写入给定io.Writer(在您的情况下os.Stderr)之前被调用。
这是一些示例代码:
type counter struct {
name string
value int32
}
func (c *counter) inc() { atomic.AddInt32(&c.value, 1) }
func (c *counter) dec() { atomic.AddInt32(&c.value, -1) }
func (c *counter) get() { atomic.LoadInt32(&c.value) }
func (c *counter) Run(e *zerolog.Event, _ zerolog.Level, _ string) {
e.Int32(c.name, c.get())
}
int main() {
numConsumers, numProducers := 3, 3
consumersRunning := &counter{
name: "consumersRunning",
value: int32(numConsumers),
}
producersRunning := &counter{
name: "producersRunning",
value: int32(numProducers),
}
logger := zerolog.New(os.Stderr)
consumerLogger := logger.With().Str("is", "consumer").Logger().Hook(consumersRunning)
producerLogger := logger.With().Str("is", "producer").Logger().Hook(producersRunning)
// your other code
}
您将使用计数器的inc和dec方法来修改运行的消费者/生产者的数量。
- 2 回答
- 0 关注
- 97 浏览
添加回答
举报