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  	"context"
     9  	"log/slog"
    10  	"net/http"
    11  	"os"
    12  	"time"
    13  )
    14  
    15  func ExampleGroup() {
    16  	r, _ := http.NewRequest("GET", "localhost", nil)
    17  	// ...
    18  
    19  	logger := slog.New(
    20  		slog.NewTextHandler(os.Stdout, &slog.HandlerOptions{
    21  			ReplaceAttr: func(groups []string, a slog.Attr) slog.Attr {
    22  				if a.Key == slog.TimeKey && len(groups) == 0 {
    23  					return slog.Attr{}
    24  				}
    25  				return a
    26  			},
    27  		}),
    28  	)
    29  	logger.Info("finished",
    30  		slog.Group("req",
    31  			slog.String("method", r.Method),
    32  			slog.String("url", r.URL.String())),
    33  		slog.Int("status", http.StatusOK),
    34  		slog.Duration("duration", time.Second))
    35  
    36  	// Output:
    37  	// level=INFO msg=finished req.method=GET req.url=localhost status=200 duration=1s
    38  }
    39  
    40  func ExampleGroupAttrs() {
    41  	r, _ := http.NewRequest("POST", "localhost", http.NoBody)
    42  	// ...
    43  
    44  	logger := slog.New(
    45  		slog.NewTextHandler(os.Stdout, &slog.HandlerOptions{
    46  			Level: slog.LevelDebug,
    47  			ReplaceAttr: func(groups []string, a slog.Attr) slog.Attr {
    48  				if a.Key == slog.TimeKey && len(groups) == 0 {
    49  					return slog.Attr{}
    50  				}
    51  				return a
    52  			},
    53  		}),
    54  	)
    55  
    56  	// Use []slog.Attr to accumulate attributes.
    57  	attrs := []slog.Attr{slog.String("method", r.Method)}
    58  	attrs = append(attrs, slog.String("url", r.URL.String()))
    59  
    60  	if r.Method == "POST" {
    61  		attrs = append(attrs, slog.Int("content-length", int(r.ContentLength)))
    62  	}
    63  
    64  	// Group the attributes under a key.
    65  	logger.LogAttrs(context.Background(), slog.LevelInfo,
    66  		"finished",
    67  		slog.Int("status", http.StatusOK),
    68  		slog.GroupAttrs("req", attrs...),
    69  	)
    70  
    71  	// Groups with empty keys are inlined.
    72  	logger.LogAttrs(context.Background(), slog.LevelInfo,
    73  		"finished",
    74  		slog.Int("status", http.StatusOK),
    75  		slog.GroupAttrs("", attrs...),
    76  	)
    77  
    78  	// Output:
    79  	// level=INFO msg=finished status=200 req.method=POST req.url=localhost req.content-length=0
    80  	// level=INFO msg=finished status=200 method=POST url=localhost content-length=0
    81  }
    82  

View as plain text