LogRow.tsx 11 KB

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