1 // Package logging is the one logger the commands write through: a level, a
2 // destination, the seam the rest of the tree already uses (`Logf`), and a
3 // request log for the HTTP faces.
4 //
5 // A server on a host nobody is watching needs three things to be diagnosable:
6 // a line per request that says what was asked, what came back and how long it
7 // took; a periodic line that says the process is still doing something; and a
8 // way to turn the volume up without a rebuild. Everything else here exists to
9 // serve those three.
10 package logging
11 12 import (
13 "bytes"
14 "context"
15 "fmt"
16 "io"
17 "log"
18 "net"
19 "net/http"
20 "os"
21 "os/signal"
22 "strings"
23 "sync"
24 "sync/atomic"
25 "syscall"
26 "time"
27 )
28 29 // Level is how much is written.
30 type Level int8
31 32 // Levels, least to most severe.
33 const (
34 // Debug carries one line per successful request and per block the fill
35 // asks for: on while diagnosing, off in normal operation.
36 Debug Level = iota
37 // Info carries lifecycle lines, failures, and slow requests.
38 Info
39 // Warn carries a request the server refused.
40 Warn
41 // Error carries a request that failed inside the server.
42 Error
43 // Off writes nothing. It is above every level, so a logger set to it
44 // passes nothing through, which is what "turn the logging off" means.
45 Off
46 )
47 48 // String names a level the way the flag takes it.
49 func (l Level) String() string {
50 switch l {
51 case Debug:
52 return "debug"
53 case Info:
54 return "info"
55 case Warn:
56 return "warn"
57 case Error:
58 return "error"
59 case Off:
60 return "off"
61 }
62 return fmt.Sprintf("level(%d)", int8(l))
63 }
64 65 // ParseLevel reads a level name.
66 func ParseLevel(s string) (Level, error) {
67 switch strings.ToLower(strings.TrimSpace(s)) {
68 case "debug":
69 return Debug, nil
70 case "info", "":
71 return Info, nil
72 case "warn", "warning":
73 return Warn, nil
74 case "error":
75 return Error, nil
76 case "off", "none", "silent":
77 return Off, nil
78 }
79 return 0, fmt.Errorf("logging: no level %q: use debug, info, warn, error or off", s)
80 }
81 82 // Access is one request as the log records it.
83 type Access struct {
84 Remote string
85 Method string
86 Path string
87 Status int
88 Bytes int64
89 Dur time.Duration
90 // Note is the start of a refused or failed response's body, so the reason
91 // is in the log and not only in the client's terminal.
92 Note string
93 }
94 95 // Stats counts what the request log has seen.
96 type Stats struct {
97 Requests uint64
98 Bytes uint64
99 Refused uint64 // 4xx
100 Failed uint64 // 5xx
101 }
102 103 // Logger writes levelled lines to one destination.
104 type Logger struct {
105 mu sync.Mutex
106 out *log.Logger
107 level Level
108 // file is the destination when it is a file the process can reopen, which
109 // is what SIGHUP does.
110 file *os.File
111 path string
112 113 requests atomic.Uint64
114 bytes atomic.Uint64
115 refused atomic.Uint64
116 failed atomic.Uint64
117 }
118 119 // New returns a logger writing to w at a level.
120 func New(w io.Writer, level Level) *Logger {
121 return &Logger{out: log.New(w, "", log.LstdFlags), level: level}
122 }
123 124 // OpenFile returns a logger writing to path, appending. An empty path means
125 // stderr.
126 func OpenFile(path string, level Level) (*Logger, error) {
127 if path == "" {
128 return New(os.Stderr, level), nil
129 }
130 l := New(io.Discard, level)
131 l.path = path
132 if err := l.Reopen(); err != nil {
133 return nil, err
134 }
135 return l, nil
136 }
137 138 // Reopen closes and reopens the destination, which is what a log rotation
139 // signals. A logger on stderr does nothing.
140 func (l *Logger) Reopen() error {
141 if l.path == "" {
142 return nil
143 }
144 f, err := os.OpenFile(l.path, os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0o644)
145 if err != nil {
146 return fmt.Errorf("logging: open %s: %w", l.path, err)
147 }
148 l.mu.Lock()
149 old := l.file
150 l.file = f
151 l.out.SetOutput(f)
152 l.mu.Unlock()
153 if old != nil {
154 _ = old.Close()
155 }
156 return nil
157 }
158 159 // SetLevel changes the level while running.
160 func (l *Logger) SetLevel(level Level) {
161 l.mu.Lock()
162 l.level = level
163 l.mu.Unlock()
164 }
165 166 // Level is the current level.
167 func (l *Logger) Level() Level {
168 l.mu.Lock()
169 defer l.mu.Unlock()
170 return l.level
171 }
172 173 // Writer is the destination, for http.Server's own error log.
174 func (l *Logger) Writer() io.Writer {
175 l.mu.Lock()
176 defer l.mu.Unlock()
177 return l.out.Writer()
178 }
179 180 // Close closes a file destination.
181 func (l *Logger) Close() error {
182 l.mu.Lock()
183 defer l.mu.Unlock()
184 if l.file == nil {
185 return nil
186 }
187 err := l.file.Close()
188 l.file = nil
189 return err
190 }
191 192 func (l *Logger) write(level Level, format string, args ...any) {
193 l.mu.Lock()
194 enabled := level >= l.level
195 l.mu.Unlock()
196 if !enabled {
197 return
198 }
199 l.out.Printf("%s: %s", level, fmt.Sprintf(format, args...))
200 }
201 202 // Debugf writes at debug.
203 func (l *Logger) Debugf(format string, args ...any) { l.write(Debug, format, args...) }
204 205 // Infof writes at info.
206 func (l *Logger) Infof(format string, args ...any) { l.write(Info, format, args...) }
207 208 // Warnf writes at warn.
209 func (l *Logger) Warnf(format string, args ...any) { l.write(Warn, format, args...) }
210 211 // Errorf writes at error.
212 func (l *Logger) Errorf(format string, args ...any) { l.write(Error, format, args...) }
213 214 // Logf is the seam the rest of the tree already takes: a format and arguments,
215 // written at info.
216 func (l *Logger) Logf(format string, args ...any) { l.write(Info, format, args...) }
217 218 // Tracef is the same seam for the lines that are one per block or one per
219 // request, written at debug.
220 func (l *Logger) Tracef(format string, args ...any) { l.write(Debug, format, args...) }
221 222 // Stats is what the request log has counted.
223 func (l *Logger) Stats() Stats {
224 return Stats{
225 Requests: l.requests.Load(),
226 Bytes: l.bytes.Load(),
227 Refused: l.refused.Load(),
228 Failed: l.failed.Load(),
229 }
230 }
231 232 // Access writes one request line, at the level the outcome deserves.
233 func (l *Logger) Access(a Access) {
234 l.requests.Add(1)
235 l.bytes.Add(uint64(max(a.Bytes, 0)))
236 switch {
237 case a.Status >= 500:
238 l.failed.Add(1)
239 case a.Status >= 400:
240 l.refused.Add(1)
241 }
242 line := fmt.Sprintf("access: remote=%s method=%s path=%q status=%d bytes=%d dur_ms=%d",
243 a.Remote, a.Method, a.Path, a.Status, a.Bytes, a.Dur.Milliseconds())
244 if a.Note != "" {
245 line += fmt.Sprintf(" note=%q", a.Note)
246 }
247 switch {
248 case a.Status >= 500:
249 l.write(Error, "%s", line)
250 case a.Status >= 400:
251 l.write(Warn, "%s", line)
252 case a.Dur >= SlowRequest:
253 l.write(Info, "%s slow", line)
254 default:
255 l.write(Debug, "%s", line)
256 }
257 }
258 259 // SlowRequest is the duration above which a successful request is worth a line
260 // even at info.
261 const SlowRequest = 5 * time.Second
262 263 // noteLimit is how much of a failed response's body is kept for the log.
264 const noteLimit = 512
265 266 // Handler logs every request through l, which is the one thing the service
267 // packages do not do for themselves: they answer, and this says what was asked
268 // and what came back.
269 func (l *Logger) Handler(next http.Handler) http.Handler {
270 return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
271 start := time.Now()
272 rec := &recorder{ResponseWriter: w}
273 next.ServeHTTP(rec, r)
274 status := rec.status
275 if status == 0 {
276 status = http.StatusOK
277 }
278 l.Access(Access{
279 Remote: hostOnly(r.RemoteAddr),
280 Method: r.Method,
281 Path: r.URL.RequestURI(),
282 Status: status,
283 Bytes: rec.written,
284 Dur: time.Since(start),
285 Note: strings.TrimSpace(rec.note.String()),
286 })
287 })
288 }
289 290 // recorder keeps the status, the byte count and, for a refusal or a failure,
291 // the start of the body.
292 type recorder struct {
293 http.ResponseWriter
294 status int
295 written int64
296 note bytes.Buffer
297 }
298 299 func (r *recorder) WriteHeader(status int) {
300 if r.status == 0 {
301 r.status = status
302 }
303 r.ResponseWriter.WriteHeader(status)
304 }
305 306 func (r *recorder) Write(b []byte) (int, error) {
307 if r.status == 0 {
308 r.status = http.StatusOK
309 }
310 n, err := r.ResponseWriter.Write(b)
311 r.written += int64(n)
312 // A successful response is not kept: a chunk is a hundred megabytes, and
313 // the reason a request succeeded is its status line.
314 if r.status >= 400 && r.note.Len() < noteLimit && n > 0 {
315 if room := noteLimit - r.note.Len(); room > 0 {
316 if len(b) > room {
317 r.note.Write(b[:room])
318 } else {
319 r.note.Write(b)
320 }
321 }
322 }
323 return n, err
324 }
325 326 // Flush passes a flush through, so a handler that streams is not held back by
327 // the wrapper.
328 func (r *recorder) Flush() {
329 if f, ok := r.ResponseWriter.(http.Flusher); ok {
330 f.Flush()
331 }
332 }
333 334 // Unwrap lets http.ResponseController reach the underlying writer.
335 func (r *recorder) Unwrap() http.ResponseWriter { return r.ResponseWriter }
336 337 // hostOnly strips the port from an address, because a port is not a client.
338 func hostOnly(addr string) string {
339 if host, _, err := net.SplitHostPort(addr); err == nil {
340 return host
341 }
342 return addr
343 }
344 345 // Always writes a line whatever the level is. It is for the acknowledgement of
346 // a signal that changed the level: an operator who turned logging off needs to
347 // see the line that says it is on again, or the signal has no visible effect
348 // either way.
349 func (l *Logger) Always(format string, args ...any) {
350 l.out.Printf("info: %s", fmt.Sprintf(format, args...))
351 }
352 353 // SignalLevels makes the level controllable while the process runs, which is
354 // what a host nobody is watching needs: SIGUSR1 turns debug on, SIGUSR2 puts it
355 // back to the level the process was started with.
356 //
357 // The two signals are also what turns logging off and on when the process was
358 // started with -log-level off: SIGUSR1 brings it back to the base level, and
359 // SIGUSR2 is harmless.
360 func (l *Logger) SignalLevels(base Level) {
361 sigs := make(chan os.Signal, 2)
362 // Notify is installed before this returns, so a caller does not have to
363 // race the first signal against the handler being there: the default
364 // action of these two is to terminate the process.
365 signal.Notify(sigs, syscall.SIGUSR1, syscall.SIGUSR2)
366 go func() {
367 for sig := range sigs {
368 switch sig {
369 case syscall.SIGUSR1:
370 l.SetLevel(Debug)
371 l.Always("log level: debug (diagnosing)")
372 default:
373 l.SetLevel(base)
374 l.Always("log level: %s", base)
375 }
376 }
377 }()
378 }
379 380 // ReopenOnHangup reopens a file destination when the process is sent SIGHUP,
381 // which is what a log rotation does. It runs until the process exits.
382 func (l *Logger) ReopenOnHangup() {
383 hup := make(chan os.Signal, 1)
384 signal.Notify(hup, syscall.SIGHUP)
385 go func() {
386 for range hup {
387 if err := l.Reopen(); err != nil {
388 l.Errorf("reopen log: %v", err)
389 continue
390 }
391 l.Infof("log reopened")
392 }
393 }()
394 }
395 396 // Heartbeat writes one line every period with whatever report returns, until
397 // ctx ends. It is the line an operator who is not watching the terminal reads
398 // to know the process is alive, and what it is holding at that moment.
399 func (l *Logger) Heartbeat(ctx context.Context, period time.Duration, report func() string) {
400 if period <= 0 {
401 return
402 }
403 t := time.NewTicker(period)
404 defer t.Stop()
405 for {
406 select {
407 case <-ctx.Done():
408 return
409 case <-t.C:
410 l.Infof("heartbeat: %s", report())
411 }
412 }
413 }
414