LogRow.tsx 11 KB

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