Source file src/log/slog/example_logvaluer_group_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 "log/slog"
     8  
     9  type Name struct {
    10  	First, Last string
    11  }
    12  
    13  // LogValue implements slog.LogValuer.
    14  // It returns a group containing the fields of
    15  // the Name, so that they appear together in the log output.
    16  func (n Name) LogValue() slog.Value {
    17  	return slog.GroupValue(
    18  		slog.String("first", n.First),
    19  		slog.String("last", n.Last))
    20  }
    21  
    22  func ExampleLogValuer_group() {
    23  	n := Name{"Perry", "Platypus"}
    24  	slog.Info("mission accomplished", "agent", n)
    25  
    26  	// JSON Output would look in part like:
    27  	// {
    28  	//     ...
    29  	//     "msg": "mission accomplished",
    30  	//     "agent": {
    31  	//         "first": "Perry",
    32  	//         "last": "Platypus"
    33  	//     }
    34  	// }
    35  }
    36  

View as plain text