|
| 1 | +package logger |
| 2 | + |
| 3 | +import ( |
| 4 | + "context" |
| 5 | + "fmt" |
| 6 | + "io" |
| 7 | + "log" |
| 8 | + "log/slog" |
| 9 | + |
| 10 | + "github.com/fatih/color" |
| 11 | +) |
| 12 | + |
| 13 | +type ColorHandler struct { |
| 14 | + slog.Handler |
| 15 | + logLogger *log.Logger |
| 16 | + isDebugModeEnabled bool |
| 17 | +} |
| 18 | + |
| 19 | +func (c *ColorHandler) Handle(ctx context.Context, record slog.Record) error { |
| 20 | + logParts := []any{} |
| 21 | + |
| 22 | + // Time (only shown in debug mode). |
| 23 | + if c.isDebugModeEnabled { |
| 24 | + logParts = append(logParts, |
| 25 | + fmt.Sprintf("(%s)", record.Time.Format("15:04")), |
| 26 | + ) |
| 27 | + } |
| 28 | + |
| 29 | + // Log level. |
| 30 | + logLevel := record.Level.String() + " :" |
| 31 | + switch record.Level { |
| 32 | + case slog.LevelDebug: |
| 33 | + logLevel = color.MagentaString(logLevel) |
| 34 | + case slog.LevelInfo: |
| 35 | + logLevel = color.GreenString(logLevel) |
| 36 | + case slog.LevelWarn: |
| 37 | + logLevel = color.YellowString(logLevel) |
| 38 | + case slog.LevelError: |
| 39 | + logLevel = color.RedString(logLevel) |
| 40 | + } |
| 41 | + logParts = append(logParts, logLevel) |
| 42 | + |
| 43 | + // Message. |
| 44 | + message := color.WhiteString(record.Message) |
| 45 | + logParts = append(logParts, message) |
| 46 | + |
| 47 | + // Attributes. |
| 48 | + record.Attrs(func(attribute slog.Attr) bool { |
| 49 | + logParts = append(logParts, |
| 50 | + fmt.Sprintf("%s=%s", color.CyanString(attribute.Key), attribute.Value.String()), |
| 51 | + ) |
| 52 | + |
| 53 | + return true |
| 54 | + }) |
| 55 | + |
| 56 | + c.logLogger.Println(logParts...) |
| 57 | + return nil |
| 58 | +} |
| 59 | + |
| 60 | +func withColorHandler(out io.Writer, handler slog.Handler, isDebugModeEnabled bool) *ColorHandler { |
| 61 | + return &ColorHandler{ |
| 62 | + Handler: handler, |
| 63 | + logLogger: log.New(out, "", 0), |
| 64 | + isDebugModeEnabled: isDebugModeEnabled, |
| 65 | + } |
| 66 | +} |
0 commit comments