zlogger

package
v0.2.3 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Apr 21, 2026 License: MIT Imports: 5 Imported by: 0

Documentation

Overview

Package zlogger 提供 pgx tracelog.Logger 的 zap 适配实现。 支持 Trace ID 注入、慢查询识别、参数化屏蔽(防止日志泄露敏感数据)。

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Logger

type Logger struct {
	// contains filtered or unexported fields
}

Logger 是实现 tracelog.Logger 的 zap 适配器。

func New

func New(opts ...Option) *Logger

New 创建一个 Logger。默认使用 zap.NewNop(),调用方应通过 WithLogger 注入实际 zap 实例。

Example
package main

import (
	"context"
	"fmt"
	"time"

	"github.com/gtkit/pgorm/zlogger"
	"github.com/jackc/pgx/v5/tracelog"
	"go.uber.org/zap"
)

func main() {
	logger := zlogger.New(
		zlogger.WithLogger(zap.NewNop()),
		zlogger.WithSlowThreshold(200*time.Millisecond),
		zlogger.WithParameterizedQueries(true),
		zlogger.WithTraceIDExtractor(func(context.Context) string { return "trace-123" }),
	)

	logger.Log(context.Background(), tracelog.LogLevelInfo, "query", map[string]any{
		"sql":  "SELECT 1",
		"time": 5 * time.Millisecond,
	})

	fmt.Println(logger != nil)
}
Output:
true

func (*Logger) Log

func (l *Logger) Log(
	ctx context.Context,
	level tracelog.LogLevel,
	msg string,
	data map[string]any,
)

Log 实现 tracelog.Logger 接口。

pgx tracelog 的 data 字段里通常包含:sql / args / time / err / pid / rowCount / commandTag 等。我们按 "已知字段显式提取 + 剩余字段透传 zap.Any" 的方式组装日志字段。

func (*Logger) WithTraceIDExtractor added in v0.2.2

func (l *Logger) WithTraceIDExtractor(extractor func(context.Context) string) tracelog.Logger

WithTraceIDExtractor returns a cloned logger with the provided trace extractor. The receiver is not mutated, which allows one logger template to be shared safely across multiple pgorm clients.

type Option

type Option func(*Logger)

Option 配置 Logger。

func WithIncludeRowCount

func WithIncludeRowCount(enabled bool) Option

WithIncludeRowCount 控制是否记录 rowCount 字段,默认开启。

func WithLogger

func WithLogger(logger *zap.Logger) Option

WithLogger 注入实际使用的 *zap.Logger。未设置时使用 zap.NewNop()。

func WithParameterizedQueries

func WithParameterizedQueries(enabled bool) Option

WithParameterizedQueries 开启后 args 字段不会进入日志, 适合生产环境防止日志泄露敏感输入。

func WithSlowThreshold

func WithSlowThreshold(d time.Duration) Option

WithSlowThreshold 设置慢查询阈值。elapsed 超过该值且级别为 Info 时, 日志被提升到 Warn 级别并加上 "pgorm slow query" 说明。<=0 表示禁用慢查询识别。

func WithTraceIDExtractor

func WithTraceIDExtractor(extractor TraceIDExtractor) Option

WithTraceIDExtractor 注入从 context 提取 trace id 的函数。

type TraceIDExtractor

type TraceIDExtractor func(ctx context.Context) string

TraceIDExtractor 从 context 提取 trace/request id。返回空串表示不注入。

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL