Skip to content

proposal: log/slog: native support for handling List #71088

Open
@longit644

Description

@longit644

Proposal Details

The current implementation of log/slog does not fully support logging arrays or slices. As a result, the type implementing the slog.Valuer interface is not respected when passed as an element of an array or slice and the Handler cannot handle the elements within the input array or slice either.

One possible workaround is to create a custom List using a generic struct that implements the slog.LogValuer interface, returns a Group and uses the index as the key. An example of this approach can be found in this comment #63204 (comment)

However, it would make more sense and be more practical if List were natively supported

type listptr  *Value    // used in Value.any when the Value is a []Value

const (
	KindAny Kind = iota
	KindBool
	KindDuration
	KindFloat64
	KindInt64
	KindString
	KindTime
	KindUint64
	KindGroup
	KindLogValuer
        KindList 
)

// ListValue returns a [Value] for a slice of arbitrary values.
func ListValue(vs ...Value) Value {
	return Value{num: uint64(len(vs)), any: listptr(unsafe.SliceData(vs))}
}

// List returns v's value as a []Value.
// It panics if v's [Kind] is not [KindList].
func (v Value) List() []Value{
	if sp, ok := v.any.(listptr); ok {
		return unsafe.Slice((*Value)(sp), v.num)
	}
	panic("List: bad kind")
}

func (v Value) list() []Value{
	return unsafe.Slice((*Value)(v.any.(listptr)), v.num)
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    Status

    Incoming

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions