Files
go-omni/logx/timeZone.go

41 lines
1013 B
Go

package logx
import (
"context"
"log/slog"
"time"
"git.yuntuo.hk/k2safe/go-omni/internal/configdiag"
)
func logLocation(name string) (*time.Location, error) {
if name == "" {
return nil, nil
}
location, err := time.LoadLocation(name)
if err != nil {
return nil, configdiag.Wrap("timeZone", "must be an available IANA time zone or UTC", err)
}
return location, nil
}
// Convert only the record timestamp. User time.Time attributes retain their
// original locations; child loggers inherit this instance's location.
type zoneHandler struct {
slog.Handler
location *time.Location
}
func (h zoneHandler) Handle(ctx context.Context, r slog.Record) error {
if !r.Time.IsZero() {
r.Time = r.Time.In(h.location)
}
return h.Handler.Handle(ctx, r)
}
func (h zoneHandler) WithAttrs(attrs []slog.Attr) slog.Handler {
return zoneHandler{h.Handler.WithAttrs(attrs), h.location}
}
func (h zoneHandler) WithGroup(name string) slog.Handler {
return zoneHandler{h.Handler.WithGroup(name), h.location}
}