LogRow.tsx 11 KB

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