LogRow.tsx 11 KB

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