添加运行模式配置,优化调试和生产环境的日志输出

This commit is contained in:
2025-05-07 19:03:44 +08:00
parent 0a16f9923c
commit 0e0affb008
5 changed files with 61 additions and 11 deletions

11
pkg/env/env.go vendored
View File

@@ -13,6 +13,7 @@ import (
var (
AppName = "platform"
RunMode = "debug" // debug, production
)
func loadApp() {
@@ -20,6 +21,16 @@ func loadApp() {
if _AppName != "" {
AppName = _AppName
}
_RunMode := os.Getenv("RUN_MODE")
switch _RunMode {
case "debug", "production":
RunMode = _RunMode
case "":
break
default:
panic("环境变量 RUN_MODE 的值只能是 debug 或 production")
}
}
// endregion

View File

@@ -1,19 +1,24 @@
package logs
import (
"github.com/lmittmann/tint"
"log/slog"
"os"
"platform/pkg/env"
"time"
"github.com/lmittmann/tint"
)
func Init() {
slog.SetDefault(slog.New(
tint.NewHandler(os.Stdout, &tint.Options{
var writer = os.Stdout
var timeFormat = "2006-01-02 15:04:05"
var handler slog.Handler
switch env.RunMode {
case "debug":
handler = tint.NewHandler(writer, &tint.Options{
AddSource: true,
Level: env.LogLevel,
TimeFormat: time.Kitchen,
TimeFormat: timeFormat,
ReplaceAttr: func(_ []string, attr slog.Attr) slog.Attr {
err, ok := attr.Value.Any().(error)
if ok {
@@ -21,6 +26,19 @@ func Init() {
}
return attr
},
}),
))
})
case "production":
handler = slog.NewJSONHandler(writer, &slog.HandlerOptions{
AddSource: false,
Level: env.LogLevel,
ReplaceAttr: func(_ []string, a slog.Attr) slog.Attr {
if a.Key == "time" {
return slog.String("time", a.Value.Time().Format(timeFormat))
}
return a
},
})
}
slog.SetDefault(slog.New(handler))
}

View File

@@ -66,6 +66,11 @@ func Protect(c *fiber.Ctx, types []services.PayloadType, permissions []string) (
return nil, fiber.NewError(fiber.StatusForbidden, "没有权限")
}
// 保存到上下文
c.Locals("auth", auth)
c.Locals("authid", auth.Payload.Id)
c.Locals("authtype", auth.Payload.Type.Name())
return auth, nil
}

View File

@@ -237,6 +237,20 @@ const (
PayloadClientConfidential
)
func (t PayloadType) Name() string {
switch t {
case PayloadUser:
return "user"
case PayloadAdmin:
return "admn"
case PayloadClientPublic:
return "cpub"
case PayloadClientConfidential:
return "ccnf"
}
return "unknown"
}
type Agent struct {
Id int32 `json:"id,omitempty"`
Addr string `json:"addr,omitempty"`

View File

@@ -51,15 +51,17 @@ func (s *Server) Run() error {
ErrorHandler: ErrorHandler,
})
s.fiber.Use(logger.New(logger.Config{
DisableColors: false,
}))
s.fiber.Use(requestid.New(requestid.Config{
Generator: func() string {
binary, _ := uuid.New().MarshalBinary()
return base62.EncodeToString(binary)
},
}))
s.fiber.Use(logger.New(logger.Config{
Format: "🚀 ${time} | ${locals:authtype} ${locals:authid} | ${method} ${path} | ${status} | ${latency} | ${error}\n",
TimeFormat: "2006-01-02 15:04:05",
TimeZone: "Asia/Shanghai",
}))
ApplyRouters(s.fiber)