登录
首页 >  Golang >  Go问答

在 Uber Zap go 中隐藏敏感字段

来源:stackoverflow

时间:2024-03-16 13:27:26 224浏览 收藏

在使用 Uber Zap Go 记录日志时,为了保护敏感信息,可以采用以下方法进行隐藏: 1. **自定义类型实现字符串接口:**为敏感字段定义自定义类型并实现 Stringer 接口,使其在打印时显示指定的掩码字符(如 "****")。 2. **自定义编码器:**实现自己的编码器版本,并在 encodeEntry 函数中根据字段名称或类型过滤要隐藏的字段。

问题内容

有什么方法可以在使用 ubergo zap 时隐藏敏感字段的记录。

如果有人能举个例子,我将不胜感激


正确答案


您可以使这些字段自定义类型并实现 stringer 接口,以便它们打印 ****。例如:

type x string

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

将打印 msg {"x": "***"}

或者您可以实现您自己的 encoder 版本,您可以在 encodeentry(ent entry, fields []field) 函数中按名称或类型 interface 过滤字段。您可以采用两个现有编码器之一(console 或 json)作为基础。例如:

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))
}

这将打印

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

以上就是《在 Uber Zap go 中隐藏敏感字段》的详细内容,更多关于的资料请关注golang学习网公众号!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>