Source file src/log/slog/example_test.go

     1  // Copyright 2022 The Go Authors. All rights reserved.
     2  // Use of this source code is governed by a BSD-style
     3  // license that can be found in the LICENSE file.
     4  
     5  package slog_test
     6  
     7  import (
     8  	"log/slog"
     9  	"net/http"
    10  	"os"
    11  	"time"
    12  )
    13  
    14  func ExampleGroup() {
    15  	r, _ := http.NewRequest("GET", "localhost", nil)
    16  	// ...
    17  
    18  	logger := slog.New(
    19  		slog.NewTextHandler(os.Stdout, &slog.HandlerOptions{
    20  			ReplaceAttr: func(groups []string, a slog.Attr) slog.Attr {
    21  				if a.Key == slog.TimeKey && len(groups) == 0 {
    22  					return slog.Attr{}
    23  				}
    24  				return a
    25  			},
    26  		}),
    27  	)
    28  	logger.Info("finished",
    29  		slog.Group("req",
    30  			slog.String("method", r.Method),
    31  			slog.String("url", r.URL.String())),
    32  		slog.Int("status", http.StatusOK),
    33  		slog.Duration("duration", time.Second))
    34  
    35  	// Output:
    36  	// level=INFO msg=finished req.method=GET req.url=localhost status=200 duration=1s
    37  }
    38  

View as plain text