logs_model.ts 7.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280
  1. import _ from 'lodash';
  2. import { TimeSeries } from 'app/core/core';
  3. import colors, { getThemeColor } from 'app/core/utils/colors';
  4. export enum LogLevel {
  5. crit = 'critical',
  6. critical = 'critical',
  7. warn = 'warning',
  8. warning = 'warning',
  9. err = 'error',
  10. error = 'error',
  11. info = 'info',
  12. debug = 'debug',
  13. trace = 'trace',
  14. unkown = 'unkown',
  15. }
  16. export const LogLevelColor = {
  17. [LogLevel.critical]: colors[7],
  18. [LogLevel.warning]: colors[1],
  19. [LogLevel.error]: colors[4],
  20. [LogLevel.info]: colors[0],
  21. [LogLevel.debug]: colors[5],
  22. [LogLevel.trace]: colors[2],
  23. [LogLevel.unkown]: getThemeColor('#8e8e8e', '#dde4ed'),
  24. };
  25. export interface LogSearchMatch {
  26. start: number;
  27. length: number;
  28. text: string;
  29. }
  30. export interface LogRow {
  31. duplicates?: number;
  32. entry: string;
  33. key: string; // timestamp + labels
  34. labels: LogsStreamLabels;
  35. logLevel: LogLevel;
  36. searchWords?: string[];
  37. timestamp: string; // ISO with nanosec precision
  38. timeFromNow: string;
  39. timeEpochMs: number;
  40. timeLocal: string;
  41. uniqueLabels?: LogsStreamLabels;
  42. }
  43. export interface LogsLabelStat {
  44. active?: boolean;
  45. count: number;
  46. proportion: number;
  47. value: string;
  48. }
  49. export enum LogsMetaKind {
  50. Number,
  51. String,
  52. LabelsMap,
  53. }
  54. export interface LogsMetaItem {
  55. label: string;
  56. value: string | number | LogsStreamLabels;
  57. kind: LogsMetaKind;
  58. }
  59. export interface LogsModel {
  60. id: string; // Identify one logs result from another
  61. meta?: LogsMetaItem[];
  62. rows: LogRow[];
  63. series?: TimeSeries[];
  64. }
  65. export interface LogsStream {
  66. labels: string;
  67. entries: LogsStreamEntry[];
  68. search?: string;
  69. parsedLabels?: LogsStreamLabels;
  70. uniqueLabels?: LogsStreamLabels;
  71. }
  72. export interface LogsStreamEntry {
  73. line: string;
  74. timestamp: string;
  75. }
  76. export interface LogsStreamLabels {
  77. [key: string]: string;
  78. }
  79. export enum LogsDedupDescription {
  80. none = 'No de-duplication',
  81. exact = 'De-duplication of successive lines that are identical, ignoring ISO datetimes.',
  82. numbers = 'De-duplication of successive lines that are identical when ignoring numbers, e.g., IP addresses, latencies.',
  83. signature = 'De-duplication of successive lines that have identical punctuation and whitespace.',
  84. }
  85. export enum LogsDedupStrategy {
  86. none = 'none',
  87. exact = 'exact',
  88. numbers = 'numbers',
  89. signature = 'signature',
  90. }
  91. export interface LogsParser {
  92. /**
  93. * Value-agnostic matcher for a field label.
  94. * Used to filter rows, and first capture group contains the value.
  95. */
  96. buildMatcher: (label: string) => RegExp;
  97. /**
  98. * Regex to find a field in the log line.
  99. * First capture group contains the label value, second capture group the value.
  100. */
  101. fieldRegex: RegExp;
  102. /**
  103. * Function to verify if this is a valid parser for the given line.
  104. * The parser accepts the line unless it returns undefined.
  105. */
  106. test: (line: string) => any;
  107. }
  108. export const LogsParsers: { [name: string]: LogsParser } = {
  109. JSON: {
  110. buildMatcher: label => new RegExp(`(?:{|,)\\s*"${label}"\\s*:\\s*"([^"]*)"`),
  111. fieldRegex: /"(\w+)"\s*:\s*"([^"]*)"/,
  112. test: line => {
  113. try {
  114. return JSON.parse(line);
  115. } catch (error) {}
  116. },
  117. },
  118. logfmt: {
  119. buildMatcher: label => new RegExp(`(?:^|\\s)${label}=("[^"]*"|\\S+)`),
  120. fieldRegex: /(?:^|\s)(\w+)=("[^"]*"|\S+)/,
  121. test: line => LogsParsers.logfmt.fieldRegex.test(line),
  122. },
  123. };
  124. export function calculateFieldStats(rows: LogRow[], extractor: RegExp): LogsLabelStat[] {
  125. // Consider only rows that satisfy the matcher
  126. const rowsWithField = rows.filter(row => extractor.test(row.entry));
  127. const rowCount = rowsWithField.length;
  128. // Get field value counts for eligible rows
  129. const countsByValue = _.countBy(rowsWithField, row => (row as LogRow).entry.match(extractor)[1]);
  130. const sortedCounts = _.chain(countsByValue)
  131. .map((count, value) => ({ count, value, proportion: count / rowCount }))
  132. .sortBy('count')
  133. .reverse()
  134. .value();
  135. return sortedCounts;
  136. }
  137. export function calculateLogsLabelStats(rows: LogRow[], label: string): LogsLabelStat[] {
  138. // Consider only rows that have the given label
  139. const rowsWithLabel = rows.filter(row => row.labels[label] !== undefined);
  140. const rowCount = rowsWithLabel.length;
  141. // Get label value counts for eligible rows
  142. const countsByValue = _.countBy(rowsWithLabel, row => (row as LogRow).labels[label]);
  143. const sortedCounts = _.chain(countsByValue)
  144. .map((count, value) => ({ count, value, proportion: count / rowCount }))
  145. .sortBy('count')
  146. .reverse()
  147. .value();
  148. return sortedCounts;
  149. }
  150. 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;
  151. function isDuplicateRow(row: LogRow, other: LogRow, strategy: LogsDedupStrategy): boolean {
  152. switch (strategy) {
  153. case LogsDedupStrategy.exact:
  154. // Exact still strips dates
  155. return row.entry.replace(isoDateRegexp, '') === other.entry.replace(isoDateRegexp, '');
  156. case LogsDedupStrategy.numbers:
  157. return row.entry.replace(/\d/g, '') === other.entry.replace(/\d/g, '');
  158. case LogsDedupStrategy.signature:
  159. return row.entry.replace(/\w/g, '') === other.entry.replace(/\w/g, '');
  160. default:
  161. return false;
  162. }
  163. }
  164. export function dedupLogRows(logs: LogsModel, strategy: LogsDedupStrategy): LogsModel {
  165. if (strategy === LogsDedupStrategy.none) {
  166. return logs;
  167. }
  168. const dedupedRows = logs.rows.reduce((result: LogRow[], row: LogRow, index, list) => {
  169. const previous = result[result.length - 1];
  170. if (index > 0 && isDuplicateRow(row, previous, strategy)) {
  171. previous.duplicates++;
  172. } else {
  173. row.duplicates = 0;
  174. result.push(row);
  175. }
  176. return result;
  177. }, []);
  178. return {
  179. ...logs,
  180. rows: dedupedRows,
  181. };
  182. }
  183. export function getParser(line: string): LogsParser {
  184. let parser;
  185. try {
  186. if (LogsParsers.JSON.test(line)) {
  187. parser = LogsParsers.JSON;
  188. }
  189. } catch (error) {}
  190. if (!parser && LogsParsers.logfmt.test(line)) {
  191. parser = LogsParsers.logfmt;
  192. }
  193. return parser;
  194. }
  195. export function filterLogLevels(logs: LogsModel, hiddenLogLevels: Set<LogLevel>): LogsModel {
  196. if (hiddenLogLevels.size === 0) {
  197. return logs;
  198. }
  199. const filteredRows = logs.rows.reduce((result: LogRow[], row: LogRow, index, list) => {
  200. if (!hiddenLogLevels.has(row.logLevel)) {
  201. result.push(row);
  202. }
  203. return result;
  204. }, []);
  205. return {
  206. ...logs,
  207. rows: filteredRows,
  208. };
  209. }
  210. export function makeSeriesForLogs(rows: LogRow[], intervalMs: number): TimeSeries[] {
  211. // currently interval is rangeMs / resolution, which is too low for showing series as bars.
  212. // need at least 10px per bucket, so we multiply interval by 10. Should be solved higher up the chain
  213. // when executing queries & interval calculated and not here but this is a temporary fix.
  214. // intervalMs = intervalMs * 10;
  215. // Graph time series by log level
  216. const seriesByLevel = {};
  217. const bucketSize = intervalMs * 10;
  218. for (const row of rows) {
  219. if (!seriesByLevel[row.logLevel]) {
  220. seriesByLevel[row.logLevel] = { lastTs: null, datapoints: [], alias: row.logLevel };
  221. }
  222. const levelSeries = seriesByLevel[row.logLevel];
  223. // Bucket to nearest minute
  224. const time = Math.round(row.timeEpochMs / bucketSize) * bucketSize;
  225. // Entry for time
  226. if (time === levelSeries.lastTs) {
  227. levelSeries.datapoints[levelSeries.datapoints.length - 1][0]++;
  228. } else {
  229. levelSeries.datapoints.push([1, time]);
  230. levelSeries.lastTs = time;
  231. }
  232. }
  233. return Object.keys(seriesByLevel).reduce((acc, level) => {
  234. if (seriesByLevel[level]) {
  235. const gs = new TimeSeries(seriesByLevel[level]);
  236. gs.setColor(LogLevelColor[level]);
  237. acc.push(gs);
  238. }
  239. return acc;
  240. }, []);
  241. }