Logger
core.ILogger — same name/verbs as v1, backed by the standard library's log/slog. Structured logging with msg, key, value, … arguments.
From a context (recommended)
ctx.Log() returns a logger that automatically tags each line with the request's request_id (and trace attributes when present):
go
ctx.Log().Info("user created", "user_id", id, "email", email)
ctx.Log().Warn("retrying", "attempt", n)
ctx.Log().Error("charge failed", "err", err, "order_id", orderID)Log กับ Sentry เป็นระบบเดียวกัน
เมื่อตั้ง APP_SENTRY_DSN แล้ว ทุกบรรทัดที่ log ผ่าน context จะ:
- กลายเป็น breadcrumb ของ request/run นั้น (category มาจาก attr
componentถ้ามี) - และถ้าบรรทัดนั้นพก error ที่ status ≥ 500 ไว้ใต้ key
err/error→ กลายเป็น event ด้วย
go
log := ctx.Log().With("component", "billing")
log.Info("เริ่มตัดบัตร", "order_id", id) // breadcrumb
log.Error("ดึงเรตไม่ได้", "err", err) // breadcrumb + event (ถ้า err เป็น 5xx)จึงไม่ต้องเขียน ctx.Sentry().CaptureMessage(...) หรือ Breadcrumb(...) ซ้ำ และ error ตัวเดียวจะไม่ถูกรายงานสองครั้งแม้ log ก่อนแล้ว return ทีหลัง — ดู Sentry
Standalone
go
log := core.NewLogger(env) // JSON, level from LOG_LEVEL
log := core.NewLoggerSimple() // plain text, info level (no config)
log := core.NewLoggerTo(w, env) // write to any io.Writer (tests)Interface
go
type ILogger interface {
Debug(msg string, args ...any)
Info(msg string, args ...any)
Warn(msg string, args ...any)
Error(msg string, args ...any)
With(args ...any) ILogger // child logger with pinned attributes
Slog() *slog.Logger // underlying slog for advanced use
}Configuration
| Env | Effect |
|---|---|
LOG_LEVEL | debug / info / warn / error (default info) |
LOG_SIMPLE | true → human-readable text handler; otherwise JSON |
go
// pin fields on a child logger
reqLog := ctx.Log().With("component", "billing")
reqLog.Info("started")Output
JSON handler (prod):
json
{"time":"...","level":"INFO","msg":"user created","user_id":"u1","request_id":"..."}Text handler (LOG_SIMPLE=true, dev):
time=... level=INFO msg="user created" user_id=u1