logs_model.ts 9.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353
  1. import _ from 'lodash';
  2. import { colors, TimeSeries } from '@grafana/ui';
  3. import { getThemeColor } from 'app/core/utils/colors';
  4. /**
  5. * Mapping of log level abbreviation to canonical log level.
  6. * Supported levels are reduce to limit color variation.
  7. */
  8. export enum LogLevel {
  9. emerg = 'critical',
  10. alert = 'critical',
  11. crit = 'critical',
  12. critical = 'critical',
  13. warn = 'warning',
  14. warning = 'warning',
  15. err = 'error',
  16. eror = 'error',
  17. error = 'error',
  18. info = 'info',
  19. notice = 'info',
  20. dbug = 'debug',
  21. debug = 'debug',
  22. trace = 'trace',
  23. unknown = 'unknown',
  24. }
  25. export const LogLevelColor = {
  26. [LogLevel.critical]: colors[7],
  27. [LogLevel.warning]: colors[1],
  28. [LogLevel.error]: colors[4],
  29. [LogLevel.info]: colors[0],
  30. [LogLevel.debug]: colors[5],
  31. [LogLevel.trace]: colors[2],
  32. [LogLevel.unknown]: getThemeColor('#8e8e8e', '#dde4ed'),
  33. };
  34. export interface LogSearchMatch {
  35. start: number;
  36. length: number;
  37. text: string;
  38. }
  39. export interface LogRowModel {
  40. duplicates?: number;
  41. entry: string;
  42. hasAnsi: boolean;
  43. key: string; // timestamp + labels
  44. labels: LogsStreamLabels;
  45. logLevel: LogLevel;
  46. raw: string;
  47. searchWords?: string[];
  48. timestamp: string; // ISO with nanosec precision
  49. timeFromNow: string;
  50. timeEpochMs: number;
  51. timeLocal: string;
  52. uniqueLabels?: LogsStreamLabels;
  53. }
  54. export interface LogLabelStatsModel {
  55. active?: boolean;
  56. count: number;
  57. proportion: number;
  58. value: string;
  59. }
  60. export enum LogsMetaKind {
  61. Number,
  62. String,
  63. LabelsMap,
  64. }
  65. export interface LogsMetaItem {
  66. label: string;
  67. value: string | number | LogsStreamLabels;
  68. kind: LogsMetaKind;
  69. }
  70. export interface LogsModel {
  71. id: string; // Identify one logs result from another
  72. meta?: LogsMetaItem[];
  73. rows: LogRowModel[];
  74. series?: TimeSeries[];
  75. }
  76. export interface LogsStream {
  77. labels: string;
  78. entries: LogsStreamEntry[];
  79. search?: string;
  80. parsedLabels?: LogsStreamLabels;
  81. uniqueLabels?: LogsStreamLabels;
  82. }
  83. export interface LogsStreamEntry {
  84. line: string;
  85. ts: string;
  86. // Legacy, was renamed to ts
  87. timestamp?: string;
  88. }
  89. export interface LogsStreamLabels {
  90. [key: string]: string;
  91. }
  92. export enum LogsDedupDescription {
  93. none = 'No de-duplication',
  94. exact = 'De-duplication of successive lines that are identical, ignoring ISO datetimes.',
  95. numbers = 'De-duplication of successive lines that are identical when ignoring numbers, e.g., IP addresses, latencies.',
  96. signature = 'De-duplication of successive lines that have identical punctuation and whitespace.',
  97. }
  98. export enum LogsDedupStrategy {
  99. none = 'none',
  100. exact = 'exact',
  101. numbers = 'numbers',
  102. signature = 'signature',
  103. }
  104. export interface LogsParser {
  105. /**
  106. * Value-agnostic matcher for a field label.
  107. * Used to filter rows, and first capture group contains the value.
  108. */
  109. buildMatcher: (label: string) => RegExp;
  110. /**
  111. * Returns all parsable substrings from a line, used for highlighting
  112. */
  113. getFields: (line: string) => string[];
  114. /**
  115. * Gets the label name from a parsable substring of a line
  116. */
  117. getLabelFromField: (field: string) => string;
  118. /**
  119. * Gets the label value from a parsable substring of a line
  120. */
  121. getValueFromField: (field: string) => string;
  122. /**
  123. * Function to verify if this is a valid parser for the given line.
  124. * The parser accepts the line unless it returns undefined.
  125. */
  126. test: (line: string) => any;
  127. }
  128. const LOGFMT_REGEXP = /(?:^|\s)(\w+)=("[^"]*"|\S+)/;
  129. export const LogsParsers: { [name: string]: LogsParser } = {
  130. JSON: {
  131. buildMatcher: label => new RegExp(`(?:{|,)\\s*"${label}"\\s*:\\s*"?([\\d\\.]+|[^"]*)"?`),
  132. getFields: line => {
  133. const fields = [];
  134. try {
  135. const parsed = JSON.parse(line);
  136. _.map(parsed, (value, key) => {
  137. const fieldMatcher = new RegExp(`"${key}"\\s*:\\s*"?${_.escapeRegExp(JSON.stringify(value))}"?`);
  138. const match = line.match(fieldMatcher);
  139. if (match) {
  140. fields.push(match[0]);
  141. }
  142. });
  143. } catch {}
  144. return fields;
  145. },
  146. getLabelFromField: field => (field.match(/^"(\w+)"\s*:/) || [])[1],
  147. getValueFromField: field => (field.match(/:\s*(.*)$/) || [])[1],
  148. test: line => {
  149. try {
  150. return JSON.parse(line);
  151. } catch (error) {}
  152. },
  153. },
  154. logfmt: {
  155. buildMatcher: label => new RegExp(`(?:^|\\s)${label}=("[^"]*"|\\S+)`),
  156. getFields: line => {
  157. const fields = [];
  158. line.replace(new RegExp(LOGFMT_REGEXP, 'g'), substring => {
  159. fields.push(substring.trim());
  160. return '';
  161. });
  162. return fields;
  163. },
  164. getLabelFromField: field => (field.match(LOGFMT_REGEXP) || [])[1],
  165. getValueFromField: field => (field.match(LOGFMT_REGEXP) || [])[2],
  166. test: line => LOGFMT_REGEXP.test(line),
  167. },
  168. };
  169. export function calculateFieldStats(rows: LogRowModel[], extractor: RegExp): LogLabelStatsModel[] {
  170. // Consider only rows that satisfy the matcher
  171. const rowsWithField = rows.filter(row => extractor.test(row.entry));
  172. const rowCount = rowsWithField.length;
  173. // Get field value counts for eligible rows
  174. const countsByValue = _.countBy(rowsWithField, row => (row as LogRowModel).entry.match(extractor)[1]);
  175. const sortedCounts = _.chain(countsByValue)
  176. .map((count, value) => ({ count, value, proportion: count / rowCount }))
  177. .sortBy('count')
  178. .reverse()
  179. .value();
  180. return sortedCounts;
  181. }
  182. export function calculateLogsLabelStats(rows: LogRowModel[], label: string): LogLabelStatsModel[] {
  183. // Consider only rows that have the given label
  184. const rowsWithLabel = rows.filter(row => row.labels[label] !== undefined);
  185. const rowCount = rowsWithLabel.length;
  186. // Get label value counts for eligible rows
  187. const countsByValue = _.countBy(rowsWithLabel, row => (row as LogRowModel).labels[label]);
  188. const sortedCounts = _.chain(countsByValue)
  189. .map((count, value) => ({ count, value, proportion: count / rowCount }))
  190. .sortBy('count')
  191. .reverse()
  192. .value();
  193. return sortedCounts;
  194. }
  195. const isoDateRegexp = /\d{4}-[01]\d-[0-3]\dT[0-2]\d:[0-5]\d:[0-6]\d[,\.]\d+([+-][0-2]\d:[0-5]\d|Z)/g;
  196. function isDuplicateRow(row: LogRowModel, other: LogRowModel, strategy: LogsDedupStrategy): boolean {
  197. switch (strategy) {
  198. case LogsDedupStrategy.exact:
  199. // Exact still strips dates
  200. return row.entry.replace(isoDateRegexp, '') === other.entry.replace(isoDateRegexp, '');
  201. case LogsDedupStrategy.numbers:
  202. return row.entry.replace(/\d/g, '') === other.entry.replace(/\d/g, '');
  203. case LogsDedupStrategy.signature:
  204. return row.entry.replace(/\w/g, '') === other.entry.replace(/\w/g, '');
  205. default:
  206. return false;
  207. }
  208. }
  209. export function dedupLogRows(logs: LogsModel, strategy: LogsDedupStrategy): LogsModel {
  210. if (strategy === LogsDedupStrategy.none) {
  211. return logs;
  212. }
  213. const dedupedRows = logs.rows.reduce((result: LogRowModel[], row: LogRowModel, index, list) => {
  214. const rowCopy = { ...row };
  215. const previous = result[result.length - 1];
  216. if (index > 0 && isDuplicateRow(row, previous, strategy)) {
  217. previous.duplicates++;
  218. } else {
  219. rowCopy.duplicates = 0;
  220. result.push(rowCopy);
  221. }
  222. return result;
  223. }, []);
  224. return {
  225. ...logs,
  226. rows: dedupedRows,
  227. };
  228. }
  229. export function getParser(line: string): LogsParser {
  230. let parser;
  231. try {
  232. if (LogsParsers.JSON.test(line)) {
  233. parser = LogsParsers.JSON;
  234. }
  235. } catch (error) {}
  236. if (!parser && LogsParsers.logfmt.test(line)) {
  237. parser = LogsParsers.logfmt;
  238. }
  239. return parser;
  240. }
  241. export function filterLogLevels(logs: LogsModel, hiddenLogLevels: Set<LogLevel>): LogsModel {
  242. if (hiddenLogLevels.size === 0) {
  243. return logs;
  244. }
  245. const filteredRows = logs.rows.reduce((result: LogRowModel[], row: LogRowModel, index, list) => {
  246. if (!hiddenLogLevels.has(row.logLevel)) {
  247. result.push(row);
  248. }
  249. return result;
  250. }, []);
  251. return {
  252. ...logs,
  253. rows: filteredRows,
  254. };
  255. }
  256. export function makeSeriesForLogs(rows: LogRowModel[], intervalMs: number): TimeSeries[] {
  257. // currently interval is rangeMs / resolution, which is too low for showing series as bars.
  258. // need at least 10px per bucket, so we multiply interval by 10. Should be solved higher up the chain
  259. // when executing queries & interval calculated and not here but this is a temporary fix.
  260. // intervalMs = intervalMs * 10;
  261. // Graph time series by log level
  262. const seriesByLevel = {};
  263. const bucketSize = intervalMs * 10;
  264. const seriesList = [];
  265. for (const row of rows) {
  266. let series = seriesByLevel[row.logLevel];
  267. if (!series) {
  268. seriesByLevel[row.logLevel] = series = {
  269. lastTs: null,
  270. datapoints: [],
  271. alias: row.logLevel,
  272. color: LogLevelColor[row.logLevel],
  273. };
  274. seriesList.push(series);
  275. }
  276. // align time to bucket size
  277. const time = Math.round(row.timeEpochMs / bucketSize) * bucketSize;
  278. // Entry for time
  279. if (time === series.lastTs) {
  280. series.datapoints[series.datapoints.length - 1][0]++;
  281. } else {
  282. series.datapoints.push([1, time]);
  283. series.lastTs = time;
  284. }
  285. // add zero to other levels to aid stacking so each level series has same number of points
  286. for (const other of seriesList) {
  287. if (other !== series && other.lastTs !== time) {
  288. other.datapoints.push([0, time]);
  289. other.lastTs = time;
  290. }
  291. }
  292. }
  293. return seriesList.map(series => {
  294. series.datapoints.sort((a, b) => {
  295. return a[1] - b[1];
  296. });
  297. return {
  298. datapoints: series.datapoints,
  299. target: series.alias,
  300. alias: series.alias,
  301. color: series.color,
  302. };
  303. });
  304. }