• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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
5package slog
6
7import (
8	"time"
9)
10
11// An Attr is a key-value pair.
12type Attr struct {
13	Key   string
14	Value Value
15}
16
17// String returns an Attr for a string value.
18func String(key, value string) Attr {
19	return Attr{key, StringValue(value)}
20}
21
22// Int64 returns an Attr for an int64.
23func Int64(key string, value int64) Attr {
24	return Attr{key, Int64Value(value)}
25}
26
27// Int converts an int to an int64 and returns
28// an Attr with that value.
29func Int(key string, value int) Attr {
30	return Int64(key, int64(value))
31}
32
33// Uint64 returns an Attr for a uint64.
34func Uint64(key string, v uint64) Attr {
35	return Attr{key, Uint64Value(v)}
36}
37
38// Float64 returns an Attr for a floating-point number.
39func Float64(key string, v float64) Attr {
40	return Attr{key, Float64Value(v)}
41}
42
43// Bool returns an Attr for a bool.
44func Bool(key string, v bool) Attr {
45	return Attr{key, BoolValue(v)}
46}
47
48// Time returns an Attr for a [time.Time].
49// It discards the monotonic portion.
50func Time(key string, v time.Time) Attr {
51	return Attr{key, TimeValue(v)}
52}
53
54// Duration returns an Attr for a [time.Duration].
55func Duration(key string, v time.Duration) Attr {
56	return Attr{key, DurationValue(v)}
57}
58
59// Group returns an Attr for a Group [Value].
60// The first argument is the key; the remaining arguments
61// are converted to Attrs as in [Logger.Log].
62//
63// Use Group to collect several key-value pairs under a single
64// key on a log line, or as the result of LogValue
65// in order to log a single value as multiple Attrs.
66func Group(key string, args ...any) Attr {
67	return Attr{key, GroupValue(argsToAttrSlice(args)...)}
68}
69
70func argsToAttrSlice(args []any) []Attr {
71	var (
72		attr  Attr
73		attrs []Attr
74	)
75	for len(args) > 0 {
76		attr, args = argsToAttr(args)
77		attrs = append(attrs, attr)
78	}
79	return attrs
80}
81
82// Any returns an Attr for the supplied value.
83// See [AnyValue] for how values are treated.
84func Any(key string, value any) Attr {
85	return Attr{key, AnyValue(value)}
86}
87
88// Equal reports whether a and b have equal keys and values.
89func (a Attr) Equal(b Attr) bool {
90	return a.Key == b.Key && a.Value.Equal(b.Value)
91}
92
93func (a Attr) String() string {
94	return a.Key + "=" + a.Value.String()
95}
96
97// isEmpty reports whether a has an empty key and a nil value.
98// That can be written as Attr{} or Any("", nil).
99func (a Attr) isEmpty() bool {
100	return a.Key == "" && a.Value.num == 0 && a.Value.any == nil
101}
102