Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit 528cd32

Browse files
authored
Update logging example to use preview version of new log/slog (go-chi#771)
1 parent 85f523b commit 528cd32

File tree

1 file changed

+50
-47
lines changed

1 file changed

+50
-47
lines changed

_examples/logging/main.go

Lines changed: 50 additions & 47 deletions
Original file line numberDiff line numberDiff line change
@@ -1,41 +1,42 @@
1-
//
21
// Custom Structured Logger
32
// ========================
43
// This example demonstrates how to use middleware.RequestLogger,
54
// middleware.LogFormatter and middleware.LogEntry to build a structured
6-
// logger using the amazing sirupsen/logrus package as the logging
5+
// logger using the preview version of the new log/slog package as the logging
76
// backend.
87
//
98
// Also: check out https://github.com/goware/httplog for an improved context
109
// logger with support for HTTP request logging, based on the example below.
11-
//
1210
package main
1311

1412
import (
1513
"fmt"
1614
"net/http"
15+
"os"
1716
"time"
1817

18+
"golang.org/x/exp/slog"
19+
1920
"github.com/go-chi/chi/v5"
2021
"github.com/go-chi/chi/v5/middleware"
21-
"github.com/sirupsen/logrus"
2222
)
2323

2424
func main() {
25-
26-
// Setup the logger backend using sirupsen/logrus and configure
27-
// it to use a custom JSONFormatter. See the logrus docs for how to
28-
// configure the backend at github.com/sirupsen/logrus
29-
logger := logrus.New()
30-
logger.Formatter = &logrus.JSONFormatter{
31-
// disable, as we set our own
32-
DisableTimestamp: true,
33-
}
25+
// Setup a JSON handler for the new log/slog library
26+
slogJSONHandler := slog.HandlerOptions{
27+
// Remove default time slog.Attr, we create our own later
28+
ReplaceAttr: func(groups []string, a slog.Attr) slog.Attr {
29+
if a.Key == slog.TimeKey {
30+
return slog.Attr{}
31+
}
32+
return a
33+
},
34+
}.NewJSONHandler(os.Stdout)
3435

3536
// Routes
3637
r := chi.NewRouter()
3738
r.Use(middleware.RequestID)
38-
r.Use(NewStructuredLogger(logger))
39+
r.Use(NewStructuredLogger(slogJSONHandler))
3940
r.Use(middleware.Recoverer)
4041

4142
r.Get("/", func(w http.ResponseWriter, r *http.Request) {
@@ -49,70 +50,70 @@ func main() {
4950
r.Get("/panic", func(w http.ResponseWriter, r *http.Request) {
5051
panic("oops")
5152
})
53+
r.Get("/add_fields", func(w http.ResponseWriter, r *http.Request) {
54+
LogEntrySetFields(r, map[string]interface{}{"foo": "bar", "bar": "foo"})
55+
})
5256
http.ListenAndServe(":3333", r)
5357
}
5458

5559
// StructuredLogger is a simple, but powerful implementation of a custom structured
56-
// logger backed on logrus. I encourage users to copy it, adapt it and make it their
60+
// logger backed on log/slog. I encourage users to copy it, adapt it and make it their
5761
// own. Also take a look at https://github.com/go-chi/httplog for a dedicated pkg based
5862
// on this work, designed for context-based http routers.
5963

60-
func NewStructuredLogger(logger *logrus.Logger) func(next http.Handler) http.Handler {
61-
return middleware.RequestLogger(&StructuredLogger{logger})
64+
func NewStructuredLogger(handler slog.Handler) func(next http.Handler) http.Handler {
65+
return middleware.RequestLogger(&StructuredLogger{Logger: handler})
6266
}
6367

6468
type StructuredLogger struct {
65-
Logger *logrus.Logger
69+
Logger slog.Handler
6670
}
6771

6872
func (l *StructuredLogger) NewLogEntry(r *http.Request) middleware.LogEntry {
69-
entry := &StructuredLoggerEntry{Logger: logrus.NewEntry(l.Logger)}
70-
logFields := logrus.Fields{}
71-
72-
logFields["ts"] = time.Now().UTC().Format(time.RFC1123)
73+
var logFields []slog.Attr
74+
logFields = append(logFields, slog.String("ts", time.Now().UTC().Format(time.RFC1123)))
7375

7476
if reqID := middleware.GetReqID(r.Context()); reqID != "" {
75-
logFields["req_id"] = reqID
77+
logFields = append(logFields, slog.String("req_id", reqID))
7678
}
7779

7880
scheme := "http"
7981
if r.TLS != nil {
8082
scheme = "https"
8183
}
82-
logFields["http_scheme"] = scheme
83-
logFields["http_proto"] = r.Proto
84-
logFields["http_method"] = r.Method
85-
86-
logFields["remote_addr"] = r.RemoteAddr
87-
logFields["user_agent"] = r.UserAgent()
8884

89-
logFields["uri"] = fmt.Sprintf("%s://%s%s", scheme, r.Host, r.RequestURI)
85+
handler := l.Logger.WithAttrs(append(logFields,
86+
slog.String("http_scheme", scheme),
87+
slog.String("http_proto", r.Proto),
88+
slog.String("http_method", r.Method),
89+
slog.String("remote_addr", r.RemoteAddr),
90+
slog.String("user_agent", r.UserAgent()),
91+
slog.String("uri", fmt.Sprintf("%s://%s%s", scheme, r.Host, r.RequestURI))))
9092

91-
entry.Logger = entry.Logger.WithFields(logFields)
93+
entry := StructuredLoggerEntry{Logger: slog.New(handler)}
9294

93-
entry.Logger.Infoln("request started")
95+
entry.Logger.LogAttrs(slog.LevelInfo, "request started", logFields...)
9496

95-
return entry
97+
return &entry
9698
}
9799

98100
type StructuredLoggerEntry struct {
99-
Logger logrus.FieldLogger
101+
Logger *slog.Logger
100102
}
101103

102104
func (l *StructuredLoggerEntry) Write(status, bytes int, header http.Header, elapsed time.Duration, extra interface{}) {
103-
l.Logger = l.Logger.WithFields(logrus.Fields{
104-
"resp_status": status, "resp_bytes_length": bytes,
105-
"resp_elapsed_ms": float64(elapsed.Nanoseconds()) / 1000000.0,
106-
})
107-
108-
l.Logger.Infoln("request complete")
105+
l.Logger.LogAttrs(slog.LevelInfo, "request complete",
106+
slog.Int("resp_status", status),
107+
slog.Int("resp_byte_length", bytes),
108+
slog.Float64("resp_elapsed_ms", float64(elapsed.Nanoseconds())/1000000.0),
109+
)
109110
}
110111

111112
func (l *StructuredLoggerEntry) Panic(v interface{}, stack []byte) {
112-
l.Logger = l.Logger.WithFields(logrus.Fields{
113-
"stack": string(stack),
114-
"panic": fmt.Sprintf("%+v", v),
115-
})
113+
l.Logger.LogAttrs(slog.LevelInfo, "",
114+
slog.String("stack", string(stack)),
115+
slog.String("panic", fmt.Sprintf("%+v", v)),
116+
)
116117
}
117118

118119
// Helper methods used by the application to get the request-scoped
@@ -122,19 +123,21 @@ func (l *StructuredLoggerEntry) Panic(v interface{}, stack []byte) {
122123
// passes through the handler chain, which at any point can be logged
123124
// with a call to .Print(), .Info(), etc.
124125

125-
func GetLogEntry(r *http.Request) logrus.FieldLogger {
126+
func GetLogEntry(r *http.Request) *slog.Logger {
126127
entry := middleware.GetLogEntry(r).(*StructuredLoggerEntry)
127128
return entry.Logger
128129
}
129130

130131
func LogEntrySetField(r *http.Request, key string, value interface{}) {
131132
if entry, ok := r.Context().Value(middleware.LogEntryCtxKey).(*StructuredLoggerEntry); ok {
132-
entry.Logger = entry.Logger.WithField(key, value)
133+
entry.Logger = entry.Logger.With(key, value)
133134
}
134135
}
135136

136137
func LogEntrySetFields(r *http.Request, fields map[string]interface{}) {
137138
if entry, ok := r.Context().Value(middleware.LogEntryCtxKey).(*StructuredLoggerEntry); ok {
138-
entry.Logger = entry.Logger.WithFields(fields)
139+
for k, v := range fields {
140+
entry.Logger = entry.Logger.With(k, v)
141+
}
139142
}
140143
}

0 commit comments

Comments
 (0)