LogRow.tsx 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359
  1. import React, { PureComponent } from 'react';
  2. import _ from 'lodash';
  3. // @ts-ignore
  4. import Highlighter from 'react-highlight-words';
  5. import classnames from 'classnames';
  6. import { calculateFieldStats, getParser } from 'app/core/logs_model';
  7. import { LogLabels } from './LogLabels';
  8. import { findHighlightChunksInText } from 'app/core/utils/text';
  9. import { LogLabelStats } from './LogLabelStats';
  10. import { LogMessageAnsi } from './LogMessageAnsi';
  11. import { css, cx } from 'emotion';
  12. import {
  13. LogRowContextProvider,
  14. LogRowContextRows,
  15. HasMoreContextRows,
  16. LogRowContextQueryErrors,
  17. } from './LogRowContextProvider';
  18. import { ThemeContext, selectThemeVariant, GrafanaTheme, DataQueryResponse } from '@grafana/ui';
  19. import { LogRowModel, LogLabelStatsModel, LogsParser, TimeZone } from '@grafana/data';
  20. import { LogRowContext } from './LogRowContext';
  21. import tinycolor from 'tinycolor2';
  22. interface Props {
  23. highlighterExpressions?: string[];
  24. row: LogRowModel;
  25. showDuplicates: boolean;
  26. showLabels: boolean;
  27. showTime: boolean;
  28. timeZone: TimeZone;
  29. getRows: () => LogRowModel[];
  30. onClickLabel?: (label: string, value: string) => void;
  31. onContextClick?: () => void;
  32. getRowContext?: (row: LogRowModel, options?: any) => Promise<DataQueryResponse>;
  33. className?: string;
  34. }
  35. interface State {
  36. fieldCount: number;
  37. fieldLabel: string;
  38. fieldStats: LogLabelStatsModel[];
  39. fieldValue: string;
  40. parsed: boolean;
  41. parser?: LogsParser;
  42. parsedFieldHighlights: string[];
  43. showFieldStats: boolean;
  44. showContext: boolean;
  45. }
  46. /**
  47. * Renders a highlighted field.
  48. * When hovering, a stats icon is shown.
  49. */
  50. const FieldHighlight = (onClick: any) => (props: any) => {
  51. return (
  52. <span className={props.className} style={props.style}>
  53. {props.children}
  54. <span className="logs-row__field-highlight--icon fa fa-signal" onClick={() => onClick(props.children)} />
  55. </span>
  56. );
  57. };
  58. const logRowStyles = css`
  59. position: relative;
  60. /* z-index: 0; */
  61. /* outline: none; */
  62. `;
  63. const getLogRowWithContextStyles = (theme: GrafanaTheme, state: State) => {
  64. const outlineColor = selectThemeVariant(
  65. {
  66. light: theme.colors.white,
  67. dark: theme.colors.black,
  68. },
  69. theme.type
  70. );
  71. return {
  72. row: css`
  73. z-index: 1;
  74. outline: 9999px solid
  75. ${tinycolor(outlineColor as tinycolor.ColorInput)
  76. .setAlpha(0.7)
  77. .toRgbString()};
  78. `,
  79. };
  80. };
  81. /**
  82. * Renders a log line.
  83. *
  84. * When user hovers over it for a certain time, it lazily parses the log line.
  85. * Once a parser is found, it will determine fields, that will be highlighted.
  86. * When the user requests stats for a field, they will be calculated and rendered below the row.
  87. */
  88. export class LogRow extends PureComponent<Props, State> {
  89. mouseMessageTimer: NodeJS.Timer;
  90. state: any = {
  91. fieldCount: 0,
  92. fieldLabel: null,
  93. fieldStats: null,
  94. fieldValue: null,
  95. parsed: false,
  96. parser: undefined,
  97. parsedFieldHighlights: [],
  98. showFieldStats: false,
  99. showContext: false,
  100. };
  101. componentWillUnmount() {
  102. clearTimeout(this.mouseMessageTimer);
  103. }
  104. onClickClose = () => {
  105. this.setState({ showFieldStats: false });
  106. };
  107. onClickHighlight = (fieldText: string) => {
  108. const { getRows } = this.props;
  109. const { parser } = this.state;
  110. const allRows = getRows();
  111. // Build value-agnostic row matcher based on the field label
  112. const fieldLabel = parser.getLabelFromField(fieldText);
  113. const fieldValue = parser.getValueFromField(fieldText);
  114. const matcher = parser.buildMatcher(fieldLabel);
  115. const fieldStats = calculateFieldStats(allRows, matcher);
  116. const fieldCount = fieldStats.reduce((sum, stat) => sum + stat.count, 0);
  117. this.setState({ fieldCount, fieldLabel, fieldStats, fieldValue, showFieldStats: true });
  118. };
  119. onMouseOverMessage = () => {
  120. if (this.state.showContext || this.isTextSelected()) {
  121. // When showing context we don't want to the LogRow rerender as it will mess up state of context block
  122. // making the "after" context to be scrolled to the top, what is desired only on open
  123. // The log row message needs to be refactored to separate component that encapsulates parsing and parsed message state
  124. return;
  125. }
  126. // Don't parse right away, user might move along
  127. this.mouseMessageTimer = setTimeout(this.parseMessage, 500);
  128. };
  129. onMouseOutMessage = () => {
  130. if (this.state.showContext) {
  131. // See comment in onMouseOverMessage method
  132. return;
  133. }
  134. clearTimeout(this.mouseMessageTimer);
  135. this.setState({ parsed: false });
  136. };
  137. parseMessage = () => {
  138. if (!this.state.parsed) {
  139. const { row } = this.props;
  140. const parser = getParser(row.entry);
  141. if (parser) {
  142. // Use parser to highlight detected fields
  143. const parsedFieldHighlights = parser.getFields(this.props.row.entry);
  144. this.setState({ parsedFieldHighlights, parsed: true, parser });
  145. }
  146. }
  147. };
  148. isTextSelected() {
  149. if (!window.getSelection) {
  150. return false;
  151. }
  152. const selection = window.getSelection();
  153. if (!selection) {
  154. return false;
  155. }
  156. return selection.anchorNode !== null && selection.isCollapsed === false;
  157. }
  158. toggleContext = () => {
  159. this.setState(state => {
  160. return {
  161. showContext: !state.showContext,
  162. };
  163. });
  164. };
  165. onContextToggle = (e: React.SyntheticEvent<HTMLElement>) => {
  166. e.stopPropagation();
  167. this.toggleContext();
  168. };
  169. renderLogRow(
  170. context?: LogRowContextRows,
  171. errors?: LogRowContextQueryErrors,
  172. hasMoreContextRows?: HasMoreContextRows,
  173. updateLimit?: () => void
  174. ) {
  175. const {
  176. getRows,
  177. highlighterExpressions,
  178. onClickLabel,
  179. row,
  180. showDuplicates,
  181. showLabels,
  182. timeZone,
  183. showTime,
  184. } = this.props;
  185. const {
  186. fieldCount,
  187. fieldLabel,
  188. fieldStats,
  189. fieldValue,
  190. parsed,
  191. parsedFieldHighlights,
  192. showFieldStats,
  193. showContext,
  194. } = this.state;
  195. const { entry, hasAnsi, raw } = row;
  196. const previewHighlights = highlighterExpressions && !_.isEqual(highlighterExpressions, row.searchWords);
  197. const highlights = previewHighlights ? highlighterExpressions : row.searchWords;
  198. const needsHighlighter = highlights && highlights.length > 0 && highlights[0] && highlights[0].length > 0;
  199. const highlightClassName = classnames('logs-row__match-highlight', {
  200. 'logs-row__match-highlight--preview': previewHighlights,
  201. });
  202. const showUtc = timeZone === 'utc';
  203. return (
  204. <ThemeContext.Consumer>
  205. {theme => {
  206. const styles = this.state.showContext
  207. ? cx(logRowStyles, getLogRowWithContextStyles(theme, this.state).row)
  208. : logRowStyles;
  209. return (
  210. <div className={`logs-row ${this.props.className}`}>
  211. {showDuplicates && (
  212. <div className="logs-row__duplicates">{row.duplicates > 0 ? `${row.duplicates + 1}x` : null}</div>
  213. )}
  214. <div className={row.logLevel ? `logs-row__level logs-row__level--${row.logLevel}` : ''} />
  215. {showTime && showUtc && (
  216. <div className="logs-row__localtime" title={`Local: ${row.timeLocal} (${row.timeFromNow})`}>
  217. {row.timeUtc}
  218. </div>
  219. )}
  220. {showTime && !showUtc && (
  221. <div className="logs-row__localtime" title={`${row.timeUtc} (${row.timeFromNow})`}>
  222. {row.timeLocal}
  223. </div>
  224. )}
  225. {showLabels && (
  226. <div className="logs-row__labels">
  227. <LogLabels getRows={getRows} labels={row.uniqueLabels} onClickLabel={onClickLabel} />
  228. </div>
  229. )}
  230. <div
  231. className="logs-row__message"
  232. onMouseEnter={this.onMouseOverMessage}
  233. onMouseLeave={this.onMouseOutMessage}
  234. >
  235. <div
  236. className={css`
  237. position: relative;
  238. `}
  239. >
  240. {showContext && context && (
  241. <LogRowContext
  242. row={row}
  243. context={context}
  244. errors={errors}
  245. hasMoreContextRows={hasMoreContextRows}
  246. onOutsideClick={this.toggleContext}
  247. onLoadMoreContext={() => {
  248. if (updateLimit) {
  249. updateLimit();
  250. }
  251. }}
  252. />
  253. )}
  254. <span className={styles}>
  255. {parsed && (
  256. <Highlighter
  257. style={{ whiteSpace: 'pre-wrap' }}
  258. autoEscape
  259. highlightTag={FieldHighlight(this.onClickHighlight)}
  260. textToHighlight={entry}
  261. searchWords={parsedFieldHighlights}
  262. highlightClassName="logs-row__field-highlight"
  263. />
  264. )}
  265. {!parsed && needsHighlighter && (
  266. <Highlighter
  267. style={{ whiteSpace: 'pre-wrap' }}
  268. textToHighlight={entry}
  269. searchWords={highlights}
  270. findChunks={findHighlightChunksInText}
  271. highlightClassName={highlightClassName}
  272. />
  273. )}
  274. {hasAnsi && !parsed && !needsHighlighter && <LogMessageAnsi value={raw} />}
  275. {!hasAnsi && !parsed && !needsHighlighter && entry}
  276. {showFieldStats && (
  277. <div className="logs-row__stats">
  278. <LogLabelStats
  279. stats={fieldStats}
  280. label={fieldLabel}
  281. value={fieldValue}
  282. onClickClose={this.onClickClose}
  283. rowCount={fieldCount}
  284. />
  285. </div>
  286. )}
  287. </span>
  288. {row.searchWords && row.searchWords.length > 0 && (
  289. <span
  290. onClick={this.onContextToggle}
  291. className={css`
  292. visibility: hidden;
  293. white-space: nowrap;
  294. position: relative;
  295. z-index: ${showContext ? 1 : 0};
  296. cursor: pointer;
  297. .logs-row:hover & {
  298. visibility: visible;
  299. margin-left: 10px;
  300. text-decoration: underline;
  301. }
  302. `}
  303. >
  304. {showContext ? 'Hide' : 'Show'} context
  305. </span>
  306. )}
  307. </div>
  308. </div>
  309. </div>
  310. );
  311. }}
  312. </ThemeContext.Consumer>
  313. );
  314. }
  315. render() {
  316. const { showContext } = this.state;
  317. if (showContext) {
  318. return (
  319. <>
  320. <LogRowContextProvider row={this.props.row} getRowContext={this.props.getRowContext}>
  321. {({ result, errors, hasMoreContextRows, updateLimit }) => {
  322. return <>{this.renderLogRow(result, errors, hasMoreContextRows, updateLimit)}</>;
  323. }}
  324. </LogRowContextProvider>
  325. </>
  326. );
  327. }
  328. return this.renderLogRow();
  329. }
  330. }