LogRow.tsx 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354
  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 || this.isTextSelected()) {
  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. isTextSelected() {
  147. if (!window.getSelection) {
  148. return false;
  149. }
  150. const selection = window.getSelection();
  151. if (!selection) {
  152. return false;
  153. }
  154. return selection.anchorNode !== null && selection.isCollapsed === false;
  155. }
  156. toggleContext = () => {
  157. this.setState(state => {
  158. return {
  159. showContext: !state.showContext,
  160. };
  161. });
  162. };
  163. onContextToggle = (e: React.SyntheticEvent<HTMLElement>) => {
  164. e.stopPropagation();
  165. this.toggleContext();
  166. };
  167. renderLogRow(
  168. context?: LogRowContextRows,
  169. errors?: LogRowContextQueryErrors,
  170. hasMoreContextRows?: HasMoreContextRows,
  171. updateLimit?: () => void
  172. ) {
  173. const {
  174. getRows,
  175. highlighterExpressions,
  176. onClickLabel,
  177. row,
  178. showDuplicates,
  179. showLabels,
  180. showLocalTime,
  181. showUtc,
  182. } = this.props;
  183. const {
  184. fieldCount,
  185. fieldLabel,
  186. fieldStats,
  187. fieldValue,
  188. parsed,
  189. parsedFieldHighlights,
  190. showFieldStats,
  191. showContext,
  192. } = this.state;
  193. const { entry, hasAnsi, raw } = row;
  194. const previewHighlights = highlighterExpressions && !_.isEqual(highlighterExpressions, row.searchWords);
  195. const highlights = previewHighlights ? highlighterExpressions : row.searchWords;
  196. const needsHighlighter = highlights && highlights.length > 0 && highlights[0] && highlights[0].length > 0;
  197. const highlightClassName = classnames('logs-row__match-highlight', {
  198. 'logs-row__match-highlight--preview': previewHighlights,
  199. });
  200. return (
  201. <ThemeContext.Consumer>
  202. {theme => {
  203. const styles = this.state.showContext
  204. ? cx(logRowStyles, getLogRowWithContextStyles(theme, this.state).row)
  205. : logRowStyles;
  206. console.log(styles);
  207. return (
  208. <div className={`logs-row ${this.props.className}`}>
  209. {showDuplicates && (
  210. <div className="logs-row__duplicates">{row.duplicates > 0 ? `${row.duplicates + 1}x` : null}</div>
  211. )}
  212. <div className={row.logLevel ? `logs-row__level logs-row__level--${row.logLevel}` : ''} />
  213. {showUtc && (
  214. <div className="logs-row__time" title={`Local: ${row.timeLocal} (${row.timeFromNow})`}>
  215. {row.timestamp}
  216. </div>
  217. )}
  218. {showLocalTime && (
  219. <div className="logs-row__localtime" title={`${row.timestamp} (${row.timeFromNow})`}>
  220. {row.timeLocal}
  221. </div>
  222. )}
  223. {showLabels && (
  224. <div className="logs-row__labels">
  225. <LogLabels getRows={getRows} labels={row.uniqueLabels} onClickLabel={onClickLabel} />
  226. </div>
  227. )}
  228. <div
  229. className="logs-row__message"
  230. onMouseEnter={this.onMouseOverMessage}
  231. onMouseLeave={this.onMouseOutMessage}
  232. >
  233. <div
  234. className={css`
  235. position: relative;
  236. `}
  237. >
  238. {showContext && context && (
  239. <LogRowContext
  240. row={row}
  241. context={context}
  242. errors={errors}
  243. hasMoreContextRows={hasMoreContextRows}
  244. onOutsideClick={this.toggleContext}
  245. onLoadMoreContext={() => {
  246. if (updateLimit) {
  247. updateLimit();
  248. }
  249. }}
  250. />
  251. )}
  252. <span className={styles}>
  253. {parsed && (
  254. <Highlighter
  255. autoEscape
  256. highlightTag={FieldHighlight(this.onClickHighlight)}
  257. textToHighlight={entry}
  258. searchWords={parsedFieldHighlights}
  259. highlightClassName="logs-row__field-highlight"
  260. />
  261. )}
  262. {!parsed && needsHighlighter && (
  263. <Highlighter
  264. textToHighlight={entry}
  265. searchWords={highlights}
  266. findChunks={findHighlightChunksInText}
  267. highlightClassName={highlightClassName}
  268. />
  269. )}
  270. {hasAnsi && !parsed && !needsHighlighter && <LogMessageAnsi value={raw} />}
  271. {!hasAnsi && !parsed && !needsHighlighter && entry}
  272. {showFieldStats && (
  273. <div className="logs-row__stats">
  274. <LogLabelStats
  275. stats={fieldStats}
  276. label={fieldLabel}
  277. value={fieldValue}
  278. onClickClose={this.onClickClose}
  279. rowCount={fieldCount}
  280. />
  281. </div>
  282. )}
  283. </span>
  284. {row.searchWords && row.searchWords.length > 0 && (
  285. <span
  286. onClick={this.onContextToggle}
  287. className={css`
  288. visibility: hidden;
  289. white-space: nowrap;
  290. position: relative;
  291. z-index: ${showContext ? 1 : 0};
  292. cursor: pointer;
  293. .logs-row:hover & {
  294. visibility: visible;
  295. margin-left: 10px;
  296. text-decoration: underline;
  297. }
  298. `}
  299. >
  300. {showContext ? 'Hide' : 'Show'} context
  301. </span>
  302. )}
  303. </div>
  304. </div>
  305. </div>
  306. );
  307. }}
  308. </ThemeContext.Consumer>
  309. );
  310. }
  311. render() {
  312. const { showContext } = this.state;
  313. if (showContext) {
  314. return (
  315. <>
  316. <LogRowContextProvider row={this.props.row} getRowContext={this.props.getRowContext}>
  317. {({ result, errors, hasMoreContextRows, updateLimit }) => {
  318. return <>{this.renderLogRow(result, errors, hasMoreContextRows, updateLimit)}</>;
  319. }}
  320. </LogRowContextProvider>
  321. </>
  322. );
  323. }
  324. return this.renderLogRow();
  325. }
  326. }