Skip to content

Consider Helper() Function to Fix Log Entry @caller Information #29

@bflad

Description

@bflad

terraform-plugin-log version

v0.2.1

Use cases

When implementing subsystem loggers, it can be helpful to create a package and wrapper functions for the tflog.SubsystemX() (or for the SDKs, tfsdklog.SubsystemX()) calls to simplify and potentially clarify the code, e.g.

//
// NOTE: This is a SDK-specific example. Providers should always use the tflog package.
//
package logging

import (
	"context"

	"github.com/hashicorp/terraform-plugin-log/tfsdklog"
)

const (
	// SubsystemProto is the tfsdklog subsystem name for protocol logging.
	SubsystemProto = "proto"
)

// ProtocolError emits a protocol subsystem log at ERROR level.
func ProtocolError(ctx context.Context, msg string, args ...interface{}) {
	tfsdklog.SubsystemError(ctx, SubsystemProto, msg, args)
}

// ProtocolTrace emits a protocol subsystem log at TRACE level.
func ProtocolTrace(ctx context.Context, msg string, args ...interface{}) {
	tfsdklog.SubsystemTrace(ctx, SubsystemProto, msg, args)
}

Which makes calling code fairly concise:

logging.ProtocolTrace(ctx, "Received request")

When doing this, the log entries are then off by one frame in the @caller (pretty printed for clarity):

{
    "@caller": "/Users/bflad/go/pkg/mod/github.com/hashicorp/terraform-plugin-go@v0.7.0/internal/logging/protocol.go:21",
    "@level": "trace",
    "@message": "Received request",
    "@module": "sdk.proto",
    "@timestamp": "2022-02-04T16:28:52.602080-05:00",
    "EXTRA_VALUE_AT_END": null,
    "tf_proto_version": "5.2",
    "tf_provider_addr": "",
    "tf_req_id": "a24b8a29-628a-01c2-0516-08b260627109",
    "tf_rpc": "GetProviderSchema"
}

Which makes troubleshooting slightly harder.

Proposal

Similar to how the Go standard library testing package implements T.Helper(), which is defined as:

Helper marks the calling function as a test helper function. When printing file and line information, that function will be skipped. Helper may be called simultaneously from multiple goroutines.

It might be possible to do something similar with these packages so callers can signify that the final frame in the stack should be ignored for file and line information.

Metadata

Metadata

Assignees

Labels

enhancementNew feature or request

Type

No type

Projects

No projects

Milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions