Not sure how to adapt your xUnit habits to Go? This is the course for you!
Sign up today to save 25% over the full price.
–
Sometimes you want to group several key/value attributes together when logging. Maybe different aspects of an error (error_code, error_detail, stacktrace, etc), or different aspects of an HTTP response (bytes_sent, status_code, etc). The log/slog package gives us this!
Groups
Attributes can be collected into groups. A group has a name that is used to qualify the names of its attributes. How this qualification is displayed depends on the handler. TextHandler separates the group and attribute names with a dot. JSONHandler treats each group as a separate JSON object, with the group name as the key.
Use Group to create a Group attribute from a name and a list of key-value pairs:
slog.Group("request", "method", r.Method, "url", r.URL)TextHandler would display this group as
request.method=GET request.url=http://example.comJSONHandler would display it as
"request":{"method":"GET","url":"http://example.com"}