The open and composable observability and data visualization platform. Visualize metrics, logs, and traces from multiple sources like Prometheus, Loki, Elasticsearch, InfluxDB, Postgres and many more.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
grafana/public/app/features/logs/components/LogRow.tsx

321 lines
11 KiB

Logs: Redesign and improve LogContext (#65939) * Logs: Add new LogRowContext types to grafana/data * use right type for `RowContextOptions` * add missing renames * add show context modal * no need to call * removed unused css * sort properties * rename * use correct * use * add tests for * wip * remove add/minus buttons * add tests * disable processing of context results in Loki * moved into table to align properly * remove imports * add highlighting of opened logline * improve scrolling behavior * correct style for the table * use correct query direction * fix text * use LoadingBar * use overflow auto * rename `onToggleContext` to `onOpenContext` * add missing import * mock scrollIntoView * update unused props * remove unused import * no need to process context dataframes * only show `LogRowContextModal` if `getRowContext` is defined * remove unused param * use `userEvent` rather `fireEvent` * change to `TimeZone` * directly use style classes * revert change to public_dashboard_service_mock.go * improved styling * add missing await in test * fix lint * fix lint * remove LogRow scrolling when context is opened * remove references to `scrollElement` * Update public/app/features/logs/components/log-context/LogRowContextModal.tsx Co-authored-by: Matias Chomicki <matyax@gmail.com> * fix lint * add comment explaining `onCloseContext` * add comment about debounced onClose * add comments and remove `showRowMenu` * scroll twice to correctly center the element * revert double scrolling * remove unnecessary `processDataFrame` * trigger drone --------- Co-authored-by: Matias Chomicki <matyax@gmail.com>
3 years ago
import { debounce } from 'lodash';
import { MouseEvent, ReactNode, useCallback, useEffect, useMemo, useRef, useState } from 'react';
import {
CoreApp,
DataFrame,
dateTimeFormat,
Field,
LinkModel,
LogRowContextOptions,
LogRowModel,
LogsSortOrder,
} from '@grafana/data';
import { reportInteraction } from '@grafana/runtime';
import { DataQuery, TimeZone } from '@grafana/schema';
import { Icon, PopoverContent, Tooltip, useTheme2 } from '@grafana/ui';
import { checkLogsError, checkLogsSampled, escapeUnescapedString } from '../utils';
import { LogDetails } from './LogDetails';
import { LogLabels } from './LogLabels';
import { LogRowMessage } from './LogRowMessage';
import { LogRowMessageDisplayedFields } from './LogRowMessageDisplayedFields';
import { getLogLevelStyles, LogRowStyles } from './getLogRowStyles';
export interface Props {
row: LogRowModel;
showDuplicates: boolean;
showLabels: boolean;
showTime: boolean;
wrapLogMessage: boolean;
prettifyLogMessage: boolean;
timeZone: TimeZone;
enableLogDetails: boolean;
logsSortOrder?: LogsSortOrder | null;
forceEscape?: boolean;
app?: CoreApp;
displayedFields?: string[];
getRows: () => LogRowModel[];
onClickFilterLabel?: (key: string, value: string, frame?: DataFrame) => void;
onClickFilterOutLabel?: (key: string, value: string, frame?: DataFrame) => void;
onContextClick?: () => void;
getFieldLinks?: (field: Field, rowIndex: number, dataFrame: DataFrame) => Array<LinkModel<Field>>;
showContextToggle?: (row: LogRowModel) => boolean;
onClickShowField?: (key: string) => void;
onClickHideField?: (key: string) => void;
onLogRowHover?: (row?: LogRowModel) => void;
Logs: Redesign and improve LogContext (#65939) * Logs: Add new LogRowContext types to grafana/data * use right type for `RowContextOptions` * add missing renames * add show context modal * no need to call * removed unused css * sort properties * rename * use correct * use * add tests for * wip * remove add/minus buttons * add tests * disable processing of context results in Loki * moved into table to align properly * remove imports * add highlighting of opened logline * improve scrolling behavior * correct style for the table * use correct query direction * fix text * use LoadingBar * use overflow auto * rename `onToggleContext` to `onOpenContext` * add missing import * mock scrollIntoView * update unused props * remove unused import * no need to process context dataframes * only show `LogRowContextModal` if `getRowContext` is defined * remove unused param * use `userEvent` rather `fireEvent` * change to `TimeZone` * directly use style classes * revert change to public_dashboard_service_mock.go * improved styling * add missing await in test * fix lint * fix lint * remove LogRow scrolling when context is opened * remove references to `scrollElement` * Update public/app/features/logs/components/log-context/LogRowContextModal.tsx Co-authored-by: Matias Chomicki <matyax@gmail.com> * fix lint * add comment explaining `onCloseContext` * add comment about debounced onClose * add comments and remove `showRowMenu` * scroll twice to correctly center the element * revert double scrolling * remove unnecessary `processDataFrame` * trigger drone --------- Co-authored-by: Matias Chomicki <matyax@gmail.com>
3 years ago
onOpenContext: (row: LogRowModel, onClose: () => void) => void;
getRowContextQuery?: (
row: LogRowModel,
options?: LogRowContextOptions,
cacheFilters?: boolean
) => Promise<DataQuery | null>;
onPermalinkClick?: (row: LogRowModel) => Promise<void>;
styles: LogRowStyles;
permalinkedRowId?: string;
scrollIntoView?: (element: HTMLElement) => void;
isFilterLabelActive?: (key: string, value: string, refId?: string) => Promise<boolean>;
onPinLine?: (row: LogRowModel, allowUnPin?: boolean) => void;
onUnpinLine?: (row: LogRowModel) => void;
pinLineButtonTooltipTitle?: PopoverContent;
pinned?: boolean;
Log Rows: Added popover menu with filter options when a log line is selected (#75306) * LogRow: detect text selection * LogRow: refactor menu as component * LogRow: add actions to menu * LogRow: hack menu position * Remove unsused imports * LogRowMessage: remove popover code * PopoverMenu: refactor * LogRows: implement PopoverMenu at log rows level * PopoverMenu: implement copy * PopoverMenu: receive row model * PopoverMenu: fix onClick capture issue * Explore: add new filter methods and props for line filters * PopoverMenu: use new filter props * Explore: separate toggleable and non toggleable filters * PopoverMenu: improve copy * ModifyQuery: extend line filter with value argument * PopoverMenu: close with escape * Remove unused import * Prettier * PopoverMenu: remove label filter options * LogRow: rename text selection handling prop * Update test * Remove unused import * Popover menu: add unit test * LogRows: update unit test * Log row: hide the log row menu if the user is selecting text * Log row: dont hide row menu if popover is not in scope * Log rows: rename state variable * Popover menu: allow menu to scroll * Log rows: fix classname prop * Log rows: close popover if mouse event comes from outside the log rows * Declare new class using object style * Fix style declaration * Logs Popover Menu: add string filtering functions (#76757) * Loki modifyQuery: add line does not contain query modification * Elastic modifyQuery: implement line filters * Modify query: change action name to not be loki specific * Prettier * Prettier * Elastic: escape filter values * Popover menu: create feature flag * Log Rows: integrate logsRowsPopoverMenu flag * Rename feature flag * Popover menu: track interactions * Prettier * logRowsPopoverMenu: update stage * Popover menu: add ds type to tracking data * Log rows: move feature flag check * Improve handle deselection
2 years ago
handleTextSelection?: (e: MouseEvent<HTMLTableRowElement>, row: LogRowModel) => boolean;
logRowMenuIconsBefore?: ReactNode[];
logRowMenuIconsAfter?: ReactNode[];
}
export const LogRow = ({
getRows,
onClickFilterLabel,
onClickFilterOutLabel,
onClickShowField,
onClickHideField,
enableLogDetails,
row,
showDuplicates,
showContextToggle,
showLabels,
showTime,
displayedFields,
wrapLogMessage,
prettifyLogMessage,
getFieldLinks,
forceEscape,
app,
styles,
getRowContextQuery,
pinned,
logRowMenuIconsBefore,
logRowMenuIconsAfter,
timeZone,
permalinkedRowId,
scrollIntoView,
handleTextSelection,
onLogRowHover,
...props
}: Props) => {
const [showingContext, setShowingContext] = useState(false);
const [showDetails, setShowDetails] = useState(false);
const [mouseIsOver, setMouseIsOver] = useState(false);
const [permalinked, setPermalinked] = useState(false);
const logLineRef = useRef<HTMLTableRowElement | null>(null);
const theme = useTheme2();
const timestamp = useMemo(
() =>
dateTimeFormat(row.timeEpochMs, {
timeZone: timeZone,
defaultWithMS: true,
}),
[row.timeEpochMs, timeZone]
);
const levelStyles = useMemo(() => getLogLevelStyles(theme, row.logLevel), [row.logLevel, theme]);
const processedRow = useMemo(
() =>
row.hasUnescapedContent && forceEscape
? { ...row, entry: escapeUnescapedString(row.entry), raw: escapeUnescapedString(row.raw) }
: row,
[forceEscape, row]
);
const errorMessage = checkLogsError(row);
const hasError = errorMessage !== undefined;
const sampleMessage = checkLogsSampled(row);
const isSampled = sampleMessage !== undefined;
useEffect(() => {
if (permalinkedRowId !== row.uid) {
setPermalinked(false);
Log Rows: Added popover menu with filter options when a log line is selected (#75306) * LogRow: detect text selection * LogRow: refactor menu as component * LogRow: add actions to menu * LogRow: hack menu position * Remove unsused imports * LogRowMessage: remove popover code * PopoverMenu: refactor * LogRows: implement PopoverMenu at log rows level * PopoverMenu: implement copy * PopoverMenu: receive row model * PopoverMenu: fix onClick capture issue * Explore: add new filter methods and props for line filters * PopoverMenu: use new filter props * Explore: separate toggleable and non toggleable filters * PopoverMenu: improve copy * ModifyQuery: extend line filter with value argument * PopoverMenu: close with escape * Remove unused import * Prettier * PopoverMenu: remove label filter options * LogRow: rename text selection handling prop * Update test * Remove unused import * Popover menu: add unit test * LogRows: update unit test * Log row: hide the log row menu if the user is selecting text * Log row: dont hide row menu if popover is not in scope * Log rows: rename state variable * Popover menu: allow menu to scroll * Log rows: fix classname prop * Log rows: close popover if mouse event comes from outside the log rows * Declare new class using object style * Fix style declaration * Logs Popover Menu: add string filtering functions (#76757) * Loki modifyQuery: add line does not contain query modification * Elastic modifyQuery: implement line filters * Modify query: change action name to not be loki specific * Prettier * Prettier * Elastic: escape filter values * Popover menu: create feature flag * Log Rows: integrate logsRowsPopoverMenu flag * Rename feature flag * Popover menu: track interactions * Prettier * logRowsPopoverMenu: update stage * Popover menu: add ds type to tracking data * Log rows: move feature flag check * Improve handle deselection
2 years ago
return;
}
if (!permalinked) {
setPermalinked(true);
return;
}
if (logLineRef.current && scrollIntoView) {
// at this point this row is the permalinked row, so we need to scroll to it and highlight it if possible.
scrollIntoView(logLineRef.current);
reportInteraction('grafana_explore_logs_permalink_opened', {
datasourceType: row.datasourceType ?? 'unknown',
logRowUid: row.uid,
});
setPermalinked(true);
}
}, [permalinked, permalinkedRowId, row.datasourceType, row.uid, scrollIntoView]);
// we are debouncing the state change by 3 seconds to highlight the logline after the context closed.
// eslint-disable-next-line react-hooks/exhaustive-deps
const debouncedContextClose = useCallback(
debounce(() => {
setShowingContext(false);
}, 3000),
[]
);
const onOpenContext = useCallback(
(row: LogRowModel) => {
setShowingContext(true);
props.onOpenContext(row, debouncedContextClose);
},
[debouncedContextClose, props]
);
const onRowClick = useCallback(
(e: MouseEvent<HTMLTableRowElement>) => {
if (handleTextSelection?.(e, row)) {
// Event handled by the parent.
return;
}
if (!enableLogDetails) {
return;
}
setShowDetails((showDetails: boolean) => !showDetails);
},
[enableLogDetails, handleTextSelection, row]
);
const onMouseEnter = useCallback(() => {
setMouseIsOver(true);
if (onLogRowHover) {
onLogRowHover(row);
}
}, [onLogRowHover, row]);
const onMouseMove = useCallback(
(e: MouseEvent) => {
// No need to worry about text selection.
if (!handleTextSelection) {
return;
}
// The user is selecting text, so hide the log row menu so it doesn't interfere.
if (document.getSelection()?.toString() && e.buttons > 0) {
setMouseIsOver(false);
}
},
[handleTextSelection]
);
const onMouseLeave = useCallback(() => {
setMouseIsOver(false);
}, []);
return (
<>
<tr
ref={logLineRef}
className={`${styles.logsRow} ${hasError ? styles.errorLogRow : ''} ${showingContext || permalinked || pinned ? styles.highlightBackground : ''}`}
onClick={onRowClick}
onMouseEnter={onMouseEnter}
onMouseLeave={onMouseLeave}
onMouseMove={onMouseMove}
/**
* For better accessibility support, we listen to the onFocus event here (to display the LogRowMenuCell), and
* to onBlur event in the LogRowMenuCell (to hide it). This way, the LogRowMenuCell is displayed when the user navigates
* using the keyboard.
*/
onFocus={onMouseEnter}
>
{showDuplicates && (
<td className={styles.logsRowDuplicates}>
{processedRow.duplicates && processedRow.duplicates > 0 ? `${processedRow.duplicates + 1}x` : null}
</td>
)}
<td
className={
hasError || isSampled ? styles.logsRowWithError : `${levelStyles.logsRowLevelColor} ${styles.logsRowLevel}`
}
>
{hasError && (
<Tooltip content={`Error: ${errorMessage}`} placement="right" theme="error">
<Icon className={styles.logIconError} name="exclamation-triangle" size="xs" />
</Tooltip>
)}
{isSampled && (
<Tooltip content={`${sampleMessage}`} placement="right" theme="info">
<Icon className={styles.logIconInfo} name="info-circle" size="xs" />
</Tooltip>
)}
</td>
<td
title={enableLogDetails ? (showDetails ? 'Hide log details' : 'See log details') : ''}
className={enableLogDetails ? styles.logsRowToggleDetails : ''}
>
{enableLogDetails && (
<Icon className={styles.topVerticalAlign} name={showDetails ? 'angle-down' : 'angle-right'} />
)}
</td>
{showTime && <td className={styles.logsRowLocalTime}>{timestamp}</td>}
{showLabels && processedRow.uniqueLabels && (
<td className={styles.logsRowLabels}>
<LogLabels labels={processedRow.uniqueLabels} addTooltip={false} />
</td>
)}
{displayedFields && displayedFields.length > 0 ? (
<LogRowMessageDisplayedFields
row={processedRow}
showContextToggle={showContextToggle}
detectedFields={displayedFields}
getFieldLinks={getFieldLinks}
wrapLogMessage={wrapLogMessage}
onOpenContext={onOpenContext}
onPermalinkClick={props.onPermalinkClick}
styles={styles}
onPinLine={props.onPinLine}
onUnpinLine={props.onUnpinLine}
pinned={pinned}
mouseIsOver={mouseIsOver}
onBlur={onMouseLeave}
logRowMenuIconsBefore={logRowMenuIconsBefore}
logRowMenuIconsAfter={logRowMenuIconsAfter}
/>
) : (
<LogRowMessage
row={processedRow}
showContextToggle={showContextToggle}
getRowContextQuery={getRowContextQuery}
wrapLogMessage={wrapLogMessage}
prettifyLogMessage={prettifyLogMessage}
onOpenContext={onOpenContext}
onPermalinkClick={props.onPermalinkClick}
app={app}
styles={styles}
onPinLine={props.onPinLine}
onUnpinLine={props.onUnpinLine}
pinLineButtonTooltipTitle={props.pinLineButtonTooltipTitle}
pinned={pinned}
mouseIsOver={mouseIsOver}
onBlur={onMouseLeave}
expanded={showDetails}
logRowMenuIconsBefore={logRowMenuIconsBefore}
logRowMenuIconsAfter={logRowMenuIconsAfter}
/>
)}
</tr>
{showDetails && (
<LogDetails
onPinLine={props.onPinLine}
className={`${styles.logsRow} ${hasError ? styles.errorLogRow : ''} ${permalinked && !showDetails ? styles.highlightBackground : ''}`}
showDuplicates={showDuplicates}
getFieldLinks={getFieldLinks}
onClickFilterLabel={onClickFilterLabel}
onClickFilterOutLabel={onClickFilterOutLabel}
onClickShowField={onClickShowField}
onClickHideField={onClickHideField}
getRows={getRows}
row={processedRow}
wrapLogMessage={wrapLogMessage}
hasError={hasError}
displayedFields={displayedFields}
app={app}
styles={styles}
isFilterLabelActive={props.isFilterLabelActive}
pinLineButtonTooltipTitle={props.pinLineButtonTooltipTitle}
/>
)}
</>
);
};