Logging Starter

简介

Logging Starter 为 Hiboot 应用程序提供结构化日志记录功能。它支持多种日志级别和格式化器,可通过 YAML 配置轻松配置。

安装

在应用程序中导入 logging starter:

import "github.com/hidevopsio/hiboot/pkg/starter/logging"

配置

application.yml 中启用日志:

app:
  profiles:
    include:
    - logging

logging:
  level: info

或通过代码启用:

package main

import (
	"github.com/hidevopsio/hiboot/pkg/app"
	"github.com/hidevopsio/hiboot/pkg/app/web"
	"github.com/hidevopsio/hiboot/pkg/starter/logging"
)

func main() {
	web.NewApplication().
		SetProperty(app.ProfilesInclude, logging.Profile).
		Run()
}

基本用法

使用 log 包进行日志记录:

package service

import (
	"github.com/hidevopsio/hiboot/pkg/log"
)

type UserService struct{}

func (s *UserService) GetUser(id uint64) (*User, error) {
	log.Infof("获取用户 ID: %d", id)

	user, err := s.repository.FindById(id)
	if err != nil {
		log.Errorf("获取用户 %d 失败: %v", id, err)
		return nil, err
	}

	log.Debugf("找到用户: %+v", user)
	return user, nil
}

日志级别

级别 描述 方法
debug 详细的调试信息 log.Debug(), log.Debugf()
info 一般操作信息 log.Info(), log.Infof()
warn 警告信息 log.Warn(), log.Warnf()
error 错误条件 log.Error(), log.Errorf()
fatal 严重错误(退出应用) log.Fatal(), log.Fatalf()

设置日志级别

application.yml 中:

logging:
  level: debug  # debug, info, warn, error, fatal

日志方法

基本日志

log.Debug("调试信息")
log.Info("信息")
log.Warn("警告信息")
log.Error("错误信息")

格式化日志

log.Debugf("用户 %s 从 %s 登录", username, ip)
log.Infof("处理请求 %d", requestId)
log.Warnf("内存使用率过高: %d%%", memoryPercent)
log.Errorf("数据库错误: %v", err)

带字段的日志

log.WithFields(log.Fields{
	"user_id":    123,
	"request_id": "abc-123",
	"action":     "login",
}).Info("用户操作已记录")

环境特定配置

开发环境

# application-dev.yml
logging:
  level: debug

生产环境

# application-prod.yml
logging:
  level: info

控制器日志示例

package controller

import (
	"github.com/hidevopsio/hiboot/pkg/app"
	"github.com/hidevopsio/hiboot/pkg/at"
	"github.com/hidevopsio/hiboot/pkg/log"
	"github.com/hidevopsio/hiboot/pkg/model"
)

type userController struct {
	at.RestController
	at.RequestMapping `value:"/user"`
}

func init() {
	app.Register(newUserController)
}

func newUserController() *userController {
	return &userController{}
}

func (c *userController) Post(request *CreateUserRequest) (model.Response, error) {
	log.Infof("创建用户: %s", request.Username)

	// 业务逻辑
	user, err := createUser(request)
	if err != nil {
		log.Errorf("创建用户失败: %v", err)
		response := new(model.BaseResponse)
		response.SetCode(500)
		response.SetMessage("创建用户失败")
		return response, nil
	}

	log.Infof("用户创建成功: ID=%d", user.Id)

	response := new(model.BaseResponse)
	response.SetData(user)
	return response, nil
}

服务日志示例

package service

import (
	"github.com/hidevopsio/hiboot/pkg/app"
	"github.com/hidevopsio/hiboot/pkg/log"
)

type OrderService interface {
	ProcessOrder(orderId uint64) error
}

type orderServiceImpl struct {
	repository OrderRepository
}

func init() {
	app.Register(newOrderService)
}

func newOrderService(repository OrderRepository) OrderService {
	return &orderServiceImpl{
		repository: repository,
	}
}

func (s *orderServiceImpl) ProcessOrder(orderId uint64) error {
	log.WithFields(log.Fields{
		"order_id": orderId,
		"action":   "process_start",
	}).Info("开始处理订单")

	order, err := s.repository.FindById(orderId)
	if err != nil {
		log.WithFields(log.Fields{
			"order_id": orderId,
			"error":    err.Error(),
		}).Error("获取订单失败")
		return err
	}

	// 处理订单...
	log.WithFields(log.Fields{
		"order_id": orderId,
		"status":   order.Status,
	}).Debug("订单状态已更新")

	log.WithFields(log.Fields{
		"order_id": orderId,
		"action":   "process_complete",
	}).Info("订单处理完成")

	return nil
}

最佳实践

  1. 使用适当的日志级别:使用 debug 记录开发细节,info 记录操作事件,warn 记录潜在问题,error 记录失败
  2. 包含上下文:始终在日志消息中包含相关 ID(user_id、request_id、order_id)
  3. 避免记录敏感数据:永远不要记录密码、令牌或个人数据
  4. 使用结构化日志:使用 log.WithFields() 生成可机器解析的日志
  5. 保持一致:在整个应用程序中使用一致的消息格式

配置参考

属性 描述 默认值
logging.level 日志级别(debug、info、warn、error、fatal) info

下一步