简体   繁体   English

隐藏 Uber Zap go 中的敏感字段

[英]Hide sensitive fields in Uber Zap go

Is there any way in which I can hide logging sensitive fields while using ubergo zap.有什么方法可以在使用 ubergo zap 时隐藏日志记录敏感字段。

Will appreciate if somebody can show an example如果有人可以举个例子,将不胜感激

You can make those fields custom type and implement Stringer interface for them printing **** .您可以将这些字段设为自定义类型并为它们实现 Stringer 接口以打印**** For example:例如:

type X string

func (x X) String() string {
    return "***"
}
func main() {
    x := X("aaaaa")
    log.Infow("msg", "x", x)
}

will print msg {"x": "***"} .将打印msg {"x": "***"}

Or you can implement your own version of Encoder where you would filter fields by name or their type Interface in EncodeEntry(ent Entry, fields []Field) function.或者您可以实现自己的Encoder版本,您可以在EncodeEntry(ent Entry, fields []Field) function 中按名称或其类型Interface过滤字段。 You can take one of the two existing encoders - console or json - as a base.您可以将现有的两个编码器之一 - 控制台或 json - 作为基础。 For example:例如:

package main

import (
    "go.uber.org/zap"
    "go.uber.org/zap/buffer"
    "go.uber.org/zap/zapcore"
)

type MyEncoder struct {
    zapcore.Encoder
}

func (m *MyEncoder) EncodeEntry(entry zapcore.Entry, fields []zapcore.Field) (*buffer.Buffer, error) {
    filtered := make([]zapcore.Field, 0, len(fields))
    for _, field := range fields {
        if field.Key == "skip" || field.Type == zapcore.Int64Type {
            continue
        }
        filtered = append(filtered, field)
    }
    return m.Encoder.EncodeEntry(entry, filtered)
}

func main() {
    _ = zap.RegisterEncoder("mine", func(config zapcore.EncoderConfig) (zapcore.Encoder, error) {
        encoder := zapcore.NewConsoleEncoder(config)
        return &MyEncoder{encoder}, nil
    })
    config := zap.NewDevelopmentConfig()
    config.Encoding = "mine"
    log, _ := config.Build()
    sugar := log.Sugar()
    sugar.Infow("Some message", "skip", "skipped", "notskip", "present", "alsoskipping", int64(1))
}

This will print这将打印

2022-08-24T13:25:54.368+0200    INFO    testl/main.go:33        Some message    {"notskip": "present"}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM