Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions .env.example
Original file line number Diff line number Diff line change
@@ -1,6 +1,10 @@
# App
APP_PORT=8080
# production:日誌輸出結構化 JSON(讓集中式日誌平台能把 ride_id、duration_ms 當欄位查詢)
# 其他值:輸出人類可讀的彩色文字,方便本機開發
APP_ENV=local
# 日誌級別 trace/debug/info/warn/error;排查時可臨時調 debug,不必改程式重新部署
LOG_LEVEL=info

# PostgreSQL
DB_HOST=postgis
Expand Down
1 change: 1 addition & 0 deletions .github/workflows/go-ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,7 @@ jobs:
# 只跑純單元包+service 中明確不碰 DB 的測試名。
run: |
CGO_ENABLED=0 go test -count=1 -timeout 60s \
./cmd/server/ \
./internal/auth/ \
./internal/config/ \
./internal/constants/ \
Expand Down
32 changes: 31 additions & 1 deletion cmd/server/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package main
import (
"context"
"fmt"
"io"
"os"
"os/signal"
"syscall"
Expand All @@ -29,7 +30,6 @@ import (

func main() {
zerolog.TimeFieldFormat = zerolog.TimeFormatUnix
log.Logger = log.Output(zerolog.ConsoleWriter{Out: os.Stdout, TimeFormat: time.RFC3339})

if len(os.Args) > 1 && os.Args[1] == "migrate" {
runMigrateOnly()
Expand All @@ -40,6 +40,7 @@ func main() {
if err != nil {
log.Fatal().Err(err).Msg("載入設定失敗")
}
setupLogger(cfg)

if err := database.RunMigrations(cfg.MigrateDSN(), "db/migrations"); err != nil {
log.Fatal().Err(err).Msg("資料庫 migration 失敗")
Expand Down Expand Up @@ -174,6 +175,8 @@ func main() {
}

r := gin.New()
// RequestLogger 放最外層,讓 panic 被 Recovery 接住後仍記得到那筆 500。
r.Use(middleware.RequestLogger())
r.Use(gin.Recovery())
r.Use(middleware.CORS())

Expand Down Expand Up @@ -365,6 +368,33 @@ func main() {
log.Info().Msg("收到關閉信號,正在停止...")
}

// newLogger 依環境組出 logger。
//
// production 走 zerolog 的 JSON 輸出,讓 ride_id、duration_ms 這類欄位在集中式日誌平台
// 可被當成結構化欄位查詢;本機開發才換成人類可讀的 ConsoleWriter。
// 先前無條件套用 ConsoleWriter,等於把結構化欄位重新攤平回字串,上線後只能全文比對。
//
// 輸出目標以參數傳入而非寫死 os.Stdout,是為了讓測試能斷言實際輸出的格式。
func newLogger(cfg *config.Config, out io.Writer) zerolog.Logger {
if cfg.AppEnv != "production" {
out = zerolog.ConsoleWriter{Out: out, TimeFormat: time.RFC3339}
}
return zerolog.New(out).With().Timestamp().Logger()
}

// setupLogger 套用 logger 與日誌級別。
// LOG_LEVEL 可在不改程式的情況下臨時調高細節(如 debug),排查完再調回。
func setupLogger(cfg *config.Config) {
log.Logger = newLogger(cfg, os.Stdout)

lvl, err := zerolog.ParseLevel(cfg.LogLevel)
if err != nil || lvl == zerolog.NoLevel {
log.Warn().Str("log_level", cfg.LogLevel).Msg("LOG_LEVEL 無法解析,退回 info")
lvl = zerolog.InfoLevel
}
zerolog.SetGlobalLevel(lvl)
}

func runMigrateOnly() {
cfg, err := config.Load()
if err != nil {
Expand Down
92 changes: 92 additions & 0 deletions cmd/server/main_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,92 @@
package main

import (
"bytes"
"encoding/json"
"testing"

"github.com/rs/zerolog"

"line-fleet-dispatch/internal/config"
)

func TestNewLogger_ProductionOutputsStructuredJSON(t *testing.T) {
buf := &bytes.Buffer{}
lg := newLogger(&config.Config{AppEnv: "production"}, buf)

lg.Info().Int64("ride_id", 42).Int64("duration_ms", 137).Msg("已派單")

var m map[string]any
if err := json.Unmarshal(bytes.TrimSpace(buf.Bytes()), &m); err != nil {
t.Fatalf("production 應輸出合法 JSON,實得:%s", buf.String())
}
// 重點不是「有輸出」,而是欄位仍是獨立的、可被日誌平台當條件查詢。
if m["ride_id"] != float64(42) {
t.Fatalf("ride_id 應為獨立欄位,實得:%v", m)
}
if m["duration_ms"] != float64(137) {
t.Fatalf("duration_ms 應為獨立欄位,實得:%v", m)
}
if m["message"] != "已派單" {
t.Fatalf("message 欄位不正確:%v", m)
}
if _, ok := m["time"]; !ok {
t.Fatalf("缺少 time 欄位,日誌平台無法排序:%v", m)
}
}

func TestNewLogger_NonProductionIsHumanReadable(t *testing.T) {
for _, env := range []string{"local", "staging", ""} {
t.Run("env="+env, func(t *testing.T) {
buf := &bytes.Buffer{}
lg := newLogger(&config.Config{AppEnv: env}, buf)

lg.Info().Int64("ride_id", 42).Msg("已派單")

var m map[string]any
if err := json.Unmarshal(bytes.TrimSpace(buf.Bytes()), &m); err == nil {
t.Fatalf("非 production 預期為人類可讀格式,卻是 JSON:%s", buf.String())
}
if !bytes.Contains(buf.Bytes(), []byte("已派單")) {
t.Fatalf("輸出應含訊息本文,實得:%s", buf.String())
}
})
}
}

func TestSetupLogger_LevelFiltering(t *testing.T) {
origLevel := zerolog.GlobalLevel()
t.Cleanup(func() { zerolog.SetGlobalLevel(origLevel) })

setupLogger(&config.Config{AppEnv: "production", LogLevel: "error"})
if got := zerolog.GlobalLevel(); got != zerolog.ErrorLevel {
t.Fatalf("LOG_LEVEL=error 應套用 error 級別,實得 %s", got)
}

// 用獨立 buffer 驗證過濾真的生效(全域級別對所有 logger 一體適用)。
buf := &bytes.Buffer{}
lg := newLogger(&config.Config{AppEnv: "production"}, buf)

lg.Info().Msg("這筆應被過濾")
if buf.Len() != 0 {
t.Fatalf("info 不應輸出,實得:%s", buf.String())
}

// 校準:同一條斷言路徑在 error 級別確實寫得出來,
// 證明上面的空值是被級別擋掉,而不是 logger 根本沒接上 buffer。
lg.Error().Msg("這筆應輸出")
if buf.Len() == 0 {
t.Fatal("校準失敗:error 級別也沒有輸出,前一項斷言不具意義")
}
}

func TestSetupLogger_InvalidLevelFallsBackToInfo(t *testing.T) {
origLevel := zerolog.GlobalLevel()
t.Cleanup(func() { zerolog.SetGlobalLevel(origLevel) })

setupLogger(&config.Config{AppEnv: "production", LogLevel: "not-a-level"})

if got := zerolog.GlobalLevel(); got != zerolog.InfoLevel {
t.Fatalf("無法解析的 LOG_LEVEL 應退回 info,實得 %s", got)
}
}
4 changes: 4 additions & 0 deletions internal/config/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,9 @@ import (
type Config struct {
AppPort int
AppEnv string
// LogLevel zerolog 級別(trace/debug/info/warn/error)。production 常態走 info,
// 排查時可臨時調 debug 而不必改程式重新部署。
LogLevel string

DBHost string
DBPort int
Expand Down Expand Up @@ -60,6 +63,7 @@ func Load() (*Config, error) {
cfg := &Config{
AppPort: getEnvInt("APP_PORT", 8080),
AppEnv: getEnv("APP_ENV", "local"),
LogLevel: getEnv("LOG_LEVEL", "info"),
DBHost: getEnv("DB_HOST", "localhost"),
DBPort: getEnvInt("DB_PORT", 5432),
DBName: getEnv("DB_NAME", "fleet"),
Expand Down
95 changes: 95 additions & 0 deletions internal/middleware/request_log.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,95 @@
package middleware

import (
"crypto/rand"
"encoding/hex"
"net/http"
"time"

"github.com/gin-gonic/gin"
"github.com/rs/zerolog/log"
)

// CtxRequestID 存放本次請求的識別碼
const CtxRequestID = "request_id"

// HeaderRequestID 請求識別碼的傳遞標頭。上游若已帶入則沿用,讓同一條鏈路跨服務仍是同一個 id。
const HeaderRequestID = "X-Request-Id"

// skipAccessLog 不記 access log 的路徑。/healthz 由容器健康檢查每幾秒打一次,
// 記下來只會把真正有價值的請求洗掉。
var skipAccessLog = map[string]bool{
"/healthz": true,
}

// RequestLogger 產生 request_id 並記錄每筆 HTTP 請求的結果與耗時。
//
// 沒有這層時,API 變慢或回 5xx 只剩業務層零星的 log,無從得知是哪支端點、花了多久、
// 回了什麼狀態碼——連「先量測再優化」的第一步都做不到。
//
// request_id 同時寫回應標頭,使用者回報問題時可直接拿它對到這筆 access log。
// 注意:業務層目前仍使用全域 logger,其 log 尚未自動帶上 request_id,
// 跨層關聯目前靠業務鍵(多數 log 已帶 ride_id)。
func RequestLogger() gin.HandlerFunc {
return func(c *gin.Context) {
rid := c.GetHeader(HeaderRequestID)
if rid == "" {
rid = newRequestID()
}
c.Set(CtxRequestID, rid)
c.Header(HeaderRequestID, rid)

start := time.Now()
c.Next()

if skipAccessLog[c.Request.URL.Path] {
return
}

status := c.Writer.Status()
// 未寫任何 body 時 gin 回 -1,log 裡出現負數位元組數只會讓讀的人困惑。
size := c.Writer.Size()
if size < 0 {
size = 0
}

ev := log.Info()
switch {
case status >= http.StatusInternalServerError:
// 5xx 是伺服器自己的問題,一定要有人看。
ev = log.Error()
case status >= http.StatusBadRequest:
// 4xx 多半是呼叫端的問題,但突然變多通常代表某端串接壞了。
ev = log.Warn()
}

ev.Str("request_id", rid).
Str("method", c.Request.Method).
Str("path", c.Request.URL.Path).
Int("status", status).
Int64("duration_ms", time.Since(start).Milliseconds()).
Str("client_ip", c.ClientIP()).
Int("bytes", size).
Msg("http request")
}
}

// RequestIDFromCtx 取出中介層放入的 request_id,沒有則回空字串
func RequestIDFromCtx(c *gin.Context) string {
if v, ok := c.Get(CtxRequestID); ok {
if s, ok := v.(string); ok {
return s
}
}
return ""
}

// newRequestID 產生 16 字元隨機 id。取亂數失敗時退回時間戳,
// 讓 access log 一定有識別碼可寫,不因此中斷請求。
func newRequestID() string {
b := make([]byte, 8)
if _, err := rand.Read(b); err != nil {
return "ts" + time.Now().Format("20060102150405.000")
}
return hex.EncodeToString(b)
}
Loading
Loading