Skip to content

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.

feat(logs): render DataViewer with filter/group-by actions in log details overview (#12426)

Aditya Singhfb106b3253a6
diff --git a/frontend/jest.config.ts b/frontend/jest.config.ts
index 9b9fcd2f98..66427cb23e 100644
--- a/frontend/jest.config.ts
+++ b/frontend/jest.config.ts
@@ -56,10 +56,10 @@ const config: Config.InitialOptions = {
transformIgnorePatterns: [
// @chenglou/pretext is ESM-only; @signozhq/ui pulls it in via text-ellipsis.
// Pattern 1: allow .pnpm virtual store through (handled by pattern 2), plus root-level ESM packages.
- 'node_modules/(?!(\\.pnpm|lodash-es|react-dnd|core-dnd|@react-dnd|dnd-core|react-dnd-html5-backend|axios|@chenglou/pretext|@signozhq/design-tokens|@signozhq|date-fns|d3-interpolate|d3-color|api|@codemirror|@lezer|@marijn|@grafana|nuqs|uuid|copy-text-to-clipboard|react-markdown|vfile|vfile-message|unist-util-stringify-position|unified|bail|is-plain-obj|trough|remark-parse|mdast-util-from-markdown|mdast-util-to-string|micromark|micromark-core-commonmark|micromark-extension-gfm|micromark-extension-gfm-autolink-literal|micromark-extension-gfm-footnote|micromark-extension-gfm-strikethrough|micromark-extension-gfm-table|micromark-extension-gfm-tagfilter|micromark-extension-gfm-task-list-item|micromark-factory-destination|micromark-factory-label|micromark-factory-space|micromark-factory-title|micromark-factory-whitespace|micromark-util-character|micromark-util-chunked|micromark-util-classify-character|micromark-util-combine-extensions|micromark-util-decode-numeric-character-reference|micromark-util-decode-string|micromark-util-encode|micromark-util-html-tag-name|micromark-util-normalize-identifier|micromark-util-resolve-all|micromark-util-sanitize-uri|micromark-util-subtokenize|micromark-util-symbol|micromark-util-types|decode-named-character-reference|remark-rehype|mdast-util-to-hast|unist-util-position|trim-lines|unist-util-visit|unist-util-visit-parents|unist-util-is|unist-util-generated|mdast-util-definitions|property-information|hast-util-whitespace|space-separated-tokens|comma-separated-tokens|rehype-raw|hast-util-raw|hast-util-from-parse5|devlop|hastscript|hast-util-parse-selector|vfile-location|web-namespaces|hast-util-to-parse5|zwitch|html-void-elements)/)',
+ 'node_modules/(?!(\\.pnpm|react-json-tree|react-base16-styling|lodash-es|react-dnd|core-dnd|@react-dnd|dnd-core|react-dnd-html5-backend|axios|@chenglou/pretext|@signozhq/design-tokens|@signozhq|date-fns|d3-interpolate|d3-color|api|@codemirror|@lezer|@marijn|@grafana|nuqs|uuid|copy-text-to-clipboard|react-markdown|vfile|vfile-message|unist-util-stringify-position|unified|bail|is-plain-obj|trough|remark-parse|mdast-util-from-markdown|mdast-util-to-string|micromark|micromark-core-commonmark|micromark-extension-gfm|micromark-extension-gfm-autolink-literal|micromark-extension-gfm-footnote|micromark-extension-gfm-strikethrough|micromark-extension-gfm-table|micromark-extension-gfm-tagfilter|micromark-extension-gfm-task-list-item|micromark-factory-destination|micromark-factory-label|micromark-factory-space|micromark-factory-title|micromark-factory-whitespace|micromark-util-character|micromark-util-chunked|micromark-util-classify-character|micromark-util-combine-extensions|micromark-util-decode-numeric-character-reference|micromark-util-decode-string|micromark-util-encode|micromark-util-html-tag-name|micromark-util-normalize-identifier|micromark-util-resolve-all|micromark-util-sanitize-uri|micromark-util-subtokenize|micromark-util-symbol|micromark-util-types|decode-named-character-reference|remark-rehype|mdast-util-to-hast|unist-util-position|trim-lines|unist-util-visit|unist-util-visit-parents|unist-util-is|unist-util-generated|mdast-util-definitions|property-information|hast-util-whitespace|space-separated-tokens|comma-separated-tokens|rehype-raw|hast-util-raw|hast-util-from-parse5|devlop|hastscript|hast-util-parse-selector|vfile-location|web-namespaces|hast-util-to-parse5|zwitch|html-void-elements)/)',
// Pattern 2: pnpm virtual store — ignore everything except ESM-only packages.
// pnpm encodes scoped packages as @scope+name@version, so match on scope prefix.
- 'node_modules/\\.pnpm/(?!(lodash-es|react-dnd|core-dnd|@react-dnd|dnd-core|react-dnd-html5-backend|axios|@chenglou|@signozhq|date-fns|d3-interpolate|d3-color|api|@codemirror|@lezer|@marijn|@grafana|nuqs|uuid|copy-text-to-clipboard|react-markdown|vfile|vfile-message|unist-util-stringify-position|unified|bail|is-plain-obj|trough|remark-parse|mdast-util-from-markdown|mdast-util-to-string|micromark|decode-named-character-reference|remark-rehype|mdast-util-to-hast|unist-util-position|trim-lines|unist-util-visit|unist-util-visit-parents|unist-util-is|unist-util-generated|mdast-util-definitions|property-information|hast-util-whitespace|space-separated-tokens|comma-separated-tokens|rehype-raw|hast-util-raw|hast-util-from-parse5|devlop|hastscript|hast-util-parse-selector|vfile-location|web-namespaces|hast-util-to-parse5|zwitch|html-void-elements)[^/]*/node_modules)',
+ 'node_modules/\\.pnpm/(?!(react-json-tree|react-base16-styling|lodash-es|react-dnd|core-dnd|@react-dnd|dnd-core|react-dnd-html5-backend|axios|@chenglou|@signozhq|date-fns|d3-interpolate|d3-color|api|@codemirror|@lezer|@marijn|@grafana|nuqs|uuid|copy-text-to-clipboard|react-markdown|vfile|vfile-message|unist-util-stringify-position|unified|bail|is-plain-obj|trough|remark-parse|mdast-util-from-markdown|mdast-util-to-string|micromark|decode-named-character-reference|remark-rehype|mdast-util-to-hast|unist-util-position|trim-lines|unist-util-visit|unist-util-visit-parents|unist-util-is|unist-util-generated|mdast-util-definitions|property-information|hast-util-whitespace|space-separated-tokens|comma-separated-tokens|rehype-raw|hast-util-raw|hast-util-from-parse5|devlop|hastscript|hast-util-parse-selector|vfile-location|web-namespaces|hast-util-to-parse5|zwitch|html-void-elements)[^/]*/node_modules)',
],
setupFilesAfterEnv: ['<rootDir>/jest.setup.ts'],
testPathIgnorePatterns: ['/node_modules/', '/public/'],
diff --git a/frontend/src/components/LogDetail/LogDetails.styles.scss b/frontend/src/components/LogDetail/LogDetails.styles.scss
index 141efa63d1..24c26684ca 100644
--- a/frontend/src/components/LogDetail/LogDetails.styles.scss
+++ b/frontend/src/components/LogDetail/LogDetails.styles.scss
@@ -41,8 +41,7 @@
.ant-drawer-body {
display: flex;
flex-direction: column;
- padding: 16px;
- padding-bottom: 0;
+ padding: 0 16px;
}
.title {
@@ -79,6 +78,7 @@
align-items: center;
gap: 4px;
position: relative;
+ margin-top: 16px;
.log-body {
font-family: 'SF Mono';
@@ -123,6 +123,19 @@
}
}
+ .log-detail-drawer__section-divider {
+ height: 8px;
+ margin: 12px 0;
+ background-image:
+ radial-gradient(circle, var(--l3-border) 1px, transparent 1px),
+ radial-gradient(circle, var(--l3-border) 1px, transparent 1px);
+ background-size: 6px 2px;
+ background-position:
+ left top,
+ left bottom;
+ background-repeat: repeat-x;
+ }
+
.tabs-and-search {
display: flex;
justify-content: space-between;
diff --git a/frontend/src/components/LogDetail/__tests__/LogDetail.test.tsx b/frontend/src/components/LogDetail/__tests__/LogDetail.test.tsx
index c7b4b45b87..4d3171daf9 100644
--- a/frontend/src/components/LogDetail/__tests__/LogDetail.test.tsx
+++ b/frontend/src/components/LogDetail/__tests__/LogDetail.test.tsx
@@ -11,6 +11,13 @@ jest.mock('@signozhq/ui/sonner', () => ({
toast: { success: jest.fn(), error: jest.fn() },
}));
+// DataViewer pulls in react-json-tree (ESM) + Monaco; mock it (as trace's tests
+// do). These drawer tests assert the header/highlights, not the Overview body.
+jest.mock('periscope/components/DataViewer', () => ({
+ __esModule: true,
+ DataViewer: (): JSX.Element => <div data-testid="overview-data-viewer" />,
+}));
+
// The flag to be removed later
jest.mock('../constants', () => ({
...jest.requireActual('../constants'),
@@ -66,6 +73,12 @@ describe('LogDetail drawer — header (isLogDetailsV2)', () => {
expect(screen.getByTestId('log-details-header-next')).toBeInTheDocument();
});
+ it('renders the DataViewer in the Overview tab', () => {
+ renderDrawer();
+
+ expect(screen.getByTestId('overview-data-viewer')).toBeInTheDocument();
+ });
+
it('shows the log timestamp formatted (DASH_DATETIME) in the header', () => {
// Pin the timezone to UTC so the formatted output is deterministic across
// machines/CI (Jest doesn't fix a TZ).
diff --git a/frontend/src/components/LogDetail/index.tsx b/frontend/src/components/LogDetail/index.tsx
index 6d6791ceca..a86dbcad68 100644
--- a/frontend/src/components/LogDetail/index.tsx
+++ b/frontend/src/components/LogDetail/index.tsx
@@ -402,6 +402,8 @@ function LogDetailInner({
{isLogDetailsV2 && <LogHighlights log={log} />}
+ {isLogDetailsV2 && <div className="log-detail-drawer__section-divider" />}
+
<div className="tabs-and-search">
<ToggleGroupSimple
type="single"
@@ -418,15 +420,21 @@ function LogDetailInner({
</div>
),
},
- {
- value: VIEW_TYPES.JSON,
- label: (
- <div className="view-title">
- <Braces size={14} />
- JSON
- </div>
- ),
- },
+ // V2's DataViewer has its own Pretty/JSON toggle, so the separate
+ // JSON tab is redundant.
+ ...(isLogDetailsV2
+ ? []
+ : [
+ {
+ value: VIEW_TYPES.JSON,
+ label: (
+ <div className="view-title">
+ <Braces size={14} />
+ JSON
+ </div>
+ ),
+ },
+ ]),
{
value: VIEW_TYPES.CONTEXT,
label: (
@@ -509,7 +517,7 @@ function LogDetailInner({
handleChangeSelectedView={handleChangeSelectedView}
/>
)}
- {selectedView === VIEW_TYPES.JSON && (
+ {!isLogDetailsV2 && selectedView === VIEW_TYPES.JSON && (
<JsonView data={LogJsonData} height="68vh" />
)}
diff --git a/frontend/src/container/LogDetailedView/Overview.styles.scss b/frontend/src/container/LogDetailedView/Overview.styles.scss
index a0a413c4b1..ebf24a2a43 100644
--- a/frontend/src/container/LogDetailedView/Overview.styles.scss
+++ b/frontend/src/container/LogDetailedView/Overview.styles.scss
@@ -1,4 +1,21 @@
.overview-container {
+ .data-viewer {
+ min-height: 500px;
+ }
+
+ .pretty-view__search-wrapper {
+ background: var(--l2-background);
+ }
+
+ .pretty-view__search-input {
+ background: var(--l2-background) !important;
+ }
+
+ .log-body-value {
+ white-space: pre-wrap;
+ overflow-wrap: anywhere;
+ }
+
.tag {
border-radius: 20px;
border: 1px solid color-mix(in srgb, var(--bg-sienna-500) 20%, transparent);
diff --git a/frontend/src/container/LogDetailedView/Overview.tsx b/frontend/src/container/LogDetailedView/Overview.tsx
index 3713e1de67..2fb3e0ad33 100644
--- a/frontend/src/container/LogDetailedView/Overview.tsx
+++ b/frontend/src/container/LogDetailedView/Overview.tsx
@@ -13,15 +13,28 @@ import { ChangeViewFunctionType } from 'container/ExplorerOptions/types';
import { OptionsQuery } from 'container/OptionsMenu/types';
import { useIsDarkMode } from 'hooks/useDarkMode';
import { ChevronDown, ChevronRight, Search } from '@signozhq/icons';
+import { isLogDetailsV2 } from 'components/LogDetail/constants';
+import { DataViewer } from 'periscope/components/DataViewer';
import { IField } from 'types/api/logs/fields';
import { ILog } from 'types/api/logs/log';
import { ActionItemProps } from './ActionItem';
+import { useLogAttributeActions } from './hooks/useLogAttributeActions';
import TableView from './TableView';
-import { getBodyDisplayString, removeEscapeCharacters } from './utils';
+import {
+ aggregateAttributesResourcesToObject,
+ getBodyDisplayString,
+ getSanitizedLogBody,
+ parseJsonStringBody,
+ removeEscapeCharacters,
+} from './utils';
import './Overview.styles.scss';
+// Skip body sanitization above this size. sanitization is expensive and fails
+// for large bodies
+const MAX_BODY_SANITIZE_CHARS = 64 * 1024;
+
interface OverviewProps {
logData: ILog;
isListViewPanel?: boolean;
@@ -51,6 +64,56 @@ function Overview({
const isDarkMode = useIsDarkMode();
+ const { actions, visibleActions } = useLogAttributeActions({
+ handleChangeSelectedView,
+ isListViewPanel,
+ });
+
+ if (isLogDetailsV2) {
+ const raw = aggregateAttributesResourcesToObject(logData);
+ const prettyData = Object.fromEntries(
+ Object.entries({ ...raw, body: parseJsonStringBody(raw.body) }).filter(
+ ([, value]) => value !== undefined,
+ ),
+ );
+ return (
+ <div className="overview-container">
+ <DataViewer
+ data={prettyData}
+ drawerKey="logs-details"
+ fontSize={13}
+ prettyViewProps={{
+ actions,
+ visibleActions,
+ renderLeafValue: (value, keyPath): ReactNode | undefined => {
+ // Sanitize (unescape + ANSI→color) string values under `body`.
+ // Skip huge ones (render raw, still safe) to avoid the sanitize
+ // choke;
+ if (
+ typeof value !== 'string' ||
+ keyPath[keyPath.length - 1] !== 'body' ||
+ value.length > MAX_BODY_SANITIZE_CHARS
+ ) {
+ return undefined;
+ }
+ return (
+ <span
+ className="log-body-value"
+ // Safe: getSanitizedLogBody runs the value through dompurify.
+ // eslint-disable-next-line react/no-danger
+ dangerouslySetInnerHTML={{
+ __html: getSanitizedLogBody(value, { shouldEscapeHtml: true }),
+ }}
+ />
+ );
+ },
+ }}
+ jsonString={JSON.stringify(raw, null, 2)}
+ />
+ </div>
+ );
+ }
+
const options: EditorProps['options'] = {
automaticLayout: true,
readOnly: true,
diff --git a/frontend/src/container/LogDetailedView/constants.ts b/frontend/src/container/LogDetailedView/constants.ts
new file mode 100644
index 0000000000..d9aaaccdc0
--- /dev/null
+++ b/frontend/src/container/LogDetailedView/constants.ts
@@ -0,0 +1,13 @@
+export enum LogAttributeBucket {
+ ATTRIBUTES = 'attributes',
+ RESOURCES = 'resources',
+ SCOPE = 'scope',
+}
+
+export enum LogDetailsAction {
+ COPY = 'copy',
+ FILTER_IN = 'filter-in',
+ FILTER_OUT = 'filter-out',
+ GROUP_BY = 'group-by',
+ REPLACE_FILTER = 'replace-filter',
+}
diff --git a/frontend/src/container/LogDetailedView/hooks/useLogAttributeActions.tsx b/frontend/src/container/LogDetailedView/hooks/useLogAttributeActions.tsx
new file mode 100644
index 0000000000..0565cdc960
--- /dev/null
+++ b/frontend/src/container/LogDetailedView/hooks/useLogAttributeActions.tsx
@@ -0,0 +1,232 @@
+import { useCallback, useMemo } from 'react';
+import { useLocation } from 'react-router-dom';
+import { CircleMinus, CirclePlus, Layers, RefreshCw } from '@signozhq/icons';
+import { FeatureKeys } from 'constants/features';
+import { QueryParams } from 'constants/query';
+import ROUTES from 'constants/routes';
+import { ChangeViewFunctionType } from 'container/ExplorerOptions/types';
+import { useGetSearchQueryParam } from 'hooks/queryBuilder/useGetSearchQueryParam';
+import { useQueryBuilder } from 'hooks/queryBuilder/useQueryBuilder';
+import { ICurrentQueryData } from 'hooks/useHandleExplorerTabChange';
+import { ExplorerViews } from 'pages/LogsExplorer/utils';
+import {
+ FieldContext,
+ PrettyViewAction,
+ VisibleActionsConfig,
+} from 'periscope/components/PrettyView/PrettyView';
+import { useAppContext } from 'providers/App/App';
+
+import { LogDetailsAction } from '../constants';
+import {
+ buildLogFilterTarget,
+ getFilterQueryData,
+ getGroupByQueryData,
+ getReplaceFilterQueryData,
+} from '../logAttributeActions.utils';
+
+interface UseLogAttributeActionsParams {
+ handleChangeSelectedView?: ChangeViewFunctionType;
+ isListViewPanel?: boolean;
+}
+
+interface UseLogAttributeActionsResult {
+ actions: PrettyViewAction[];
+ visibleActions: VisibleActionsConfig;
+}
+
+const COPY_ONLY_ACTIONS = [LogDetailsAction.COPY];
+const ALL_LEAF_ACTIONS = [
+ LogDetailsAction.COPY,
+ LogDetailsAction.FILTER_IN,
+ LogDetailsAction.FILTER_OUT,
+ LogDetailsAction.GROUP_BY,
+ LogDetailsAction.REPLACE_FILTER,
+];
+
+/**
+ * PrettyView filter/group-by/replace actions for the log-details drawer (keys mapped via
+ * buildLogFilterTarget). Also owns `visibleActions` (leaf/nested + list-panel copy-only).
+ */
+export function useLogAttributeActions({
+ handleChangeSelectedView,
+ isListViewPanel = false,
+}: UseLogAttributeActionsParams): UseLogAttributeActionsResult {
+ const { pathname } = useLocation();
+ const { stagedQuery, updateQueriesData } = useQueryBuilder();
+ const { featureFlags } = useAppContext();
+ const viewName = useGetSearchQueryParam(QueryParams.viewName) || '';
+
+ const isBodyJsonQueryEnabled =
+ featureFlags?.find((flag) => flag.name === FeatureKeys.USE_JSON_BODY)
+ ?.active || false;
+
+ const isOldExplorerOrLive =
+ pathname === ROUTES.OLD_LOGS_EXPLORER || pathname === ROUTES.LIVE_LOGS;
+
+ const filterFor = useCallback(
+ (context: FieldContext, isFilterIn: boolean): void => {
+ if (!stagedQuery) {
+ return;
+ }
+ const target = buildLogFilterTarget(
+ context.fieldKeyPath,
+ context.fieldValue,
+ isBodyJsonQueryEnabled,
+ );
+ const operator = isFilterIn
+ ? target.filterInOperator
+ : target.filterOutOperator;
+
+ const updatedQuery = updateQueriesData(
+ stagedQuery,
+ 'queryData',
+ (item, index) =>
+ index === 0
+ ? getFilterQueryData(item, target, context.fieldValue, operator)
+ : item,
+ );
+
+ const queryData: ICurrentQueryData = {
+ name: viewName,
+ id: updatedQuery.id,
+ query: updatedQuery,
+ };
+ handleChangeSelectedView?.(ExplorerViews.LIST, queryData);
+ },
+ [
+ stagedQuery,
+ isBodyJsonQueryEnabled,
+ updateQueriesData,
+ viewName,
+ handleChangeSelectedView,
+ ],
+ );
+
+ const groupBy = useCallback(
+ (context: FieldContext): void => {
+ if (!stagedQuery) {
+ return;
+ }
+ const target = buildLogFilterTarget(
+ context.fieldKeyPath,
+ context.fieldValue,
+ isBodyJsonQueryEnabled,
+ );
+ if (!target.groupBySupported || !target.groupByKey) {
+ return;
+ }
+
+ const updatedQuery = updateQueriesData(
+ stagedQuery,
+ 'queryData',
+ (item, index) => (index === 0 ? getGroupByQueryData(item, target) : item),
+ );
+
+ const queryData: ICurrentQueryData = {
+ name: viewName,
+ id: updatedQuery.id,
+ query: updatedQuery,
+ };
+ handleChangeSelectedView?.(ExplorerViews.TIMESERIES, queryData);
+ },
+ [
+ stagedQuery,
+ isBodyJsonQueryEnabled,
+ updateQueriesData,
+ viewName,
+ handleChangeSelectedView,
+ ],
+ );
+
+ const replaceFilter = useCallback(
+ (context: FieldContext): void => {
+ if (!stagedQuery) {
+ return;
+ }
+ const target = buildLogFilterTarget(
+ context.fieldKeyPath,
+ context.fieldValue,
+ isBodyJsonQueryEnabled,
+ );
+
+ const updatedQuery = updateQueriesData(
+ stagedQuery,
+ 'queryData',
+ (item, index) =>
+ index === 0
+ ? getReplaceFilterQueryData(item, target, context.fieldValue)
+ : item,
+ );
+
+ const queryData: ICurrentQueryData = {
+ name: viewName,
+ id: updatedQuery.id,
+ query: updatedQuery,
+ };
+ handleChangeSelectedView?.(ExplorerViews.LIST, queryData);
+ },
+ [
+ stagedQuery,
+ isBodyJsonQueryEnabled,
+ updateQueriesData,
+ viewName,
+ handleChangeSelectedView,
+ ],
+ );
+
+ const actions: PrettyViewAction[] = useMemo(() => {
+ const isRestricted = (fieldKeyPath: (string | number)[]): boolean =>
+ buildLogFilterTarget(fieldKeyPath, undefined, isBodyJsonQueryEnabled)
+ .isRestricted;
+
+ return [
+ {
+ key: LogDetailsAction.FILTER_IN,
+ label: 'Filter for value',
+ icon: <CirclePlus size={12} />,
+ onClick: (context): void => filterFor(context, true),
+ shouldHide: (_key, fieldKeyPath): boolean => isRestricted(fieldKeyPath),
+ },
+ {
+ key: LogDetailsAction.FILTER_OUT,
+ label: 'Filter out value',
+ icon: <CircleMinus size={12} />,
+ onClick: (context): void => filterFor(context, false),
+ shouldHide: (_key, fieldKeyPath): boolean => isRestricted(fieldKeyPath),
+ },
+ {
+ key: LogDetailsAction.GROUP_BY,
+ label: 'Group by field',
+ icon: <Layers size={12} />,
+ onClick: groupBy,
+ shouldHide: (_key, fieldKeyPath): boolean =>
+ !buildLogFilterTarget(fieldKeyPath, undefined, isBodyJsonQueryEnabled)
+ .groupBySupported || isOldExplorerOrLive,
+ },
+ {
+ key: LogDetailsAction.REPLACE_FILTER,
+ label: 'Replace filters with this value',
+ icon: <RefreshCw size={12} />,
+ onClick: replaceFilter,
+ shouldHide: (_key, fieldKeyPath): boolean =>
+ isRestricted(fieldKeyPath) || isOldExplorerOrLive,
+ },
+ ];
+ }, [
+ filterFor,
+ groupBy,
+ replaceFilter,
+ isBodyJsonQueryEnabled,
+ isOldExplorerOrLive,
+ ]);
+
+ const visibleActions = useMemo<VisibleActionsConfig>(
+ () => ({
+ leaf: isListViewPanel ? COPY_ONLY_ACTIONS : ALL_LEAF_ACTIONS,
+ nested: COPY_ONLY_ACTIONS,
+ }),
+ [isListViewPanel],
+ );
+
+ return { actions, visibleActions };
+}
diff --git a/frontend/src/container/LogDetailedView/logAttributeActions.utils.test.ts b/frontend/src/container/LogDetailedView/logAttributeActions.utils.test.ts
new file mode 100644
index 0000000000..52461b97e5
--- /dev/null
+++ b/frontend/src/container/LogDetailedView/logAttributeActions.utils.test.ts
@@ -0,0 +1,198 @@
+import { MetricsType } from 'container/MetricsApplication/constant';
+
+import {
+ buildLogFilterTarget,
+ toTypedFilterValue,
+} from './logAttributeActions.utils';
+
+describe('buildLogFilterTarget', () => {
+ describe('attributes / resources / scope / top-level scalars', () => {
+ it('maps a top-level scalar to its bare key with =/!=, groupable', () => {
+ const t = buildLogFilterTarget(['severity_text'], 'ERROR', true);
+ expect(t).toMatchObject({
+ fieldKey: 'severity_text',
+ filterInOperator: '=',
+ filterOutOperator: '!=',
+ groupBySupported: true,
+ groupByKey: 'severity_text',
+ isRestricted: false,
+ });
+ expect(t.metricsType).toBeUndefined();
+ });
+
+ it('strips the `attributes` root to a bare dotted key + Tag type', () => {
+ expect(
+ buildLogFilterTarget(['attributes', 'http.method'], 'GET', true),
+ ).toMatchObject({
+ fieldKey: 'http.method',
+ filterInOperator: '=',
+ metricsType: MetricsType.Tag,
+ groupBySupported: true,
+ });
+ });
+
+ it('maps `resources` with Resource type', () => {
+ expect(
+ buildLogFilterTarget(['resources', 'service.name'], 'api', true),
+ ).toMatchObject({
+ fieldKey: 'service.name',
+ metricsType: MetricsType.Resource,
+ });
+ });
+
+ it('maps `scope` with Scope type', () => {
+ expect(
+ buildLogFilterTarget(['scope', 'name'], 'my-scope', true),
+ ).toMatchObject({ fieldKey: 'name', metricsType: MetricsType.Scope });
+ });
+
+ it('offers group-by for attributes now', () => {
+ expect(
+ buildLogFilterTarget(['attributes', 'k'], 'v', true).groupBySupported,
+ ).toBe(true);
+ });
+ });
+
+ describe('restricted fields (timestamp / id)', () => {
+ it.each(['timestamp', 'id'])(
+ 'marks %s restricted with no group-by',
+ (key) => {
+ const t = buildLogFilterTarget([key], 'v', true);
+ expect(t.isRestricted).toBe(true);
+ expect(t.groupBySupported).toBe(false);
+ expect(t.groupByKey).toBeUndefined();
+ },
+ );
+ });
+
+ describe('body scalars', () => {
+ it('maps a top-level body scalar to body.<key> with =/!=, groupable when json body on', () => {
+ const t = buildLogFilterTarget(['body', 'message'], 'hello', true);
+ expect(t).toMatchObject({
+ fieldKey: 'body.message',
+ filterInOperator: '=',
+ filterOutOperator: '!=',
+ groupBySupported: true,
+ groupByKey: 'body.message',
+ isRestricted: false,
+ });
+ expect(t.dataType).toBeDefined();
+ expect(t.metricsType).toBeUndefined();
+ });
+
+ it('maps a nested body scalar to a dotted body key', () => {
+ expect(buildLogFilterTarget(['body', 'a', 'b'], 'x', true)).toMatchObject({
+ fieldKey: 'body.a.b',
+ groupBySupported: true,
+ groupByKey: 'body.a.b',
+ });
+ });
+
+ it('does not offer group-by when USE_JSON_BODY is off', () => {
+ const t = buildLogFilterTarget(['body', 'message'], 'hello', false);
+ expect(t.groupBySupported).toBe(false);
+ expect(t.groupByKey).toBeUndefined();
+ expect(t.fieldKey).toBe('body.message');
+ });
+
+ it('filters the whole `body` field when body is an unparsed string leaf', () => {
+ expect(buildLogFilterTarget(['body'], 'raw text', true)).toMatchObject({
+ fieldKey: 'body',
+ filterInOperator: '=',
+ groupBySupported: false,
+ });
+ });
+
+ it('restricts a body leaf named `timestamp` (no filter / group-by)', () => {
+ const t = buildLogFilterTarget(['body', 'timestamp'], '2026-01-01', true);
+ expect(t.fieldKey).toBe('body.timestamp');
+ expect(t.isRestricted).toBe(true);
+ expect(t.groupBySupported).toBe(false);
+ expect(t.groupByKey).toBeUndefined();
+ });
+
+ it('restricts a nested body leaf named `timestamp`', () => {
+ const t = buildLogFilterTarget(['body', 'obj', 'timestamp'], 'x', true);
+ expect(t.isRestricted).toBe(true);
+ expect(t.groupBySupported).toBe(false);
+ });
+
+ it('restricts a body leaf named `id` (uses RESTRICTED_SELECTED_FIELDS)', () => {
+ expect(buildLogFilterTarget(['body', 'id'], 'abc', true).isRestricted).toBe(
+ true,
+ );
+ });
+
+ it('does not restrict an ordinary body leaf', () => {
+ expect(
+ buildLogFilterTarget(['body', 'message'], 'hello', true).isRestricted,
+ ).toBe(false);
+ });
+ });
+
+ describe('body arrays', () => {
+ it('uses has()/!has() on the array key for a primitive array element', () => {
+ const t = buildLogFilterTarget(['body', 'tags', 0], 'urgent', true);
+ expect(t).toMatchObject({
+ fieldKey: 'body.tags',
+ filterInOperator: 'has',
+ groupBySupported: false,
+ });
+ expect(t.filterOutOperator).toContain('has');
+ expect(t.filterOutOperator).not.toBe('has');
+ });
+
+ it('collapses deep array-element paths to a []-marked has() key', () => {
+ expect(
+ buildLogFilterTarget(
+ ['body', 'config', 'features', 1, 'items', 0, 'variants', 2],
+ 'ballpen',
+ true,
+ ),
+ ).toMatchObject({
+ fieldKey: 'body.config.features[].items[].variants',
+ filterInOperator: 'has',
+ });
+ });
+
+ it('maps a field nested inside an array element with =/!= and a []-marked key, no group-by', () => {
+ expect(
+ buildLogFilterTarget(['body', 'items', 2, 'sku'], 'ABC', true),
+ ).toMatchObject({
+ fieldKey: 'body.items[].sku',
+ filterInOperator: '=',
+ filterOutOperator: '!=',
+ groupBySupported: false,
+ });
+ });
+
+ it('uses the [*] string-body marker for an array element when USE_JSON_BODY is off', () => {
+ expect(
+ buildLogFilterTarget(['body', 'tags', 0], 'urgent', false),
+ ).toMatchObject({ fieldKey: 'body.tags[*]', filterInOperator: 'has' });
+ });
+
+ it('uses [*] for a field nested inside an array element when USE_JSON_BODY is off', () => {
+ expect(
+ buildLogFilterTarget(['body', 'items', 2, 'sku'], 'ABC', false),
+ ).toMatchObject({ fieldKey: 'body.items[*].sku', filterInOperator: '=' });
+ });
+ });
+});
+
+describe('toTypedFilterValue', () => {
+ const run = (value: unknown): unknown => toTypedFilterValue(value);
+
+ it('keeps numbers/booleans as their JS type (so the expression stays unquoted)', () => {
+ expect(run(848)).toBe(848);
+ expect(typeof run(848)).toBe('number');
+ expect(run(1.1)).toBe(1.1);
+ expect(run(true)).toBe(true);
+ expect(typeof run(true)).toBe('boolean');
+ });
+
+ it('passes strings through unchanged (no numeric inference)', () => {
+ expect(run('unknown_service')).toBe('unknown_service');
+ expect(typeof run('12345')).toBe('string');
+ });
+});
diff --git a/frontend/src/container/LogDetailedView/logAttributeActions.utils.ts b/frontend/src/container/LogDetailedView/logAttributeActions.utils.ts
new file mode 100644
index 0000000000..5d8683bbf8
--- /dev/null
+++ b/frontend/src/container/LogDetailedView/logAttributeActions.utils.ts
@@ -0,0 +1,229 @@
+import { v4 as uuid } from 'uuid';
+import {
+ negateOperator,
+ OPERATORS,
+ QUERY_BUILDER_FUNCTIONS,
+} from 'constants/antlrQueryConstants';
+import { OPERATORS as QUERY_BUILDER_OPERATORS } from 'constants/queryBuilder';
+import { RESTRICTED_SELECTED_FIELDS } from 'container/LogsFilters/config';
+import { MetricsType } from 'container/MetricsApplication/constant';
+import { getOperatorValue } from 'container/QueryBuilder/filters/QueryBuilderSearch/utils';
+import { chooseAutocompleteFromCustomValue } from 'lib/newQueryBuilder/chooseAutocompleteFromCustomValue';
+import {
+ BaseAutocompleteData,
+ DataTypes,
+} from 'types/api/queryBuilder/queryAutocompleteResponse';
+import { IBuilderQuery } from 'types/api/queryBuilder/queryBuilderData';
+
+import { LogAttributeBucket } from './constants';
+import { generateFieldKeyForArray, getDataTypes } from './utils';
+
+export const toTypedFilterValue = (value: unknown): string =>
+ typeof value === 'number' || typeof value === 'boolean'
+ ? (value as unknown as string)
+ : String(value);
+
+export interface LogFilterTarget {
+ fieldKey: string;
+ filterInOperator: string;
+ filterOutOperator: string;
+ dataType?: DataTypes;
+ metricsType?: MetricsType;
+ groupBySupported: boolean;
+ groupByKey?: string;
+ isRestricted: boolean;
+}
+
+// Collapse a body forward path into the query-builder key segment; array indices become
+// `[]` (json body on) or `[*]` (string body off — a distinct operator/search path).
+// ['items', 2, 'sku'] -> 'items[].sku' (json on) / 'items[*].sku' (off)
+// ['tags', 0] -> 'tags[]' (json on) / 'tags[*]' (off)
+const collapseBodyPath = (
+ subpath: (string | number)[],
+ isBodyJsonQueryEnabled: boolean,
+): string => {
+ const arrayMarker = isBodyJsonQueryEnabled ? '[]' : '[*]';
+ let out = '';
+ subpath.forEach((seg) => {
+ if (typeof seg === 'number') {
+ out += arrayMarker;
+ } else {
+ out += out ? `.${seg}` : seg;
+ }
+ });
+ return out;
+};
+
+const metricsTypeForRoot = (root: string | number): MetricsType | undefined => {
+ if (root === LogAttributeBucket.ATTRIBUTES) {
+ return MetricsType.Tag;
+ }
+ if (root === LogAttributeBucket.RESOURCES) {
+ return MetricsType.Resource;
+ }
+ if (root === LogAttributeBucket.SCOPE) {
+ return MetricsType.Scope;
+ }
+ return undefined;
+};
+
+/**
+ * Map a PrettyView leaf (forward keyPath) to its query-builder filter/group-by target:
+ * scalars → `=`/`!=`, body array elements → `has`/`!has`; group-by gated by
+ * `groupBySupported`. Attribute/resource/scope carry a `metricsType` (Tag/Resource/Scope).
+ */
+export const buildLogFilterTarget = (
+ fieldKeyPath: (string | number)[],
+ value: unknown,
+ isBodyJsonQueryEnabled: boolean,
+): LogFilterTarget => {
+ const root = fieldKeyPath[0];
+
+ // Attributes / resources / scope / top-level scalars: bare dotted key, =/!=.
+ if (root !== 'body') {
+ const fieldKey =
+ fieldKeyPath.length > 1 ? fieldKeyPath.slice(1).join('.') : String(root);
+ const isRestricted = RESTRICTED_SELECTED_FIELDS.includes(fieldKey);
+ return {
+ fieldKey,
+ filterInOperator: OPERATORS['='],
+ filterOutOperator: OPERATORS['!='],
+ dataType: getDataTypes(value),
+ metricsType: metricsTypeForRoot(root),
+ groupBySupported: !isRestricted,
+ groupByKey: isRestricted ? undefined : fieldKey,
+ isRestricted,
+ };
+ }
+
+ const subpath = fieldKeyPath.slice(1);
+
+ // Whole-body leaf (unparsed string body): filter on the `body` field itself.
+ if (subpath.length === 0) {
+ return {
+ fieldKey: 'body',
+ filterInOperator: OPERATORS['='],
+ filterOutOperator: OPERATORS['!='],
+ dataType: getDataTypes(value),
+ groupBySupported: false,
+ isRestricted: false,
+ };
+ }
+
+ const collapsed = collapseBodyPath(subpath, isBodyJsonQueryEnabled);
+ const isArrayElement = typeof subpath[subpath.length - 1] === 'number';
+
+ if (isArrayElement) {
+ // has(body.<array>, value): generateFieldKeyForArray strips the trailing value
+ // segment + `[]` exactly as the old BodyTitleRenderer.filterHandler did.
+ const fieldKey = generateFieldKeyForArray(
+ `${collapsed}.${String(value)}`,
+ getDataTypes(value),
+ isBodyJsonQueryEnabled,
+ );
+ return {
+ fieldKey,
+ filterInOperator: QUERY_BUILDER_FUNCTIONS.HAS,
+ filterOutOperator: negateOperator(QUERY_BUILDER_FUNCTIONS.HAS),
+ dataType: getDataTypes([value]),
+ groupBySupported: false,
+ isRestricted: false,
+ };
+ }
+
+ const fieldKey = `body.${collapsed}`;
+ // Restrict body leaves whose own key is a restricted field (e.g. a JSON body's own
+ // `timestamp`/`id`/`date`) — hides filter / group-by, same as top-level fields.
+ const leafKey = String(subpath[subpath.length - 1]);
+ const isRestricted = RESTRICTED_SELECTED_FIELDS.includes(leafKey);
+ // Group by only for plain body scalars (no array anywhere in the path) with json
+ // body on — mirrors isGroupBySupported in the old BodyTitleRenderer.
+ const groupBySupported =
+ isBodyJsonQueryEnabled && !collapsed.includes('[]') && !isRestricted;
+ return {
+ fieldKey,
+ filterInOperator: OPERATORS['='],
+ filterOutOperator: OPERATORS['!='],
+ dataType: getDataTypes(value),
+ groupBySupported,
+ groupByKey: groupBySupported ? fieldKey : undefined,
+ isRestricted,
+ };
+};
+
+const normalizeDataType = (
+ dataType: DataTypes | undefined,
+): DataTypes | undefined =>
+ dataType && Object.values(DataTypes).includes(dataType) ? dataType : undefined;
+
+// Append a filter item (filter-in / filter-out) to a query-data item. The autocomplete
+// key is fabricated locally (empty source list), so no click-time getAggregateKeys fetch.
+export const getFilterQueryData = (
+ item: IBuilderQuery,
+ target: LogFilterTarget,
+ value: unknown,
+ operator: string,
+): IBuilderQuery => {
+ const filterKey = chooseAutocompleteFromCustomValue(
+ [],
+ target.fieldKey,
+ target.dataType,
+ target.metricsType,
+ );
+ return {
+ ...item,
+ filters: {
+ items: [
+ ...(item.filters?.items || []),
+ {
+ id: uuid(),
+ key: filterKey,
+ op: getOperatorValue(operator),
+ value: toTypedFilterValue(value),
+ },
+ ],
+ op: item.filters?.op || 'AND',
+ },
+ };
+};
+
+// Append a group-by. Caller guards groupBySupported / groupByKey.
+export const getGroupByQueryData = (
+ item: IBuilderQuery,
+ target: LogFilterTarget,
+): IBuilderQuery => {
+ const newGroupByItem: BaseAutocompleteData = {
+ key: target.groupByKey || '',
+ type: target.metricsType || '',
+ dataType: normalizeDataType(target.dataType),
+ };
+ return { ...item, groupBy: [...(item.groupBy || []), newGroupByItem] };
+};
+
+// Replace all filters with a single IN filter on this value.
+export const getReplaceFilterQueryData = (
+ item: IBuilderQuery,
+ target: LogFilterTarget,
+ value: unknown,
+): IBuilderQuery => {
+ const newFilterItem: BaseAutocompleteData = {
+ key: target.fieldKey,
+ type: target.metricsType || '',
+ dataType: normalizeDataType(target.dataType),
+ };
+ return {
+ ...item,
+ filters: {
+ items: [
+ {
+ id: '',
+ key: newFilterItem,
+ op: QUERY_BUILDER_OPERATORS.IN,
+ value: [toTypedFilterValue(value)],
+ },
+ ],
+ op: 'AND',
+ },
+ filter: { expression: '' },
+ };
+};
diff --git a/frontend/src/container/LogDetailedView/util.test.ts b/frontend/src/container/LogDetailedView/util.test.ts
index 3a16e253a4..e1ddebe6ba 100644
--- a/frontend/src/container/LogDetailedView/util.test.ts
+++ b/frontend/src/container/LogDetailedView/util.test.ts
@@ -1,12 +1,87 @@
+import { ILog } from 'types/api/logs/log';
import { DataTypes } from 'types/api/queryBuilder/queryAutocompleteResponse';
import {
+ aggregateAttributesResourcesToObject,
flattenObject,
getDataTypes,
getSanitizedLogBody,
+ parseJsonStringBody,
recursiveParseJSON,
} from './utils';
+describe('parseJsonStringBody', () => {
+ it('parses a JSON-object string into an object', () => {
+ expect(parseJsonStringBody('{"a":1,"b":{"c":2}}')).toStrictEqual({
+ a: 1,
+ b: { c: 2 },
+ });
+ });
+
+ it('parses a JSON-array string into an array', () => {
+ expect(parseJsonStringBody('[1,2,3]')).toStrictEqual([1, 2, 3]);
+ });
+
+ it('returns a plain (non-JSON) string unchanged', () => {
+ expect(parseJsonStringBody('plain log line')).toBe('plain log line');
+ });
+
+ it('returns a string that is not object/array-looking unchanged', () => {
+ expect(parseJsonStringBody('42')).toBe('42');
+ });
+
+ it('returns an invalid JSON string unchanged', () => {
+ expect(parseJsonStringBody('{not valid}')).toBe('{not valid}');
+ });
+
+ it('returns an already-object body unchanged (same reference)', () => {
+ const body = { message: 'hi', a: 1 };
+ expect(parseJsonStringBody(body)).toBe(body);
+ });
+
+ it('leaves a body larger than the 128KB parse guard as a string', () => {
+ const huge = `{"x":"${'a'.repeat(130 * 1024)}"}`;
+ expect(parseJsonStringBody(huge)).toBe(huge);
+ });
+});
+
+describe('aggregateAttributesResourcesToObject', () => {
+ const mockLog = {
+ id: 'log-1',
+ timestamp: 1234,
+ body: 'hello',
+ severity_text: 'INFO',
+ severity_number: 9,
+ attributes_string: { 'http.method': 'GET' },
+ attributes_int: { retries: 3 },
+ resources_string: { 'service.name': 'cart' },
+ scope_string: { lib: 'otel' },
+ } as unknown as ILog;
+
+ it('merges attributes_/resources_/scope_ maps and keeps scalars + body', () => {
+ const result = aggregateAttributesResourcesToObject(mockLog);
+
+ expect(result.attributes).toStrictEqual({
+ 'http.method': 'GET',
+ retries: 3,
+ });
+ expect(result.resources).toStrictEqual({ 'service.name': 'cart' });
+ expect(result.scope).toStrictEqual({ lib: 'otel' });
+ expect(result.body).toBe('hello');
+ expect(result.id).toBe('log-1');
+ expect(result.severity_text).toBe('INFO');
+ });
+
+ it('does not parse a JSON-string body (leaves it raw)', () => {
+ const result = aggregateAttributesResourcesToObject({
+ ...mockLog,
+ body: '{"a":1}',
+ } as unknown as ILog);
+
+ expect(result.body).toBe('{"a":1}');
+ });
+});
+
describe('recursiveParseJSON', () => {
it('should return an empty object if the input is not valid JSON', () => {
const result = recursiveParseJSON('not valid JSON');
diff --git a/frontend/src/container/LogDetailedView/utils.tsx b/frontend/src/container/LogDetailedView/utils.tsx
index ba3dc56d5f..6a6072c16b 100644
--- a/frontend/src/container/LogDetailedView/utils.tsx
+++ b/frontend/src/container/LogDetailedView/utils.tsx
@@ -1,3 +1,4 @@
+import * as Sentry from '@sentry/react';
import Convert from 'ansi-to-html';
import type { DataNode } from 'antd/es/tree';
import { ChangeViewFunctionType } from 'container/ExplorerOptions/types';
@@ -262,10 +263,11 @@ export const filterKeyForField = (field: string): string => {
return fieldAttribs?.newField || field;
};
-export const aggregateAttributesResourcesToString = (logData: ILog): string => {
+export const aggregateAttributesResourcesToObject = (
+ logData: ILog,
+): ILogAggregateAttributesResources => {
const outputJson: ILogAggregateAttributesResources = {
body: logData.body,
- date: logData.date,
id: logData.id,
severityNumber: logData.severityNumber,
severityText: logData.severityText,
@@ -281,6 +283,9 @@ export const aggregateAttributesResourcesToString = (logData: ILog): string => {
};
Object.keys(logData).forEach((key) => {
+ if (key === 'date') {
+ return;
+ }
if (key.startsWith('attributes_')) {
outputJson.attributes = outputJson.attributes || {};
Object.assign(outputJson.attributes, logData[key as keyof ILog]);
@@ -291,12 +296,47 @@ export const aggregateAttributesResourcesToString = (logData: ILog): string => {
outputJson.scope = outputJson.scope || {};
Object.assign(outputJson.scope, logData[key as keyof ILog]);
} else {
- // @ts-expect-error
+ // @ts-expect-error dynamic top-level copy
outputJson[key] = logData[key as keyof ILog];
}
});
- return JSON.stringify(outputJson, null, 2);
+ // Show `timestamp` first and `id` last in the details view.
+ const { timestamp, id, ...rest } = outputJson;
+ return { timestamp, ...rest, id };
+};
+
+export const aggregateAttributesResourcesToString = (logData: ILog): string => {
+ try {
+ return JSON.stringify(aggregateAttributesResourcesToObject(logData), null, 2);
+ } catch (err) {
+ Sentry.captureException(err);
+ return '';
+ }
+};
+
+const MAX_JSON_BODY_PARSE_BYTES = 128 * 1024;
+
+// A JSON-encoded object/array `body` is parsed so DataViewer renders it as a
+// tree instead of one escaped string; plain-text bodies are returned unchanged.
+// Guarded against very large payloads.
+export const parseJsonStringBody = (body: ILog['body']): ILog['body'] => {
+ if (typeof body !== 'string') {
+ return body;
+ }
+ const trimmed = body.trim();
+ const looksLikeJson = trimmed.startsWith('{') || trimmed.startsWith('[');
+ if (!looksLikeJson || trimmed.length > MAX_JSON_BODY_PARSE_BYTES) {
+ return body;
+ }
+ try {
+ const parsed = JSON.parse(trimmed);
+ return parsed !== null && typeof parsed === 'object'
+ ? (parsed as ILogBody)
+ : body;
+ } catch {
+ return body;
+ }
};
const isFloat = (num: number): boolean => num % 1 !== 0;
diff --git a/frontend/src/periscope/components/DataViewer/DataViewer.tsx b/frontend/src/periscope/components/DataViewer/DataViewer.tsx
index 01d2ee06fb..b1da1375bd 100644
--- a/frontend/src/periscope/components/DataViewer/DataViewer.tsx
+++ b/frontend/src/periscope/components/DataViewer/DataViewer.tsx
@@ -1,4 +1,4 @@
-import { useMemo, useState } from 'react';
+import { CSSProperties, useMemo, useState } from 'react';
import { ToggleGroupSimple } from '@signozhq/ui/toggle-group';
import logEvent from 'api/common/logEvent';
import CopyButton from 'periscope/components/CopyButton/CopyButton';
@@ -24,16 +24,23 @@ export interface DataViewerProps {
data: Record<string, any>;
drawerKey?: string;
prettyViewProps?: Omit<PrettyViewProps, 'data' | 'drawerKey'>;
+ // Optional override for the JSON view otherwise `data` is
+ // stringified and used.
+ jsonString?: string;
+ fontSize?: number;
}
function DataViewer({
data,
drawerKey = 'default',
prettyViewProps,
+ jsonString,
+ fontSize,
}: DataViewerProps): JSX.Element {
const [viewMode, setViewMode] = useState<ViewMode>(ViewMode.Pretty);
- const jsonString = useMemo(() => JSON.stringify(data, null, 2), [data]);
+ const derivedJson = useMemo(() => JSON.stringify(data, null, 2), [data]);
+ const json = jsonString ?? derivedJson;
const handleViewModeChange = (value: string): void => {
const next = value as ViewMode;
@@ -55,7 +62,14 @@ function DataViewer({
};
return (
- <div className="data-viewer">
+ <div
+ className="data-viewer"
+ style={
+ fontSize
+ ? ({ '--data-viewer-font-size': `${fontSize}px` } as CSSProperties)
+ : undefined
+ }
+ >
<div className="data-viewer__toolbar">
<ToggleGroupSimple
type="single"
@@ -65,14 +79,14 @@ function DataViewer({
items={VIEW_MODE_OPTIONS}
testId="data-viewer-view-mode"
/>
- <CopyButton value={jsonString} ariaLabel="Copy JSON" />
+ <CopyButton value={json} ariaLabel="Copy JSON" />
</div>
<div className="data-viewer__content">
{viewMode === ViewMode.Pretty && (
<PrettyView data={data} drawerKey={drawerKey} {...prettyViewProps} />
)}
- {viewMode === ViewMode.Json && <JsonView data={jsonString} />}
+ {viewMode === ViewMode.Json && <JsonView data={json} fontSize={fontSize} />}
</div>
</div>
);
diff --git a/frontend/src/periscope/components/JsonView/JsonView.tsx b/frontend/src/periscope/components/JsonView/JsonView.tsx
index c6f874b7d1..1317cc6353 100644
--- a/frontend/src/periscope/components/JsonView/JsonView.tsx
+++ b/frontend/src/periscope/components/JsonView/JsonView.tsx
@@ -10,6 +10,7 @@ import './JsonView.styles.scss';
export interface JsonViewProps {
data: string;
height?: string;
+ fontSize?: number;
}
const editorOptions: EditorProps['options'] = {
@@ -56,7 +57,11 @@ function setEditorTheme(monaco: Monaco): void {
});
}
-function JsonView({ data, height = '575px' }: JsonViewProps): JSX.Element {
+function JsonView({
+ data,
+ height = '575px',
+ fontSize = 12,
+}: JsonViewProps): JSX.Element {
const [isWrapWord, setIsWrapWord] = useState(true);
const isDarkMode = useIsDarkMode();
@@ -65,7 +70,11 @@ function JsonView({ data, height = '575px' }: JsonViewProps): JSX.Element {
<MEditor
value={data}
language="json"
- options={{ ...editorOptions, wordWrap: isWrapWord ? 'on' : 'off' }}
+ options={{
+ ...editorOptions,
+ fontSize,
+ wordWrap: isWrapWord ? 'on' : 'off',
+ }}
onChange={(): void => {}}
height={height}
theme={isDarkMode ? 'signoz-dark' : 'light'}
diff --git a/frontend/src/periscope/components/PrettyView/PrettyView.styles.scss b/frontend/src/periscope/components/PrettyView/PrettyView.styles.scss
index ec7ffe6972..7f826b261b 100644
--- a/frontend/src/periscope/components/PrettyView/PrettyView.styles.scss
+++ b/frontend/src/periscope/components/PrettyView/PrettyView.styles.scss
@@ -17,7 +17,7 @@
border-bottom: 1px solid var(--l2-border) !important;
border-radius: 0 !important;
font-family: 'SF Mono', 'Geist Mono', 'Fira Code', monospace !important;
- font-size: 12px !important;
+ font-size: var(--data-viewer-font-size, 12px) !important;
line-height: 18px !important;
background: var(--l1-background) !important;
outline: none !important;
@@ -33,7 +33,7 @@
// Font spec: SF Mono, 12px, 400, 18px line-height, -0.5% letter-spacing
font-family: 'SF Mono', 'Geist Mono', 'Fira Code', monospace;
- font-size: 12px;
+ font-size: var(--data-viewer-font-size, 12px);
font-weight: 400;
line-height: 18px;
letter-spacing: -0.06px;
@@ -77,6 +77,17 @@
margin-right: 16px;
}
+ // Pin the caret to the leaf padding-left (1.25em) so nested keys align with leaf
+ // keys at every depth; inline-flex centers the glyph on the text line.
+ &__arrow {
+ box-sizing: border-box !important;
+ width: 1.25em !important;
+ padding-right: 0 !important;
+ display: inline-flex !important;
+ align-items: center !important;
+ height: 18px; // match the row line-height so the caret centers on the text
+ }
+
// Leaf node row — full-width hover highlight
&__row {
display: flex !important;
@@ -84,6 +95,11 @@
position: relative;
isolation: isolate; // own stacking context so ::before sits behind content, not the panel bg
+ // react-json-tree indents leaf values with a depth-dependent padding-left
+ // (2.125em when nested vs 1.25em at top); we indent via `ul`, so pin it flat
+ // to keep leaf and nested keys aligned at every depth.
+ padding-left: 1.25em !important;
+
// Keep actions visible on hover, or while this row's menu is open
&:hover .pretty-view__actions,
&:has(> span [data-state='open']) .pretty-view__actions {
@@ -175,6 +191,13 @@
&__row &__value-row {
justify-content: space-between;
width: 100%;
+ // Anchor the ... to the top of the value (not centered in a tall value)
+ align-items: flex-start;
+
+ .pretty-view__actions {
+ position: sticky;
+ top: 4px;
+ }
}
// ... actions button — hidden by default, shown on row hover
diff --git a/frontend/src/periscope/components/PrettyView/PrettyView.tsx b/frontend/src/periscope/components/PrettyView/PrettyView.tsx
index 075de728b4..a58f697d87 100644
--- a/frontend/src/periscope/components/PrettyView/PrettyView.tsx
+++ b/frontend/src/periscope/components/PrettyView/PrettyView.tsx
@@ -67,6 +67,15 @@ export interface PrettyViewProps {
*/
pinnedFieldsValue?: string[];
onPinnedFieldsChange?: (next: string[]) => void;
+ /**
+ * Optional per-leaf value renderer. Return a node to override the default
+ * `String(value)` rendering for that leaf, or `undefined` to fall back. Used
+ * e.g. to sanitize/format log body values (ANSI → color, unescape).
+ */
+ renderLeafValue?: (
+ value: unknown,
+ keyPath: readonly (string | number)[],
+ ) => React.ReactNode | undefined;
}
function PrettyView({
@@ -78,6 +87,7 @@ function PrettyView({
drawerKey = 'default',
pinnedFieldsValue,
onPinnedFieldsChange,
+ renderLeafValue,
}: PrettyViewProps): JSX.Element {
const isDarkMode = useIsDarkMode();
const [, setCopy] = useCopyToClipboard();
@@ -233,7 +243,9 @@ function PrettyView({
>
<span
className="pretty-view__actions"
- onClick={(e): void => e.stopPropagation()}
+ onClick={(e): void => {
+ e.stopPropagation();
+ }}
role="button"
tabIndex={0}
>
@@ -278,15 +290,16 @@ function PrettyView({
...keyPath: KeyPath
): React.ReactNode => {
const forwardPath = keyPathToForward(keyPath);
+ const custom = renderLeafValue?.(value, keyPath);
return renderWithActions({
- content: String(valueAsString),
+ content: custom ?? String(valueAsString),
fieldKey: keyPathToDisplayString(keyPath),
fieldKeyPath: forwardPath,
value,
isNested: typeof value === 'object' && value !== null,
});
},
- [renderWithActions],
+ [renderWithActions, renderLeafValue],
);
const pinnedLabelRenderer = useCallback(
diff --git a/frontend/src/periscope/components/PrettyView/constants.ts b/frontend/src/periscope/components/PrettyView/constants.ts
index 80fb129a20..f3b13a973f 100644
--- a/frontend/src/periscope/components/PrettyView/constants.ts
+++ b/frontend/src/periscope/components/PrettyView/constants.ts
@@ -59,4 +59,12 @@ export const themeExtension = {
style: { ...style },
className: 'pretty-view__nested-row',
}),
+ arrowContainer: (
+ { style }: { style: Record<string, unknown> },
+ arrowStyle: string,
+ ): { style: Record<string, unknown>; className?: string } => ({
+ style: { ...style },
+ // Only pin the single caret's width (for key alignment).
+ className: arrowStyle === 'double' ? undefined : 'pretty-view__arrow',
+ }),
};
diff --git a/frontend/src/types/api/logs/log.ts b/frontend/src/types/api/logs/log.ts
index d4c1daf52f..8a0c57e2aa 100644
--- a/frontend/src/types/api/logs/log.ts
+++ b/frontend/src/types/api/logs/log.ts
@@ -29,6 +29,7 @@ type OmitAttributesResources = Pick<
ILog,
Exclude<
keyof ILog,
+ | 'date'
| 'resources_string'
| 'scope_string'
| 'attributesString'