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: performance optimizations in log details view json field rendering (#8324)
Sahil Khanff13504a7455
diff --git a/frontend/src/container/LogDetailedView/TableView.tsx b/frontend/src/container/LogDetailedView/TableView.tsxindex 652b3c20e8..05a578f60a 100644--- a/frontend/src/container/LogDetailedView/TableView.tsx+++ b/frontend/src/container/LogDetailedView/TableView.tsx@@ -32,7 +32,7 @@ import { DataTypes } from 'types/api/queryBuilder/queryAutocompleteResponse';import { ActionItemProps } from './ActionItem';import FieldRenderer from './FieldRenderer';-import { TableViewActions } from './TableView/TableViewActions';+import TableViewActions from './TableView/TableViewActions';import {filterKeyForField,findKeyPath,diff --git a/frontend/src/container/LogDetailedView/TableView/TableViewActions.tsx b/frontend/src/container/LogDetailedView/TableView/TableViewActions.tsxindex 749a91172d..f09e9a5c57 100644--- a/frontend/src/container/LogDetailedView/TableView/TableViewActions.tsx+++ b/frontend/src/container/LogDetailedView/TableView/TableViewActions.tsx@@ -1,3 +1,4 @@+/* eslint-disable sonarjs/no-duplicate-string */import './TableViewActions.styles.scss';import { Color } from '@signozhq/design-tokens';@@ -11,10 +12,9 @@ import { OPERATORS } from 'constants/queryBuilder';import ROUTES from 'constants/routes';import { RESTRICTED_SELECTED_FIELDS } from 'container/LogsFilters/config';import dompurify from 'dompurify';-import { isEmpty } from 'lodash-es';import { ArrowDownToDot, ArrowUpFromDot, Ellipsis } from 'lucide-react';import { useTimezone } from 'providers/Timezone';-import React, { useMemo, useState } from 'react';+import React, { useCallback, useMemo, useState } from 'react';import { useLocation } from 'react-router-dom';import { DataTypes } from 'types/api/queryBuilder/queryAutocompleteResponse';import { FORBID_DOM_PURIFY_TAGS } from 'utils/app';@@ -24,12 +24,11 @@ import {escapeHtml,filterKeyForField,getFieldAttributes,- jsonToDataNodes,parseFieldValue,- recursiveParseJSON,removeEscapeCharacters,unescapeString,} from '../utils';+import useAsyncJSONProcessing from './useAsyncJSONProcessing';interface ITableViewActionsProps {fieldData: Record<string, string>;@@ -52,7 +51,64 @@ interface ITableViewActionsProps {const convert = new Convert();-export function TableViewActions(+// Memoized Tree Component+const MemoizedTree = React.memo<{ treeData: any[] }>(({ treeData }) => (+ <Tree defaultExpandAll showLine treeData={treeData} />+));++MemoizedTree.displayName = 'MemoizedTree';++// Body Content Component+const BodyContent: React.FC<{+ fieldData: Record<string, string>;+ record: DataType;+ bodyHtml: { __html: string };+}> = React.memo(({ fieldData, record, bodyHtml }) => {+ const { isLoading, treeData, error } = useAsyncJSONProcessing(+ fieldData.value,+ record.field === 'body',+ );++ // Show JSON tree if available, otherwise show HTML content+ if (record.field === 'body' && treeData) {+ return <MemoizedTree treeData={treeData} />;+ }++ if (record.field === 'body' && isLoading) {+ return (+ <div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>+ <Spin size="small" />+ <span style={{ color: Color.BG_SIENNA_400 }}>Processing JSON...</span>+ </div>+ );+ }++ if (record.field === 'body' && error) {+ return (+ <span+ style={{ color: Color.BG_SIENNA_400, whiteSpace: 'pre-wrap', tabSize: 4 }}+ >+ Error parsing Body JSON+ </span>+ );+ }++ if (record.field === 'body') {+ return (+ <span+ style={{ color: Color.BG_SIENNA_400, whiteSpace: 'pre-wrap', tabSize: 4 }}+ >+ <span dangerouslySetInnerHTML={bodyHtml} />+ </span>+ );+ }++ return null;+});++BodyContent.displayName = 'BodyContent';++export default function TableViewActions(props: ITableViewActionsProps,): React.ReactElement {const {@@ -78,44 +134,42 @@ export function TableViewActions(const { formatTimezoneAdjustedTimestamp } = useTimezone();- if (record.field === 'body') {- const parsedBody = recursiveParseJSON(fieldData.value);- if (!isEmpty(parsedBody)) {- return (- <Tree defaultExpandAll showLine treeData={jsonToDataNodes(parsedBody)} />- );- }- }- const bodyHtml =- record.field === 'body'- ? {- __html: convert.toHtml(- dompurify.sanitize(unescapeString(escapeHtml(record.value)), {- FORBID_TAGS: [...FORBID_DOM_PURIFY_TAGS],- }),- ),- }- : { __html: '' };+ // Memoize bodyHtml computation+ const bodyHtml = useMemo(() => {+ if (record.field !== 'body') return { __html: '' };++ return {+ __html: convert.toHtml(+ dompurify.sanitize(unescapeString(escapeHtml(record.value)), {+ FORBID_TAGS: [...FORBID_DOM_PURIFY_TAGS],+ }),+ ),+ };+ }, [record.field, record.value]);const fieldFilterKey = filterKeyForField(fieldData.field);- let textToCopy = fieldData.value;-- // remove starting and ending quotes from the value- try {- textToCopy = textToCopy.replace(/^"|"$/g, '');- } catch (error) {- console.error(- 'Failed to remove starting and ending quotes from the value',- error,- );- }- let cleanTimestamp: string;- if (record.field === 'timestamp') {- cleanTimestamp = fieldData.value.replace(/^["']|["']$/g, '');- }+ // Memoize textToCopy computation+ const textToCopy = useMemo(() => {+ let text = fieldData.value;+ try {+ text = text.replace(/^"|"$/g, '');+ } catch (error) {+ console.error(+ 'Failed to remove starting and ending quotes from the value',+ error,+ );+ }+ return text;+ }, [fieldData.value]);++ // Memoize cleanTimestamp computation+ const cleanTimestamp = useMemo(() => {+ if (record.field !== 'timestamp') return '';+ return fieldData.value.replace(/^["']|["']$/g, '');+ }, [record.field, fieldData.value]);- const renderFieldContent = (): JSX.Element => {+ const renderFieldContent = useCallback((): JSX.Element => {const commonStyles: React.CSSProperties = {color: Color.BG_SIENNA_400,whiteSpace: 'pre-wrap',@@ -124,7 +178,9 @@ export function TableViewActions(switch (record.field) {case 'body':- return <span style={commonStyles} dangerouslySetInnerHTML={bodyHtml} />;+ return (+ <BodyContent fieldData={fieldData} record={record} bodyHtml={bodyHtml} />+ );case 'timestamp':return (@@ -141,7 +197,93 @@ export function TableViewActions(<span style={commonStyles}>{removeEscapeCharacters(fieldData.value)}</span>);}- };+ }, [+ record,+ fieldData,+ bodyHtml,+ formatTimezoneAdjustedTimestamp,+ cleanTimestamp,+ ]);++ // Early return for body field with async processing+ if (record.field === 'body') {+ return (+ <div className={cx('value-field', isOpen ? 'open-popover' : '')}>+ <CopyClipboardHOC entityKey={fieldFilterKey} textToCopy={textToCopy}>+ <BodyContent fieldData={fieldData} record={record} bodyHtml={bodyHtml} />+ </CopyClipboardHOC>+ {!isListViewPanel && !RESTRICTED_SELECTED_FIELDS.includes(fieldFilterKey) && (+ <span className="action-btn">+ <Tooltip title="Filter for value">+ <Button+ className="filter-btn periscope-btn"+ icon={+ isfilterInLoading ? (+ <Spin size="small" />+ ) : (+ <ArrowDownToDot size={14} style={{ transform: 'rotate(90deg)' }} />+ )+ }+ onClick={onClickHandler(+ OPERATORS['='],+ fieldFilterKey,+ parseFieldValue(fieldData.value),+ dataType,+ )}+ />+ </Tooltip>+ <Tooltip title="Filter out value">+ <Button+ className="filter-btn periscope-btn"+ icon={+ isfilterOutLoading ? (+ <Spin size="small" />+ ) : (+ <ArrowUpFromDot size={14} style={{ transform: 'rotate(90deg)' }} />+ )+ }+ onClick={onClickHandler(+ OPERATORS['!='],+ fieldFilterKey,+ parseFieldValue(fieldData.value),+ dataType,+ )}+ />+ </Tooltip>+ {!isOldLogsExplorerOrLiveLogsPage && (+ <Popover+ open={isOpen}+ onOpenChange={setIsOpen}+ arrow={false}+ content={+ <div>+ <Button+ className="group-by-clause"+ type="text"+ icon={<GroupByIcon />}+ onClick={(): Promise<void> | void =>+ onGroupByAttribute?.(fieldFilterKey)+ }+ >+ Group By Attribute+ </Button>+ </div>+ }+ rootClassName="table-view-actions-content"+ trigger="hover"+ placement="bottomLeft"+ >+ <Button+ icon={<Ellipsis size={14} />}+ className="filter-btn periscope-btn"+ />+ </Popover>+ )}+ </span>+ )}+ </div>+ );+ }return (<div className={cx('value-field', isOpen ? 'open-popover' : '')}>diff --git a/frontend/src/container/LogDetailedView/TableView/__test__/TableViewActions.test.tsx b/frontend/src/container/LogDetailedView/TableView/__test__/TableViewActions.test.tsxindex 84a07f5080..da6b3bdad3 100644--- a/frontend/src/container/LogDetailedView/TableView/__test__/TableViewActions.test.tsx+++ b/frontend/src/container/LogDetailedView/TableView/__test__/TableViewActions.test.tsx@@ -1,7 +1,7 @@import { render, screen } from '@testing-library/react';import { RESTRICTED_SELECTED_FIELDS } from 'container/LogsFilters/config';-import { TableViewActions } from '../TableViewActions';+import TableViewActions from '../TableViewActions';// Mock the components and hooksjest.mock('components/Logs/CopyClipboardHOC', () => ({diff --git a/frontend/src/container/LogDetailedView/TableView/useAsyncJSONProcessing.ts b/frontend/src/container/LogDetailedView/TableView/useAsyncJSONProcessing.tsnew file mode 100644index 0000000000..d7403a4796--- /dev/null+++ b/frontend/src/container/LogDetailedView/TableView/useAsyncJSONProcessing.ts@@ -0,0 +1,102 @@+/* eslint-disable sonarjs/no-duplicate-string */+import { isEmpty } from 'lodash-es';+import { useEffect, useRef, useState } from 'react';++import { jsonToDataNodes, recursiveParseJSON } from '../utils';++// Hook for async JSON processing+const useAsyncJSONProcessing = (+ value: string,+ shouldProcess: boolean,+): {+ isLoading: boolean;+ treeData: any[] | null;+ error: string | null;+} => {+ const [jsonState, setJsonState] = useState<{+ isLoading: boolean;+ treeData: any[] | null;+ error: string | null;+ }>({+ isLoading: false,+ treeData: null,+ error: null,+ });++ const processingRef = useRef<boolean>(false);++ // eslint-disable-next-line sonarjs/cognitive-complexity+ useEffect((): (() => void) => {+ if (!shouldProcess || processingRef.current) {+ return (): void => {};+ }++ processingRef.current = true;+ setJsonState({ isLoading: true, treeData: null, error: null });++ // Option 1: Using setTimeout for non-blocking processing+ const processAsync = (): void => {+ setTimeout(() => {+ try {+ const parsedBody = recursiveParseJSON(value);+ if (!isEmpty(parsedBody)) {+ const treeData = jsonToDataNodes(parsedBody);+ setJsonState({ isLoading: false, treeData, error: null });+ } else {+ setJsonState({ isLoading: false, treeData: null, error: null });+ }+ } catch (error) {+ setJsonState({+ isLoading: false,+ treeData: null,+ error: error instanceof Error ? error.message : 'Parsing failed',+ });+ } finally {+ processingRef.current = false;+ }+ }, 0);+ };++ // Option 2: Using requestIdleCallback for better performance+ const processWithIdleCallback = (): void => {+ if ('requestIdleCallback' in window) {+ requestIdleCallback(+ // eslint-disable-next-line sonarjs/no-identical-functions+ (): void => {+ try {+ const parsedBody = recursiveParseJSON(value);+ if (!isEmpty(parsedBody)) {+ const treeData = jsonToDataNodes(parsedBody);+ setJsonState({ isLoading: false, treeData, error: null });+ } else {+ setJsonState({ isLoading: false, treeData: null, error: null });+ }+ } catch (error) {+ setJsonState({+ isLoading: false,+ treeData: null,+ error: error instanceof Error ? error.message : 'Parsing failed',+ });+ } finally {+ processingRef.current = false;+ }+ },+ { timeout: 1000 },+ );+ } else {+ processAsync();+ }+ };++ processWithIdleCallback();++ // Cleanup function+ return (): void => {+ processingRef.current = false;+ };+ }, [value, shouldProcess]);++ return jsonState;+};++export default useAsyncJSONProcessing;