feat: add logging for trace id (#1061)

relates to STACKITTPR-290
This commit is contained in:
Marcel Jacek 2025-11-27 11:06:18 +01:00 committed by GitHub
parent d1e12fcf64
commit 24b7387db9
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
140 changed files with 1597 additions and 7 deletions

View file

@ -7,6 +7,7 @@ import (
"strings"
"github.com/hashicorp/terraform-plugin-framework/types"
"github.com/stackitcloud/stackit-sdk-go/core/runtime"
"github.com/hashicorp/terraform-plugin-framework/diag"
"github.com/hashicorp/terraform-plugin-log/tflog"
@ -102,12 +103,20 @@ func DiagsToError(diags diag.Diagnostics) error {
// LogAndAddError Logs the error and adds it to the diags
func LogAndAddError(ctx context.Context, diags *diag.Diagnostics, summary, detail string) {
if traceId := runtime.GetTraceId(ctx); traceId != "" {
detail = fmt.Sprintf("%s\nTrace ID: %q", detail, traceId)
}
tflog.Error(ctx, fmt.Sprintf("%s | %s", summary, detail))
diags.AddError(summary, detail)
}
// LogAndAddWarning Logs the warning and adds it to the diags
func LogAndAddWarning(ctx context.Context, diags *diag.Diagnostics, summary, detail string) {
if traceId := runtime.GetTraceId(ctx); traceId != "" {
detail = fmt.Sprintf("%s\nTrace ID: %q", detail, traceId)
}
tflog.Warn(ctx, fmt.Sprintf("%s | %s", summary, detail))
diags.AddWarning(summary, detail)
}
@ -125,3 +134,22 @@ func LogAndAddErrorBeta(ctx context.Context, diags *diag.Diagnostics, name strin
tflog.Error(ctx, fmt.Sprintf("%s | %s", errTitle, errContent))
diags.AddError(errTitle, errContent)
}
// InitProviderContext extends the context to capture the http response
func InitProviderContext(ctx context.Context) context.Context {
// Capture http response to get trace-id
var httpResp *http.Response
return runtime.WithCaptureHTTPResponse(ctx, &httpResp)
}
// LogResponse logs the trace-id of the last request
func LogResponse(ctx context.Context) context.Context {
// Logs the trace-id of the request
traceId := runtime.GetTraceId(ctx)
ctx = tflog.SetField(ctx, "x-trace-id", traceId)
tflog.Info(ctx, "response data", map[string]interface{}{
"x-trace-id": traceId,
})
return ctx
}