fix: enrich error logs
This commit is contained in:
@@ -10,6 +10,9 @@ import (
|
||||
"github.com/google/uuid"
|
||||
log "github.com/sirupsen/logrus"
|
||||
"gorm.io/gorm"
|
||||
|
||||
"quyun/v2/database/models"
|
||||
"quyun/v2/pkg/consts"
|
||||
)
|
||||
|
||||
// ResponseSender 响应发送器
|
||||
@@ -29,14 +32,14 @@ func (s *ResponseSender) SendError(ctx fiber.Ctx, err error) error {
|
||||
appErr := s.handler.Handle(err)
|
||||
|
||||
// 记录错误日志
|
||||
s.logError(appErr)
|
||||
s.logError(appErr, ctx)
|
||||
|
||||
// 根据 Content-Type 返回不同格式
|
||||
return s.sendResponse(ctx, appErr)
|
||||
}
|
||||
|
||||
// logError 记录错误日志
|
||||
func (s *ResponseSender) logError(appErr *AppError) {
|
||||
func (s *ResponseSender) logError(appErr *AppError, ctx fiber.Ctx) {
|
||||
// 确保每个错误实例都有唯一ID,便于日志关联
|
||||
if appErr.ID == "" {
|
||||
appErr.ID = uuid.NewString()
|
||||
@@ -86,7 +89,18 @@ func (s *ResponseSender) logError(appErr *AppError) {
|
||||
|
||||
root := chain[len(chain)-1]["error"]
|
||||
|
||||
logEntry := log.WithFields(log.Fields{
|
||||
requestID := ctx.Get(fiber.HeaderXRequestID)
|
||||
path := ctx.Path()
|
||||
method := ctx.Method()
|
||||
ua := ctx.Get(fiber.HeaderUserAgent)
|
||||
remoteIP := ctx.IP()
|
||||
query := string(ctx.Request().URI().QueryString())
|
||||
fullPath := path
|
||||
if query != "" {
|
||||
fullPath = fmt.Sprintf("%s?%s", path, query)
|
||||
}
|
||||
|
||||
fields := log.Fields{
|
||||
"id": appErr.ID,
|
||||
"code": appErr.Code,
|
||||
"statusCode": appErr.StatusCode,
|
||||
@@ -95,7 +109,29 @@ func (s *ResponseSender) logError(appErr *AppError) {
|
||||
"params": appErr.params,
|
||||
"error_chain": chain,
|
||||
"root_error": root,
|
||||
})
|
||||
"request_id": requestID,
|
||||
"method": method,
|
||||
"path": path,
|
||||
"full_path": fullPath,
|
||||
"user_agent": ua,
|
||||
"ip": remoteIP,
|
||||
}
|
||||
|
||||
if user := ctx.Locals(consts.CtxKeyUser); user != nil {
|
||||
if model, ok := user.(*models.User); ok {
|
||||
fields["user_id"] = model.ID
|
||||
fields["user_roles"] = model.Roles
|
||||
}
|
||||
}
|
||||
|
||||
if tenant := ctx.Locals(consts.CtxKeyTenant); tenant != nil {
|
||||
if model, ok := tenant.(*models.Tenant); ok {
|
||||
fields["tenant_id"] = model.ID
|
||||
fields["tenant_code"] = model.Code
|
||||
}
|
||||
}
|
||||
|
||||
logEntry := log.WithFields(fields)
|
||||
|
||||
if appErr.originalErr != nil {
|
||||
logEntry = logEntry.WithError(appErr.originalErr)
|
||||
|
||||
Reference in New Issue
Block a user