mirror of
https://github.com/andwati/zitadel.git
synced 2026-11-05 13:52:15 +00:00
# Which Problems Are Solved Zitadel did not provide easy correlation between errors, logs, traces and metrics. The configuration for those instrumentations was also not consistent, with some supporting different exporters then others. Implementation and parsing of config was also spaghettified over multiple packages, with awkward parsing and inconsistent naming of options. # How the Problems Are Solved All telemetry is now merged under the name "instrumentation". Why? 1. We thought it was a good idea in the past to call the milestone exporter `Telemtry` in the runtime config. Calling this `TelemetryV2` looks weird. 2. Not everything is a meter and not everything is sent (tele...). 3. It's also [defined](https://opentelemetry.io/docs/concepts/instrumentation/) as such by the OTEL documentation. ## New features - Adds structured, context based logging with trace-ID awareness - Static log fields are added to the context, such as service and request path - Static log fields are injected in each logline emitted by the application - Structured logs can also be send to an otel exporter - Structured logs can be printed to StdErr in text and JSON format - Error sinks make sure every error is logged at the correct level: - Warnings for client side errors (HTTP 400 range, Invalid request etc) - Error for server side errors (Internal server errors) - Metrics can now also be send to a OTEL collector. (previously they could only be scraped from `/debug/metrics` with prometheus) ## Exporters This change adds all the exporters supported by OTEL upstream and some google specific exporters for our cloud deployment. - StdOut / StdErr: all instrumentations - OTEL gRPC / HTTP: all instrumentations - Google: all instrumentations except logging - Prometheus (pull-based): only metrics The exception is profiling, which only supports the google exporting due to lack of support by OTEL upstream. ## Configuration and structure - All instrumentation is moved into the new `backend/v3/instrumentation` package. It reuses configuration types, so both code and runtime configuration are easier to understand. - The `internal/telemetry` packages are removed. - Instrumentation is started with a single function and a proper shutdown function is now provided. - Legacy configuration is still parsed from the runtime config, as long as the new configuration is disabled. This allows backporting this feature to v4 without breaking existing configurations. # Additional Changes - Devcontainer: set `$PATH` variable so installed go binaries can be run individually, without NX. - NX: install GCI tool to fix imports # Additional Context - Closes https://github.com/zitadel/zitadel/issues/8408 - Closes https://github.com/zitadel/zitadel/issues/6664 - Backport to v4
198 lines
5.3 KiB
Go
198 lines
5.3 KiB
Go
package instrumentation
|
|
|
|
import (
|
|
"context"
|
|
"log/slog"
|
|
"net/http"
|
|
"os"
|
|
"strings"
|
|
"time"
|
|
|
|
"connectrpc.com/connect"
|
|
"github.com/muhlemmer/sloggcp"
|
|
"github.com/rs/xid"
|
|
slogmulti "github.com/samber/slog-multi"
|
|
slogctx "github.com/veqryn/slog-context"
|
|
slogotel "github.com/veqryn/slog-context/otel"
|
|
"go.opentelemetry.io/contrib/bridges/otelslog"
|
|
"go.opentelemetry.io/otel/sdk/log"
|
|
"google.golang.org/grpc"
|
|
|
|
http_util "github.com/zitadel/zitadel/internal/api/http"
|
|
)
|
|
|
|
type LogFormat int
|
|
|
|
//go:generate enumer -type=LogFormat -trimprefix=LogFormat -text -linecomment
|
|
const (
|
|
// Empty line comment sets empty string of unspecified value
|
|
LogFormatUndefined LogFormat = iota //
|
|
LogFormatDisabled
|
|
LogFormatText
|
|
LogFormatJSON
|
|
// JSON formatted logs compatible with Google Cloud Platform
|
|
LogFormatGCP
|
|
)
|
|
|
|
type LogConfig struct {
|
|
Level slog.Level
|
|
Format LogFormat
|
|
AddSource bool
|
|
GoogleProjectID string
|
|
GoogleLogName string
|
|
Exporter ExporterConfig
|
|
}
|
|
|
|
// setLogger configures the global slog logger.
|
|
// Logs are sent to StdErr and/or the [log.LoggerProvider].
|
|
//
|
|
// When present in the context, each line emitted contains:
|
|
// - Trace ID
|
|
// - Span ID
|
|
// - Service name
|
|
// - Sanitized request hosts from [http_util.DomainCtx]
|
|
// - Request details, such as method and path.
|
|
func setLogger(provider *log.LoggerProvider, cfg LogConfig) {
|
|
options := &slog.HandlerOptions{
|
|
AddSource: cfg.AddSource,
|
|
Level: cfg.Level,
|
|
}
|
|
var stdErrHandler slog.Handler
|
|
switch cfg.Format {
|
|
case LogFormatUndefined:
|
|
return // uses default slog logger
|
|
case LogFormatDisabled:
|
|
stdErrHandler = slog.DiscardHandler
|
|
case LogFormatText:
|
|
stdErrHandler = slog.NewTextHandler(os.Stderr, options)
|
|
case LogFormatJSON:
|
|
stdErrHandler = slog.NewJSONHandler(os.Stderr, options)
|
|
case LogFormatGCP:
|
|
options.ReplaceAttr = sloggcp.ReplaceAttr
|
|
stdErrHandler = slog.NewJSONHandler(os.Stderr, options)
|
|
}
|
|
|
|
stdErrHandler = slogctx.NewHandler(
|
|
stdErrHandler,
|
|
&slogctx.HandlerOptions{
|
|
Prependers: []slogctx.AttrExtractor{
|
|
domainExtractor,
|
|
requestExtractor,
|
|
slogotel.ExtractTraceSpanID,
|
|
slogctx.ExtractPrepended,
|
|
},
|
|
},
|
|
)
|
|
|
|
otelHandler := otelslog.NewHandler(
|
|
Name,
|
|
otelslog.WithLoggerProvider(provider),
|
|
)
|
|
|
|
logger := slog.New(slogmulti.Fanout(stdErrHandler, otelHandler))
|
|
logger.Info("structured logger configured", "config_level", cfg.Level, "format", cfg.Format)
|
|
slog.SetDefault(logger)
|
|
}
|
|
|
|
const (
|
|
ProtocolHttp = "http"
|
|
ProtocolConnect = "connect"
|
|
ProtocolGrpc = "grpc"
|
|
)
|
|
|
|
// SetHttpRequestDetails adds static details to each context aware log entry.
|
|
func SetHttpRequestDetails(ctx context.Context, service string, request *http.Request) context.Context {
|
|
now := time.Now()
|
|
return context.WithValue(ctx, ctxKey{}, &requestDetails{
|
|
protocol: ProtocolHttp,
|
|
service: service,
|
|
http_method: request.Method,
|
|
path: request.URL.Path,
|
|
requestID: xid.NewWithTime(now),
|
|
start: now,
|
|
})
|
|
}
|
|
|
|
// SetConnectRequestDetails adds static details to each context aware log entry.
|
|
func SetConnectRequestDetails(ctx context.Context, request connect.AnyRequest) context.Context {
|
|
now := time.Now()
|
|
spec := request.Spec()
|
|
return context.WithValue(ctx, ctxKey{}, &requestDetails{
|
|
protocol: ProtocolConnect,
|
|
service: serviceFromRPCMethod(spec.Procedure),
|
|
http_method: request.HTTPMethod(),
|
|
path: spec.Procedure,
|
|
requestID: xid.NewWithTime(now),
|
|
start: now,
|
|
})
|
|
}
|
|
|
|
func SetGrpcRequestDetails(ctx context.Context, info *grpc.UnaryServerInfo) context.Context {
|
|
now := time.Now()
|
|
return context.WithValue(ctx, ctxKey{}, &requestDetails{
|
|
protocol: ProtocolGrpc,
|
|
service: serviceFromRPCMethod(info.FullMethod),
|
|
http_method: http.MethodPost, // gRPC always uses POST
|
|
path: info.FullMethod,
|
|
requestID: xid.NewWithTime(now),
|
|
start: now,
|
|
})
|
|
}
|
|
|
|
type ctxKey struct{}
|
|
|
|
type requestDetails struct {
|
|
protocol string
|
|
service string
|
|
http_method string
|
|
path string
|
|
requestID xid.ID
|
|
start time.Time
|
|
}
|
|
|
|
func (r *requestDetails) attrs() []slog.Attr {
|
|
attrs := make([]slog.Attr, 0, 6)
|
|
if r.protocol != "" {
|
|
attrs = append(attrs, slog.String("protocol", r.protocol))
|
|
}
|
|
if r.service != "" {
|
|
attrs = append(attrs, slog.String("service", r.service))
|
|
}
|
|
if r.http_method != "" {
|
|
attrs = append(attrs, slog.String("http_method", r.http_method))
|
|
}
|
|
if r.path != "" {
|
|
attrs = append(attrs, slog.String("path", r.path))
|
|
}
|
|
if !r.requestID.IsZero() {
|
|
attrs = append(attrs, slog.String("request_id", r.requestID.String()))
|
|
}
|
|
if !r.start.IsZero() {
|
|
attrs = append(attrs, slog.Duration("duration", time.Since(r.start)))
|
|
}
|
|
return attrs
|
|
}
|
|
|
|
func serviceFromRPCMethod(fullMethod string) string {
|
|
parts := strings.Split(fullMethod, "/")
|
|
if len(parts) >= 2 {
|
|
return parts[1]
|
|
}
|
|
return "unknown"
|
|
}
|
|
|
|
// domainExtractor sets the sanitized request hosts from [http_util.DomainCtx] to a log entry.
|
|
func domainExtractor(ctx context.Context, _ time.Time, _ slog.Level, _ string) []slog.Attr {
|
|
return []slog.Attr{
|
|
slog.Any("domain", http_util.DomainContext(ctx)),
|
|
}
|
|
}
|
|
|
|
// requestExtractor sets the request details from [requestDetails] to a log entry.
|
|
func requestExtractor(ctx context.Context, _ time.Time, _ slog.Level, _ string) []slog.Attr {
|
|
if r, ok := ctx.Value(ctxKey{}).(*requestDetails); ok {
|
|
return r.attrs()
|
|
}
|
|
return nil
|
|
}
|