SigNoz is an open-source, OpenTelemetry-native observability platform for your team and their AI agents. Get logs, metrics, and traces in one tool with features like APM, distributed tracing, log management, infra monitoring, etc. Combined with SigNoz MCP and a native AI teammate (in SigNoz Cloud) it helps you build more resilient apps.
TypeScript apmapplication-monitoringdistributed-tracinggogood-first-issuejaegerloglogsmetricsmonitoringnextjsobservabilityopen-sourceopentelemetryprometheusreactreactjsself-hostedtracingtypescript
fix: postprocess json logs message key (#11189)
Piyush Singariya847bc71f4eaa
diff --git a/go.mod b/go.modindex 83b3d4d33d..ba76f0029d 100644--- a/go.mod+++ b/go.mod@@ -11,6 +11,7 @@ require (github.com/SigNoz/signoz-otel-collector v0.144.3github.com/antlr4-go/antlr/v4 v4.13.1github.com/antonmedv/expr v1.15.3+ github.com/bytedance/sonic v1.14.1github.com/cespare/xxhash/v2 v2.3.0github.com/coreos/go-oidc/v3 v3.17.0github.com/dgraph-io/ristretto/v2 v2.3.0@@ -112,7 +113,6 @@ require (github.com/aws/aws-sdk-go-v2/service/sts v1.41.9 // indirectgithub.com/aws/smithy-go v1.24.2 // indirectgithub.com/bytedance/gopkg v0.1.3 // indirect- github.com/bytedance/sonic v1.14.1 // indirectgithub.com/bytedance/sonic/loader v0.3.0 // indirectgithub.com/cloudwego/base64x v0.1.6 // indirectgithub.com/emersion/go-sasl v0.0.0-20241020182733-b788ff22d5a6 // indirectdiff --git a/pkg/querier/consume.go b/pkg/querier/consume.goindex beeae9a65d..eaada79864 100644--- a/pkg/querier/consume.go+++ b/pkg/querier/consume.go@@ -12,8 +12,10 @@ import ("time""github.com/ClickHouse/clickhouse-go/v2/lib/driver"+ "github.com/SigNoz/signoz/pkg/errors"qbtypes "github.com/SigNoz/signoz/pkg/types/querybuildertypes/querybuildertypesv5""github.com/SigNoz/signoz/pkg/types/telemetrytypes"+ "github.com/bytedance/sonic")var (@@ -22,6 +24,8 @@ var (// written clickhouse query. The column alias indcate which value is// to be considered as final result (or target).legacyReservedColumnTargetAliases = []string{"__result", "__value", "result", "res", "value"}++ CodeFailUnmarshalJSONColumn = errors.MustNewCode("fail_unmarshal_json_column"))// consume reads every row and shapes it into the payload expected for the@@ -393,11 +397,16 @@ func readAsRaw(rows driver.Rows, queryName string) (*qbtypes.RawData, error) {// de-reference the typed pointer to anyval := reflect.ValueOf(cellPtr).Elem().Interface()- // Post-process JSON columns: normalize into String value+ // Post-process JSON columns: unmarshal bytes into map[string]anyif strings.HasPrefix(strings.ToUpper(colTypes[i].DatabaseTypeName()), "JSON") {switch x := val.(type) {case []byte:- val = string(x)+ var m map[string]any+ err := sonic.Unmarshal(x, &m)+ if err != nil {+ return nil, errors.WrapInternalf(err, CodeFailUnmarshalJSONColumn, "failed to unmarshal JSON column %s", name)+ }+ val = mdefault:// already a structured type (map[string]any, []any, etc.)}diff --git a/pkg/querier/postprocess.go b/pkg/querier/postprocess.goindex 104e6dd3d6..954ef89d0f 100644--- a/pkg/querier/postprocess.go+++ b/pkg/querier/postprocess.go@@ -12,9 +12,12 @@ import ("github.com/SigNoz/govaluate""github.com/SigNoz/signoz/pkg/errors"+ "github.com/SigNoz/signoz/pkg/flagger"+ "github.com/SigNoz/signoz/pkg/types/featuretypes""github.com/SigNoz/signoz/pkg/querybuilder"qbtypes "github.com/SigNoz/signoz/pkg/types/querybuildertypes/querybuildertypesv5""github.com/SigNoz/signoz/pkg/types/telemetrytypes"+ "github.com/SigNoz/signoz/pkg/valuer")// queryInfo holds common query properties.@@ -50,7 +53,7 @@ func getQueryName(spec any) string {return getqueryInfo(spec).Name}-func (q *querier) postProcessResults(ctx context.Context, results map[string]any, req *qbtypes.QueryRangeRequest) (map[string]any, error) {+func (q *querier) postProcessResults(ctx context.Context, orgID valuer.UUID, results map[string]any, req *qbtypes.QueryRangeRequest) (map[string]any, error) {// Convert results to typed format for processingtypedResults := make(map[string]*qbtypes.Result)for name, result := range results {@@ -69,6 +72,7 @@ func (q *querier) postProcessResults(ctx context.Context, results map[string]anycase qbtypes.QueryBuilderQuery[qbtypes.LogAggregation]:if result, ok := typedResults[spec.Name]; ok {result = postProcessBuilderQuery(q, result, spec, req)+ result = q.postProcessLogBody(ctx, orgID, result, req)typedResults[spec.Name] = result}case qbtypes.QueryBuilderQuery[qbtypes.MetricAggregation]:@@ -1046,3 +1050,33 @@ func (q *querier) calculateFormulaStep(expression string, req *qbtypes.QueryRangreturn result}++// postProcessLogBody removes the "message" key from the body map when it is empty.+// Only runs for raw list queries with the use_json_body feature enabled.+func (q *querier) postProcessLogBody(ctx context.Context, orgID valuer.UUID, result *qbtypes.Result, req *qbtypes.QueryRangeRequest) *qbtypes.Result {+ if req.RequestType != qbtypes.RequestTypeRaw {+ return result+ }+ if !q.fl.BooleanOrEmpty(ctx, flagger.FeatureUseJSONBody, featuretypes.NewFlaggerEvaluationContext(orgID)) {+ return result+ }+ rawData, ok := result.Value.(*qbtypes.RawData)+ if !ok {+ return result+ }+ for _, row := range rawData.Rows {+ bodyMap, ok := row.Data["body"].(map[string]any)+ if !ok {+ continue+ }+ if msg, exists := bodyMap["message"]; exists {+ switch v := msg.(type) {+ case string:+ if v == "" {+ delete(bodyMap, "message")+ }+ }+ }+ }+ return result+}diff --git a/pkg/querier/querier.go b/pkg/querier/querier.goindex 304b3b1269..14cdad5833 100644--- a/pkg/querier/querier.go+++ b/pkg/querier/querier.go@@ -16,6 +16,7 @@ import ("github.com/SigNoz/signoz/pkg/errors""github.com/SigNoz/signoz/pkg/factory"+ "github.com/SigNoz/signoz/pkg/flagger""github.com/SigNoz/signoz/pkg/prometheus""github.com/SigNoz/signoz/pkg/query-service/utils""github.com/SigNoz/signoz/pkg/querybuilder"@@ -35,6 +36,7 @@ var (type querier struct {logger *slog.Logger+ fl flagger.FlaggertelemetryStore telemetrystore.TelemetryStoremetadataStore telemetrytypes.MetadataStorepromEngine prometheus.Prometheus@@ -62,10 +64,12 @@ func New(meterStmtBuilder qbtypes.StatementBuilder[qbtypes.MetricAggregation],traceOperatorStmtBuilder qbtypes.TraceOperatorStatementBuilder,bucketCache BucketCache,+ flagger flagger.Flagger,) *querier {querierSettings := factory.NewScopedProviderSettings(settings, "github.com/SigNoz/signoz/pkg/querier")return &querier{logger: querierSettings.Logger(),+ fl: flagger,telemetryStore: telemetryStore,metadataStore: metadataStore,promEngine: promEngine,@@ -684,7 +688,7 @@ func (q *querier) run(}gomaps.Copy(results, preseededResults)- processedResults, err := q.postProcessResults(ctx, results, req)+ processedResults, err := q.postProcessResults(ctx, orgID, results, req)if err != nil {return nil, err}diff --git a/pkg/querier/querier_test.go b/pkg/querier/querier_test.goindex f49c06a421..cda1171c7f 100644--- a/pkg/querier/querier_test.go+++ b/pkg/querier/querier_test.go@@ -7,6 +7,7 @@ import (cmock "github.com/srikanthccv/ClickHouse-go-mock"+ "github.com/SigNoz/signoz/pkg/flagger/flaggertest""github.com/SigNoz/signoz/pkg/instrumentation/instrumentationtest""github.com/SigNoz/signoz/pkg/telemetrystore""github.com/SigNoz/signoz/pkg/telemetrystore/telemetrystoretest"@@ -44,14 +45,15 @@ func TestQueryRange_MetricTypeMissing(t *testing.T) {providerSettings,nil, // telemetryStoremetadataStore,- nil, // prometheus- nil, // traceStmtBuilder- nil, // logStmtBuilder- nil, // auditStmtBuilder- nil, // metricStmtBuilder- nil, // meterStmtBuilder- nil, // traceOperatorStmtBuilder- nil, // bucketCache+ nil, // prometheus+ nil, // traceStmtBuilder+ nil, // logStmtBuilder+ nil, // auditStmtBuilder+ nil, // metricStmtBuilder+ nil, // meterStmtBuilder+ nil, // traceOperatorStmtBuilder+ nil, // bucketCache+ flaggertest.New(t), // flagger)req := &qbtypes.QueryRangeRequest{@@ -116,6 +118,7 @@ func TestQueryRange_MetricTypeFromStore(t *testing.T) {nil, // meterStmtBuildernil, // traceOperatorStmtBuildernil, // bucketCache+ flaggertest.New(t), // flagger)req := &qbtypes.QueryRangeRequest{diff --git a/pkg/querier/signozquerier/provider.go b/pkg/querier/signozquerier/provider.goindex c9cf8910e1..2ece6bec23 100644--- a/pkg/querier/signozquerier/provider.go+++ b/pkg/querier/signozquerier/provider.go@@ -186,5 +186,6 @@ func newProvider(meterStmtBuilder,traceOperatorStmtBuilder,bucketCache,+ flagger,), nil}diff --git a/pkg/query-service/rules/setups_test.go b/pkg/query-service/rules/setups_test.goindex e03c2ad8dc..d974c21a60 100644--- a/pkg/query-service/rules/setups_test.go+++ b/pkg/query-service/rules/setups_test.go@@ -53,6 +53,7 @@ func prepareQuerierForMetrics(t *testing.T, telemetryStore telemetrystore.Telemenil, // meterStmtBuildernil, // traceOperatorStmtBuildernil, // bucketCache+ flagger,), metadataStore}@@ -102,6 +103,7 @@ func prepareQuerierForLogs(t *testing.T, telemetryStore telemetrystore.Telemetrynil, // meterStmtBuildernil, // traceOperatorStmtBuildernil, // bucketCache+ fl,)}@@ -146,5 +148,6 @@ func prepareQuerierForTraces(t *testing.T, telemetryStore telemetrystore.Telemetnil, // meterStmtBuildernil, // traceOperatorStmtBuildernil, // bucketCache+ fl,)}diff --git a/tests/integration/tests/querier_json_body/01_logs_json_body_new_qb.py b/tests/integration/tests/querier_json_body/01_logs_json_body_new_qb.pyindex efa8ff796e..f7544bdd11 100644--- a/tests/integration/tests/querier_json_body/01_logs_json_body_new_qb.py+++ b/tests/integration/tests/querier_json_body/01_logs_json_body_new_qb.py@@ -21,7 +21,7 @@ from fixtures.querier import (def _get_bodies(response: requests.Response) -> list[dict[str, Any]]:- return [json.loads(row["data"]["body"]) for row in get_rows(response)]+ return [row["data"]["body"] for row in get_rows(response)]def _run_query_case(signoz: types.SigNoz, token: str, now: datetime, case: dict[str, Any]) -> None:@@ -1188,7 +1188,7 @@ def test_message_searches(token = get_token(email=USER_ADMIN_EMAIL, password=USER_ADMIN_PASSWORD)def _body_messages(response: requests.Response) -> list[str]:- return [json.loads(row["data"]["body"]).get("message", "") for row in get_rows(response)]+ return [row["data"]["body"].get("message", "") for row in get_rows(response)]payment_messages = {"Payment processed successfully",diff --git a/tests/integration/tests/querier_json_body/02_non_body_fields.py b/tests/integration/tests/querier_json_body/02_non_body_fields.pyindex 2470adc26d..aa379022d8 100644--- a/tests/integration/tests/querier_json_body/02_non_body_fields.py+++ b/tests/integration/tests/querier_json_body/02_non_body_fields.py@@ -69,11 +69,11 @@ def _scalar(def _body_users(response: requests.Response) -> set[str | None]:- return {json.loads(row["data"]["body"]).get("user") for row in get_rows(response)}+ return {row["data"]["body"].get("user") for row in get_rows(response)}def _body_scores(response: requests.Response) -> list[int | None]:- return [json.loads(row["data"]["body"]).get("score") for row in get_rows(response)]+ return [row["data"]["body"].get("score") for row in get_rows(response)]def _services(response: requests.Response) -> list[str]: