// Package logging is the one logger the commands write through: a level, a // destination, the seam the rest of the tree already uses (`Logf`), and a // request log for the HTTP faces. // // A server on a host nobody is watching needs three things to be diagnosable: // a line per request that says what was asked, what came back and how long it // took; a periodic line that says the process is still doing something; and a // way to turn the volume up without a rebuild. Everything else here exists to // serve those three. package logging import ( "bytes" "context" "fmt" "io" "log" "net" "net/http" "os" "os/signal" "strings" "sync" "sync/atomic" "syscall" "time" ) // Level is how much is written. type Level int8 // Levels, least to most severe. const ( // Debug carries one line per successful request and per block the fill // asks for: on while diagnosing, off in normal operation. Debug Level = iota // Info carries lifecycle lines, failures, and slow requests. Info // Warn carries a request the server refused. Warn // Error carries a request that failed inside the server. Error // Off writes nothing. It is above every level, so a logger set to it // passes nothing through, which is what "turn the logging off" means. Off ) // String names a level the way the flag takes it. func (l Level) String() string { switch l { case Debug: return "debug" case Info: return "info" case Warn: return "warn" case Error: return "error" case Off: return "off" } return fmt.Sprintf("level(%d)", int8(l)) } // ParseLevel reads a level name. func ParseLevel(s string) (Level, error) { switch strings.ToLower(strings.TrimSpace(s)) { case "debug": return Debug, nil case "info", "": return Info, nil case "warn", "warning": return Warn, nil case "error": return Error, nil case "off", "none", "silent": return Off, nil } return 0, fmt.Errorf("logging: no level %q: use debug, info, warn, error or off", s) } // Access is one request as the log records it. type Access struct { Remote string Method string Path string Status int Bytes int64 Dur time.Duration // Note is the start of a refused or failed response's body, so the reason // is in the log and not only in the client's terminal. Note string } // Stats counts what the request log has seen. type Stats struct { Requests uint64 Bytes uint64 Refused uint64 // 4xx Failed uint64 // 5xx } // Logger writes levelled lines to one destination. type Logger struct { mu sync.Mutex out *log.Logger level Level // file is the destination when it is a file the process can reopen, which // is what SIGHUP does. file *os.File path string requests atomic.Uint64 bytes atomic.Uint64 refused atomic.Uint64 failed atomic.Uint64 } // New returns a logger writing to w at a level. func New(w io.Writer, level Level) *Logger { return &Logger{out: log.New(w, "", log.LstdFlags), level: level} } // OpenFile returns a logger writing to path, appending. An empty path means // stderr. func OpenFile(path string, level Level) (*Logger, error) { if path == "" { return New(os.Stderr, level), nil } l := New(io.Discard, level) l.path = path if err := l.Reopen(); err != nil { return nil, err } return l, nil } // Reopen closes and reopens the destination, which is what a log rotation // signals. A logger on stderr does nothing. func (l *Logger) Reopen() error { if l.path == "" { return nil } f, err := os.OpenFile(l.path, os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0o644) if err != nil { return fmt.Errorf("logging: open %s: %w", l.path, err) } l.mu.Lock() old := l.file l.file = f l.out.SetOutput(f) l.mu.Unlock() if old != nil { _ = old.Close() } return nil } // SetLevel changes the level while running. func (l *Logger) SetLevel(level Level) { l.mu.Lock() l.level = level l.mu.Unlock() } // Level is the current level. func (l *Logger) Level() Level { l.mu.Lock() defer l.mu.Unlock() return l.level } // Writer is the destination, for http.Server's own error log. func (l *Logger) Writer() io.Writer { l.mu.Lock() defer l.mu.Unlock() return l.out.Writer() } // Close closes a file destination. func (l *Logger) Close() error { l.mu.Lock() defer l.mu.Unlock() if l.file == nil { return nil } err := l.file.Close() l.file = nil return err } func (l *Logger) write(level Level, format string, args ...any) { l.mu.Lock() enabled := level >= l.level l.mu.Unlock() if !enabled { return } l.out.Printf("%s: %s", level, fmt.Sprintf(format, args...)) } // Debugf writes at debug. func (l *Logger) Debugf(format string, args ...any) { l.write(Debug, format, args...) } // Infof writes at info. func (l *Logger) Infof(format string, args ...any) { l.write(Info, format, args...) } // Warnf writes at warn. func (l *Logger) Warnf(format string, args ...any) { l.write(Warn, format, args...) } // Errorf writes at error. func (l *Logger) Errorf(format string, args ...any) { l.write(Error, format, args...) } // Logf is the seam the rest of the tree already takes: a format and arguments, // written at info. func (l *Logger) Logf(format string, args ...any) { l.write(Info, format, args...) } // Tracef is the same seam for the lines that are one per block or one per // request, written at debug. func (l *Logger) Tracef(format string, args ...any) { l.write(Debug, format, args...) } // Stats is what the request log has counted. func (l *Logger) Stats() Stats { return Stats{ Requests: l.requests.Load(), Bytes: l.bytes.Load(), Refused: l.refused.Load(), Failed: l.failed.Load(), } } // Access writes one request line, at the level the outcome deserves. func (l *Logger) Access(a Access) { l.requests.Add(1) l.bytes.Add(uint64(max(a.Bytes, 0))) switch { case a.Status >= 500: l.failed.Add(1) case a.Status >= 400: l.refused.Add(1) } line := fmt.Sprintf("access: remote=%s method=%s path=%q status=%d bytes=%d dur_ms=%d", a.Remote, a.Method, a.Path, a.Status, a.Bytes, a.Dur.Milliseconds()) if a.Note != "" { line += fmt.Sprintf(" note=%q", a.Note) } switch { case a.Status >= 500: l.write(Error, "%s", line) case a.Status >= 400: l.write(Warn, "%s", line) case a.Dur >= SlowRequest: l.write(Info, "%s slow", line) default: l.write(Debug, "%s", line) } } // SlowRequest is the duration above which a successful request is worth a line // even at info. const SlowRequest = 5 * time.Second // noteLimit is how much of a failed response's body is kept for the log. const noteLimit = 512 // Handler logs every request through l, which is the one thing the service // packages do not do for themselves: they answer, and this says what was asked // and what came back. func (l *Logger) Handler(next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { start := time.Now() rec := &recorder{ResponseWriter: w} next.ServeHTTP(rec, r) status := rec.status if status == 0 { status = http.StatusOK } l.Access(Access{ Remote: hostOnly(r.RemoteAddr), Method: r.Method, Path: r.URL.RequestURI(), Status: status, Bytes: rec.written, Dur: time.Since(start), Note: strings.TrimSpace(rec.note.String()), }) }) } // recorder keeps the status, the byte count and, for a refusal or a failure, // the start of the body. type recorder struct { http.ResponseWriter status int written int64 note bytes.Buffer } func (r *recorder) WriteHeader(status int) { if r.status == 0 { r.status = status } r.ResponseWriter.WriteHeader(status) } func (r *recorder) Write(b []byte) (int, error) { if r.status == 0 { r.status = http.StatusOK } n, err := r.ResponseWriter.Write(b) r.written += int64(n) // A successful response is not kept: a chunk is a hundred megabytes, and // the reason a request succeeded is its status line. if r.status >= 400 && r.note.Len() < noteLimit && n > 0 { if room := noteLimit - r.note.Len(); room > 0 { if len(b) > room { r.note.Write(b[:room]) } else { r.note.Write(b) } } } return n, err } // Flush passes a flush through, so a handler that streams is not held back by // the wrapper. func (r *recorder) Flush() { if f, ok := r.ResponseWriter.(http.Flusher); ok { f.Flush() } } // Unwrap lets http.ResponseController reach the underlying writer. func (r *recorder) Unwrap() http.ResponseWriter { return r.ResponseWriter } // hostOnly strips the port from an address, because a port is not a client. func hostOnly(addr string) string { if host, _, err := net.SplitHostPort(addr); err == nil { return host } return addr } // Always writes a line whatever the level is. It is for the acknowledgement of // a signal that changed the level: an operator who turned logging off needs to // see the line that says it is on again, or the signal has no visible effect // either way. func (l *Logger) Always(format string, args ...any) { l.out.Printf("info: %s", fmt.Sprintf(format, args...)) } // SignalLevels makes the level controllable while the process runs, which is // what a host nobody is watching needs: SIGUSR1 turns debug on, SIGUSR2 puts it // back to the level the process was started with. // // The two signals are also what turns logging off and on when the process was // started with -log-level off: SIGUSR1 brings it back to the base level, and // SIGUSR2 is harmless. func (l *Logger) SignalLevels(base Level) { sigs := make(chan os.Signal, 2) // Notify is installed before this returns, so a caller does not have to // race the first signal against the handler being there: the default // action of these two is to terminate the process. signal.Notify(sigs, syscall.SIGUSR1, syscall.SIGUSR2) go func() { for sig := range sigs { switch sig { case syscall.SIGUSR1: l.SetLevel(Debug) l.Always("log level: debug (diagnosing)") default: l.SetLevel(base) l.Always("log level: %s", base) } } }() } // ReopenOnHangup reopens a file destination when the process is sent SIGHUP, // which is what a log rotation does. It runs until the process exits. func (l *Logger) ReopenOnHangup() { hup := make(chan os.Signal, 1) signal.Notify(hup, syscall.SIGHUP) go func() { for range hup { if err := l.Reopen(); err != nil { l.Errorf("reopen log: %v", err) continue } l.Infof("log reopened") } }() } // Heartbeat writes one line every period with whatever report returns, until // ctx ends. It is the line an operator who is not watching the terminal reads // to know the process is alive, and what it is holding at that moment. func (l *Logger) Heartbeat(ctx context.Context, period time.Duration, report func() string) { if period <= 0 { return } t := time.NewTicker(period) defer t.Stop() for { select { case <-ctx.Done(): return case <-t.C: l.Infof("heartbeat: %s", report()) } } }