|
| 1 | +// Copyright 2020-2025 Buf Technologies, Inc. |
| 2 | +// |
| 3 | +// Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 | +// you may not use this file except in compliance with the License. |
| 5 | +// You may obtain a copy of the License at |
| 6 | +// |
| 7 | +// http://www.apache.org/licenses/LICENSE-2.0 |
| 8 | +// |
| 9 | +// Unless required by applicable law or agreed to in writing, software |
| 10 | +// distributed under the License is distributed on an "AS IS" BASIS, |
| 11 | +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | +// See the License for the specific language governing permissions and |
| 13 | +// limitations under the License. |
| 14 | + |
| 15 | +package slogapp |
| 16 | + |
| 17 | +import ( |
| 18 | + "bytes" |
| 19 | + "context" |
| 20 | + "fmt" |
| 21 | + "io" |
| 22 | + "log/slog" |
| 23 | + "os" |
| 24 | + "sync" |
| 25 | + |
| 26 | + "github.com/mattn/go-colorable" |
| 27 | +) |
| 28 | + |
| 29 | +const ( |
| 30 | + // color codes for ANSI escape sequences. |
| 31 | + colorBlack color = iota + 30 |
| 32 | + colorRed |
| 33 | + colorGreen |
| 34 | + colorYellow |
| 35 | + colorBlue |
| 36 | + colorMagenta |
| 37 | + colorCyan |
| 38 | + colorWhite |
| 39 | + |
| 40 | + // consoleSeparator is the separator used in console output. |
| 41 | + consoleSeparator = "\t" |
| 42 | +) |
| 43 | + |
| 44 | +// color represents an ANSI color code. |
| 45 | +type color uint8 |
| 46 | + |
| 47 | +type consoleHandlerOption func(*consoleHandlerOptions) |
| 48 | + |
| 49 | +// withConsoleColor enables or disables color output for the console handler. |
| 50 | +// |
| 51 | +// If set to true, the console handler will use colors for log levels. |
| 52 | +// If the environment variable NO_COLOR is set, colors will be disabled regardless of this setting. |
| 53 | +func withConsoleColor(enable bool) consoleHandlerOption { |
| 54 | + return func(options *consoleHandlerOptions) { |
| 55 | + options.enableColor = enable |
| 56 | + } |
| 57 | +} |
| 58 | + |
| 59 | +type consoleHandlerOptions struct { |
| 60 | + enableColor bool |
| 61 | +} |
| 62 | + |
| 63 | +func newConsoleHandlerOptions() *consoleHandlerOptions { |
| 64 | + return &consoleHandlerOptions{} |
| 65 | +} |
| 66 | + |
| 67 | +// consoleHandler is a custom slog.Handler that formats log messages for the console. |
| 68 | +type consoleHandler struct { |
| 69 | + enableColor bool |
| 70 | + out io.Writer |
| 71 | + lock *sync.Mutex // Lock protects access to the buffer. |
| 72 | + buffer *bytes.Buffer // Buffer output for the delegate's writer. |
| 73 | + delegate slog.Handler // Delegate writes to buffer. |
| 74 | +} |
| 75 | + |
| 76 | +// newConsoleHandler creates a new consoleHandler with the specified output writer and log level. |
| 77 | +// |
| 78 | +// It pretty prints the level (optionally with color) and message with JSON encoded attributes. |
| 79 | +// It wraps the output writer with colorable if it's os.Stdout or os.Stderr to support color output on Windows. |
| 80 | +// It logs attributes formatted using the slog.JSONHandler as a delegate. |
| 81 | +// It uses a mutex to synchronize access to the output. Not suitable for high-throughput logging. |
| 82 | +func newConsoleHandler(out io.Writer, logLevel slog.Level, options ...consoleHandlerOption) *consoleHandler { |
| 83 | + consoleHandlerOptions := newConsoleHandlerOptions() |
| 84 | + for _, option := range options { |
| 85 | + option(consoleHandlerOptions) |
| 86 | + } |
| 87 | + // Disable color if the environment variable NO_COLOR is set. |
| 88 | + enableColor := consoleHandlerOptions.enableColor |
| 89 | + if e := os.Getenv("NO_COLOR"); e != "" { |
| 90 | + enableColor = false |
| 91 | + } |
| 92 | + // Wrap the output writer with colorable if it's os.Stdout or os.Stderr |
| 93 | + // to support color output on Windows. |
| 94 | + if enableColor && (out == os.Stderr || out == os.Stdout) { |
| 95 | + file, _ := out.(*os.File) |
| 96 | + out = colorable.NewColorable(file) |
| 97 | + } |
| 98 | + // A delegate handler is used to format the log attributes. |
| 99 | + // It uses a buffer to accumulate the log attributes before writing them to the output. |
| 100 | + // The buffer is protected by the lock. |
| 101 | + var ( |
| 102 | + lock sync.Mutex |
| 103 | + buffer bytes.Buffer |
| 104 | + ) |
| 105 | + delegateHandler := slog.NewJSONHandler(&buffer, &slog.HandlerOptions{ |
| 106 | + Level: logLevel, |
| 107 | + ReplaceAttr: consoleReplaceAttr, |
| 108 | + }) |
| 109 | + return &consoleHandler{ |
| 110 | + enableColor: enableColor, |
| 111 | + out: out, |
| 112 | + lock: &lock, |
| 113 | + buffer: &buffer, |
| 114 | + delegate: delegateHandler, |
| 115 | + } |
| 116 | +} |
| 117 | + |
| 118 | +// Enabled implements the slog.Handler interface. |
| 119 | +func (c *consoleHandler) Enabled(ctx context.Context, level slog.Level) bool { |
| 120 | + return c.delegate.Enabled(ctx, level) |
| 121 | +} |
| 122 | + |
| 123 | +// Handle implements the slog.Handler interface. |
| 124 | +func (c *consoleHandler) Handle(ctx context.Context, r slog.Record) error { |
| 125 | + c.lock.Lock() |
| 126 | + defer c.lock.Unlock() |
| 127 | + c.buffer.Reset() |
| 128 | + if c.enableColor { |
| 129 | + c.buffer.WriteString(colorize(r.Level.String(), getColor(r.Level))) |
| 130 | + } else { |
| 131 | + c.buffer.WriteString(r.Level.String()) |
| 132 | + } |
| 133 | + c.buffer.WriteString(consoleSeparator) |
| 134 | + c.buffer.WriteString(r.Message) |
| 135 | + bufN := c.buffer.Len() |
| 136 | + c.buffer.WriteString(consoleSeparator) |
| 137 | + // Delegate must always be called, as it may have attributes to write. |
| 138 | + if err := c.delegate.Handle(ctx, r); err != nil { |
| 139 | + return err |
| 140 | + } |
| 141 | + if c.buffer.Len() == bufN+len(consoleSeparator+"{}\n") { |
| 142 | + // No attributes to write, trim the buffer to remove the empty JSON object. |
| 143 | + c.buffer.Truncate(bufN) |
| 144 | + c.buffer.WriteByte('\n') |
| 145 | + } |
| 146 | + _, err := c.buffer.WriteTo(c.out) |
| 147 | + return err |
| 148 | +} |
| 149 | + |
| 150 | +// WithAttrs implements the slog.Handler interface. |
| 151 | +func (c *consoleHandler) WithAttrs(attrs []slog.Attr) slog.Handler { |
| 152 | + return c.cloneWithDelegate(c.delegate.WithAttrs(attrs)) |
| 153 | +} |
| 154 | + |
| 155 | +// WithGroup implements the slog.Handler interface. |
| 156 | +func (c *consoleHandler) WithGroup(name string) slog.Handler { |
| 157 | + return c.cloneWithDelegate(c.delegate.WithGroup(name)) |
| 158 | +} |
| 159 | + |
| 160 | +// cloneWithDelegate creates a new consoleHandler with a new delegate handler. |
| 161 | +func (c *consoleHandler) cloneWithDelegate(delegate slog.Handler) *consoleHandler { |
| 162 | + return &consoleHandler{ |
| 163 | + enableColor: c.enableColor, |
| 164 | + delegate: delegate, |
| 165 | + out: c.out, |
| 166 | + lock: c.lock, |
| 167 | + buffer: c.buffer, |
| 168 | + } |
| 169 | +} |
| 170 | + |
| 171 | +// getColor returns the color code for the specified log level. |
| 172 | +func getColor(level slog.Level) color { |
| 173 | + switch { |
| 174 | + case level >= slog.LevelError: |
| 175 | + return colorRed |
| 176 | + case level >= slog.LevelWarn: |
| 177 | + return colorYellow |
| 178 | + case level >= slog.LevelInfo: |
| 179 | + return colorBlue |
| 180 | + case level >= slog.LevelDebug: |
| 181 | + return colorMagenta |
| 182 | + default: |
| 183 | + return 0 |
| 184 | + } |
| 185 | +} |
| 186 | + |
| 187 | +// colorize formats the string with the specified color. |
| 188 | +func colorize(s string, color color) string { |
| 189 | + if color == 0 { |
| 190 | + return s |
| 191 | + } |
| 192 | + return fmt.Sprintf("\x1b[%dm%s\x1b[0m", color, s) |
| 193 | +} |
| 194 | + |
| 195 | +// consoleReplaceAttr is a custom ReplaceAttr function for consoleHandler. |
| 196 | +// It silences the time, level, and message attributes to avoid duplication. |
| 197 | +func consoleReplaceAttr(groups []string, a slog.Attr) slog.Attr { |
| 198 | + switch a.Key { |
| 199 | + case slog.TimeKey, slog.LevelKey, slog.MessageKey: |
| 200 | + return slog.Attr{} |
| 201 | + default: |
| 202 | + return defaultReplaceAttr(groups, a) |
| 203 | + } |
| 204 | +} |
0 commit comments