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 ¶
- func ApplicationServiceLogOutput()
- func DemoAllScenarios()
- func DemoAsyncWorker()
- func DemoBackgroundTask()
- func DemoErrorHandling()
- func DemoModuleLogger()
- func DemoProgramStartup()
- func DemoSystemEvents()
- func DisableRedisLogging() *redis.Client
- func GRPCInterceptorOutput()
- func GormLoggerOutput()
- func HTTPMiddlewareOutput()
- func PerformDatabaseOperations(client *mongo.Client) error
- func RedisLoggerOutput()
- func RedisUsageExample(client *redis.Client)
- func SetupGRPCServer() *grpc.Server
- func SetupGRPCServerWithConfig() *grpc.Server
- func SetupGRPCServerWithMultipleInterceptors() *grpc.Server
- func SetupGormDynamicLogLevel(db *gorm.DB)
- func SetupGormWithCustomConfig() (*gorm.DB, error)
- func SetupGormWithLogger() (*gorm.DB, error)
- func SetupHTTPMiddleware() *gin.Engine
- func SetupHTTPMiddlewareMinimal() *gin.Engine
- func SetupMongoWithAuth(username, password, host, database string) (*mongo.Client, error)
- func SetupMongoWithCustomConfig() (*mongo.Client, error)
- func SetupMongoWithLogger() (*mongo.Client, error)
- func SetupRedisCluster() *redis.ClusterClient
- func SetupRedisWithCustomConfig() *redis.Client
- func SetupRedisWithLogger() *redis.Client
- type ApplicationServiceExample
- func (s *ApplicationServiceExample) CreateUser(ctx context.Context, username, email string) error
- func (s *ApplicationServiceExample) DeleteUser(ctx context.Context, userID string) error
- func (s *ApplicationServiceExample) GetUserByID(ctx context.Context, userID string) error
- func (s *ApplicationServiceExample) HandleError(ctx context.Context) error
- func (s *ApplicationServiceExample) Login(ctx context.Context, loginType, appCode string) error
- func (s *ApplicationServiceExample) ProcessWithSubLogger(ctx context.Context, orderID string) error
- func (s *ApplicationServiceExample) UpdateUser(ctx context.Context, userID string, updates map[string]interface{}) error
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 DemoAsyncWorker ¶ added in v0.4.0
func DemoAsyncWorker()
DemoAsyncWorker 演示独立的 goroutine(无 context)
func DemoBackgroundTask ¶ added in v0.4.0
func DemoBackgroundTask()
DemoBackgroundTask 演示后台任务/定时任务的日志记录
func DemoErrorHandling ¶ added in v0.4.0
func DemoErrorHandling()
DemoErrorHandling 演示错误处理(无 context)
func DemoModuleLogger ¶ added in v0.4.0
func DemoModuleLogger()
DemoModuleLogger 演示模块级别的日志(可以声明为全局变量)
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 PerformDatabaseOperations ¶ added in v0.4.0
PerformDatabaseOperations 演示数据库操作示例
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 ¶
RedisUsageExample 演示 Redis 操作时日志的自动记录
func SetupGRPCServerWithConfig ¶
SetupGRPCServerWithConfig 演示如何使用自定义配置
func SetupGRPCServerWithMultipleInterceptors ¶
SetupGRPCServerWithMultipleInterceptors 演示多拦截器链配置
func SetupGormDynamicLogLevel ¶
SetupGormDynamicLogLevel 演示动态调整日志级别
func SetupGormWithCustomConfig ¶
SetupGormWithCustomConfig 演示使用自定义配置
func SetupGormWithLogger ¶
SetupGormWithLogger 演示如何在 GORM 中配置日志适配器
func SetupHTTPMiddleware ¶
SetupHTTPMiddleware 演示如何在 Gin 中配置 HTTP 日志中间件
func SetupHTTPMiddlewareMinimal ¶
SetupHTTPMiddlewareMinimal 演示最简配置
func SetupMongoWithAuth ¶ added in v0.4.0
SetupMongoWithAuth 演示带认证的 MongoDB 连接
func SetupMongoWithCustomConfig ¶ added in v0.4.0
SetupMongoWithCustomConfig 演示使用自定义配置
func SetupMongoWithLogger ¶ added in v0.4.0
SetupMongoWithLogger 演示如何在 MongoDB 客户端中配置日志钩子
func SetupRedisWithCustomConfig ¶
SetupRedisWithCustomConfig 演示使用自定义配置
func SetupRedisWithLogger ¶
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 演示更新操作的日志记录