examples

package
v0.3.9 Latest Latest
Warning

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

Go to latest
Published: Dec 10, 2025 License: Apache-2.0 Imports: 10 Imported by: 0

Documentation

Overview

Package examples 提供 logger 包的使用示例

本目录包含以下示例:

  • http_middleware_example.go: Gin HTTP 中间件使用示例
  • grpc_interceptor_example.go: gRPC 拦截器使用示例
  • gorm_example.go: GORM 日志适配器使用示例
  • redis_example.go: Redis 日志钩子使用示例
  • application_service_example.go: 应用层服务日志使用示例

注意:这些示例文件仅供参考,不会被编译到最终产物中

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func ApplicationServiceLogOutput

func ApplicationServiceLogOutput()

ApplicationServiceLogOutput 说明应用层日志的格式

操作开始日志(Debug 级别):

{
    "level": "debug",
    "ts": "2025-12-10T10:00:00.050Z",
    "msg": "开始创建用户",
    "trace_id": "abc123def456",
    "request_id": "req-001",
    "action": "create",
    "resource": "user",
    "username": "john_doe"
}

操作成功日志(Info 级别):

{
    "level": "info",
    "ts": "2025-12-10T10:00:00.120Z",
    "msg": "用户创建成功",
    "trace_id": "abc123def456",
    "request_id": "req-001",
    "action": "create",
    "resource": "user",
    "resource_id": "user-12345",
    "result": "success"
}

业务错误日志(Warn 级别):

{
    "level": "warn",
    "ts": "2025-12-10T10:00:00.080Z",
    "msg": "用户不存在",
    "trace_id": "abc123def456",
    "request_id": "req-001",
    "action": "read",
    "resource": "user",
    "resource_id": "user-not-found",
    "result": "failed"
}

系统错误日志(Error 级别):

{
    "level": "error",
    "ts": "2025-12-10T10:00:00.090Z",
    "msg": "数据库连接失败",
    "trace_id": "abc123def456",
    "request_id": "req-001",
    "action": "read",
    "resource": "user",
    "error": "connection refused",
    "result": "failed"
}

func DisableRedisLogging

func DisableRedisLogging() *redis.Client

DisableRedisLogging 演示如何禁用日志记录

func GRPCInterceptorOutput

func GRPCInterceptorOutput()

GRPCInterceptorOutput 说明拦截器产生的日志格式

一元调用开始时的日志:

{
    "level": "info",
    "ts": "2025-12-10T10:00:00.000Z",
    "msg": "gRPC request started",
    "event": "request_start",
    "trace_id": "abc123def456",
    "request_id": "req-001",
    "grpc.service": "iam.authn.v1.AuthnService",
    "grpc.method": "Login",
    "grpc.full_method": "/iam.authn.v1.AuthnService/Login",
    "client_ip": "192.168.1.100",
    "request": "{\"app_code\": \"test-app\", \"login_type\": \"wechat\"}"
}

一元调用成功结束时的日志:

{
    "level": "info",
    "ts": "2025-12-10T10:00:00.050Z",
    "msg": "gRPC request completed",
    "event": "request_end",
    "trace_id": "abc123def456",
    "request_id": "req-001",
    "grpc.full_method": "/iam.authn.v1.AuthnService/Login",
    "grpc.code": "OK",
    "duration_ms": 50,
    "result": "success",
    "response": "{\"access_token\": \"eyJ...\", \"expires_in\": 3600}"
}

一元调用失败时的日志:

{
    "level": "error",
    "ts": "2025-12-10T10:00:00.030Z",
    "msg": "gRPC request failed",
    "event": "request_end",
    "trace_id": "abc123def456",
    "request_id": "req-001",
    "grpc.full_method": "/iam.authn.v1.AuthnService/Login",
    "grpc.code": "Unauthenticated",
    "error": "invalid credentials",
    "duration_ms": 30,
    "result": "failed"
}

流式调用日志格式类似,额外包含:

  • is_client_stream: 是否为客户端流
  • is_server_stream: 是否为服务端流

func GormLoggerOutput

func GormLoggerOutput()

GormLoggerOutput 说明 GORM 日志适配器产生的日志格式

正常 SQL 执行日志(Debug 级别):

{
    "level": "debug",
    "ts": "2025-12-10T10:00:00.100Z",
    "msg": "GORM trace",
    "caller": "repository/user_repo.go:45",
    "sql": "SELECT * FROM users WHERE id = ?",
    "elapsed_ms": 5.2,
    "rows": 1,
    "trace_id": "abc123def456",
    "request_id": "req-001"
}

慢查询警告日志:

{
    "level": "warn",
    "ts": "2025-12-10T10:00:00.500Z",
    "msg": "GORM slow query",
    "caller": "repository/user_repo.go:78",
    "sql": "SELECT * FROM orders WHERE user_id = ? AND status IN (?)",
    "elapsed_ms": 350.5,
    "rows": 156,
    "event": "slow_query",
    "slow_threshold": "200ms",
    "trace_id": "abc123def456",
    "request_id": "req-001"
}

SQL 执行错误日志:

{
    "level": "error",
    "ts": "2025-12-10T10:00:00.200Z",
    "msg": "GORM trace failed",
    "caller": "repository/user_repo.go:92",
    "sql": "INSERT INTO users (username, email) VALUES (?, ?)",
    "elapsed_ms": 10.5,
    "rows": 0,
    "error": "Error 1062: Duplicate entry 'john@example.com' for key 'email'",
    "trace_id": "abc123def456",
    "request_id": "req-001"
}

func HTTPMiddlewareOutput

func HTTPMiddlewareOutput()

HTTPMiddlewareOutput 说明中间件产生的日志格式

请求开始时的日志:

{
    "level": "info",
    "ts": "2025-12-10T10:00:00.000Z",
    "msg": "HTTP Request Started",
    "event": "request_start",
    "trace_id": "abc123def456",
    "request_id": "req-001",
    "method": "POST",
    "path": "/v1/users",
    "query": "page=1&size=10",
    "client_ip": "192.168.1.100",
    "user_agent": "Mozilla/5.0...",
    "request_headers": {"Content-Type": "application/json", ...}
}

请求结束时的日志:

{
    "level": "info",
    "ts": "2025-12-10T10:00:00.150Z",
    "msg": "HTTP Request Completed Successfully",
    "event": "request_end",
    "trace_id": "abc123def456",
    "request_id": "req-001",
    "method": "POST",
    "path": "/v1/users",
    "status_code": 201,
    "duration_ms": 150,
    "response_size": 256,
    "request_body": "{\"username\": \"john\", \"password\": \"***\"}",
    "response_body": "{\"id\": \"12345\", \"username\": \"john\"}"
}

func RedisLoggerOutput

func RedisLoggerOutput()

RedisLoggerOutput 说明 Redis 日志钩子产生的日志格式

正常命令执行日志(Debug 级别):

{
    "level": "debug",
    "ts": "2025-12-10T10:00:00.010Z",
    "msg": "Redis command executed",
    "command": "SET user:1:name John",
    "elapsed_ms": 2.5,
    "trace_id": "abc123def456",
    "request_id": "req-001"
}

慢命令警告日志:

{
    "level": "warn",
    "ts": "2025-12-10T10:00:00.300Z",
    "msg": "Redis slow command",
    "command": "KEYS user:*",
    "elapsed_ms": 250.5,
    "event": "slow_command",
    "slow_threshold": "200ms",
    "trace_id": "abc123def456",
    "request_id": "req-001"
}

命令执行错误日志:

{
    "level": "error",
    "ts": "2025-12-10T10:00:00.020Z",
    "msg": "Redis command failed",
    "command": "GET user:1:name",
    "elapsed_ms": 5.0,
    "error": "WRONGTYPE Operation against a key holding the wrong kind of value",
    "trace_id": "abc123def456",
    "request_id": "req-001"
}

管道执行日志:

{
    "level": "debug",
    "ts": "2025-12-10T10:00:00.015Z",
    "msg": "Redis pipeline executed",
    "command_count": 3,
    "commands": "SET, SET, GET",
    "elapsed_ms": 8.0,
    "trace_id": "abc123def456",
    "request_id": "req-001"
}

注意事项:

  • AUTH 和 HELLO 命令的参数会自动脱敏为 ***
  • 超过 100 字符的参数会被截断
  • 超过 500 字符的完整命令会被截断
  • redis.Nil 错误(key 不存在)不会记录为错误

func RedisUsageExample

func RedisUsageExample(client *redis.Client)

RedisUsageExample 演示 Redis 操作时日志的自动记录

func SetupGRPCServer

func SetupGRPCServer() *grpc.Server

SetupGRPCServer 演示如何在 gRPC 服务器中配置日志拦截器

func SetupGRPCServerWithConfig

func SetupGRPCServerWithConfig() *grpc.Server

SetupGRPCServerWithConfig 演示如何使用自定义配置

func SetupGRPCServerWithMultipleInterceptors

func SetupGRPCServerWithMultipleInterceptors() *grpc.Server

SetupGRPCServerWithMultipleInterceptors 演示多拦截器链配置

func SetupGormDynamicLogLevel

func SetupGormDynamicLogLevel(db *gorm.DB)

SetupGormDynamicLogLevel 演示动态调整日志级别

func SetupGormWithCustomConfig

func SetupGormWithCustomConfig() (*gorm.DB, error)

SetupGormWithCustomConfig 演示使用自定义配置

func SetupGormWithLogger

func SetupGormWithLogger() (*gorm.DB, error)

SetupGormWithLogger 演示如何在 GORM 中配置日志适配器

func SetupHTTPMiddleware

func SetupHTTPMiddleware() *gin.Engine

SetupHTTPMiddleware 演示如何在 Gin 中配置 HTTP 日志中间件

func SetupHTTPMiddlewareMinimal

func SetupHTTPMiddlewareMinimal() *gin.Engine

SetupHTTPMiddlewareMinimal 演示最简配置

func SetupRedisCluster

func SetupRedisCluster() *redis.ClusterClient

SetupRedisCluster 演示集群模式下的配置

func SetupRedisWithCustomConfig

func SetupRedisWithCustomConfig() *redis.Client

SetupRedisWithCustomConfig 演示使用自定义配置

func SetupRedisWithLogger

func SetupRedisWithLogger() *redis.Client

SetupRedisWithLogger 演示如何在 Redis 客户端中配置日志钩子

Types

type ApplicationServiceExample

type ApplicationServiceExample struct {
}

ApplicationServiceExample 演示在应用层服务中使用 logger

func (*ApplicationServiceExample) CreateUser

func (s *ApplicationServiceExample) CreateUser(ctx context.Context, username, email string) error

CreateUser 演示创建操作的日志记录

func (*ApplicationServiceExample) DeleteUser

func (s *ApplicationServiceExample) DeleteUser(ctx context.Context, userID string) error

DeleteUser 演示删除操作的日志记录

func (*ApplicationServiceExample) GetUserByID

func (s *ApplicationServiceExample) GetUserByID(ctx context.Context, userID string) error

GetUserByID 演示查询操作的日志记录

func (*ApplicationServiceExample) HandleError

func (s *ApplicationServiceExample) HandleError(ctx context.Context) error

HandleError 演示错误处理时的日志记录

func (*ApplicationServiceExample) Login

func (s *ApplicationServiceExample) Login(ctx context.Context, loginType, appCode string) error

Login 演示认证操作的日志记录

func (*ApplicationServiceExample) ProcessWithSubLogger

func (s *ApplicationServiceExample) ProcessWithSubLogger(ctx context.Context, orderID string) error

ProcessWithSubLogger 演示如何添加额外字段创建子 Logger

func (*ApplicationServiceExample) UpdateUser

func (s *ApplicationServiceExample) UpdateUser(ctx context.Context, userID string, updates map[string]interface{}) error

UpdateUser 演示更新操作的日志记录

Jump to

Keyboard shortcuts

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