File: logger.go

package info (click to toggle)
webhook 2.8.0-4
  • links: PTS, VCS
  • area: main
  • in suites: bookworm, forky, sid, trixie
  • size: 11,064 kB
  • sloc: asm: 1,650; sh: 620; xml: 88; makefile: 50; ansic: 24
file content (59 lines) | stat: -rw-r--r-- 1,392 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
package middleware

import (
	"bytes"
	"fmt"
	"log"
	"net/http"
	"time"

	"github.com/dustin/go-humanize"
	"github.com/go-chi/chi/middleware"
)

// Logger is a middleware that logs useful data about each HTTP request.
type Logger struct {
	Logger middleware.LoggerInterface
}

// NewLogger creates a new RequestLogger Handler.
func NewLogger() func(next http.Handler) http.Handler {
	return middleware.RequestLogger(&Logger{})
}

// NewLogEntry creates a new LogEntry for the request.
func (l *Logger) NewLogEntry(r *http.Request) middleware.LogEntry {
	e := &LogEntry{
		req: r,
		buf: &bytes.Buffer{},
	}

	return e
}

// LogEntry represents an individual log entry.
type LogEntry struct {
	*Logger
	req *http.Request
	buf *bytes.Buffer
}

// Write constructs and writes the final log entry.
func (l *LogEntry) Write(status, totalBytes int, elapsed time.Duration) {
	rid := GetReqID(l.req.Context())
	if rid != "" {
		fmt.Fprintf(l.buf, "[%s] ", rid)
	}

	fmt.Fprintf(l.buf, "%03d | %s | %s | ", status, humanize.IBytes(uint64(totalBytes)), elapsed)
	l.buf.WriteString(l.req.Host + " | " + l.req.Method + " " + l.req.RequestURI)
	log.Print(l.buf.String())
}

// Panic prints the call stack for a panic.
func (l *LogEntry) Panic(v interface{}, stack []byte) {
	e := l.NewLogEntry(l.req).(*LogEntry)
	fmt.Fprintf(e.buf, "panic: %#v", v)
	log.Print(e.buf.String())
	log.Print(string(stack))
}