logs_model.ts 7.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273
  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 LogsDedupStrategy {
  80. none = 'none',
  81. exact = 'exact',
  82. numbers = 'numbers',
  83. signature = 'signature',
  84. }
  85. export interface LogsParser {
  86. /**
  87. * Value-agnostic matcher for a field label.
  88. * Used to filter rows, and first capture group contains the value.
  89. */
  90. buildMatcher: (label: string) => RegExp;
  91. /**
  92. * Regex to find a field in the log line.
  93. * First capture group contains the label value, second capture group the value.
  94. */
  95. fieldRegex: RegExp;
  96. /**
  97. * Function to verify if this is a valid parser for the given line.
  98. * The parser accepts the line unless it returns undefined.
  99. */
  100. test: (line: string) => any;
  101. }
  102. export const LogsParsers: { [name: string]: LogsParser } = {
  103. JSON: {
  104. buildMatcher: label => new RegExp(`(?:{|,)\\s*"${label}"\\s*:\\s*"([^"]*)"`),
  105. fieldRegex: /"(\w+)"\s*:\s*"([^"]*)"/,
  106. test: line => {
  107. try {
  108. return JSON.parse(line);
  109. } catch (error) {}
  110. },
  111. },
  112. logfmt: {
  113. buildMatcher: label => new RegExp(`(?:^|\\s)${label}=("[^"]*"|\\S+)`),
  114. fieldRegex: /(?:^|\s)(\w+)=("[^"]*"|\S+)/,
  115. test: line => LogsParsers.logfmt.fieldRegex.test(line),
  116. },
  117. };
  118. export function calculateFieldStats(rows: LogRow[], extractor: RegExp): LogsLabelStat[] {
  119. // Consider only rows that satisfy the matcher
  120. const rowsWithField = rows.filter(row => extractor.test(row.entry));
  121. const rowCount = rowsWithField.length;
  122. // Get field value counts for eligible rows
  123. const countsByValue = _.countBy(rowsWithField, row => (row as LogRow).entry.match(extractor)[1]);
  124. const sortedCounts = _.chain(countsByValue)
  125. .map((count, value) => ({ count, value, proportion: count / rowCount }))
  126. .sortBy('count')
  127. .reverse()
  128. .value();
  129. return sortedCounts;
  130. }
  131. export function calculateLogsLabelStats(rows: LogRow[], label: string): LogsLabelStat[] {
  132. // Consider only rows that have the given label
  133. const rowsWithLabel = rows.filter(row => row.labels[label] !== undefined);
  134. const rowCount = rowsWithLabel.length;
  135. // Get label value counts for eligible rows
  136. const countsByValue = _.countBy(rowsWithLabel, row => (row as LogRow).labels[label]);
  137. const sortedCounts = _.chain(countsByValue)
  138. .map((count, value) => ({ count, value, proportion: count / rowCount }))
  139. .sortBy('count')
  140. .reverse()
  141. .value();
  142. return sortedCounts;
  143. }
  144. 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;
  145. function isDuplicateRow(row: LogRow, other: LogRow, strategy: LogsDedupStrategy): boolean {
  146. switch (strategy) {
  147. case LogsDedupStrategy.exact:
  148. // Exact still strips dates
  149. return row.entry.replace(isoDateRegexp, '') === other.entry.replace(isoDateRegexp, '');
  150. case LogsDedupStrategy.numbers:
  151. return row.entry.replace(/\d/g, '') === other.entry.replace(/\d/g, '');
  152. case LogsDedupStrategy.signature:
  153. return row.entry.replace(/\w/g, '') === other.entry.replace(/\w/g, '');
  154. default:
  155. return false;
  156. }
  157. }
  158. export function dedupLogRows(logs: LogsModel, strategy: LogsDedupStrategy): LogsModel {
  159. if (strategy === LogsDedupStrategy.none) {
  160. return logs;
  161. }
  162. const dedupedRows = logs.rows.reduce((result: LogRow[], row: LogRow, index, list) => {
  163. const previous = result[result.length - 1];
  164. if (index > 0 && isDuplicateRow(row, previous, strategy)) {
  165. previous.duplicates++;
  166. } else {
  167. row.duplicates = 0;
  168. result.push(row);
  169. }
  170. return result;
  171. }, []);
  172. return {
  173. ...logs,
  174. rows: dedupedRows,
  175. };
  176. }
  177. export function getParser(line: string): LogsParser {
  178. let parser;
  179. try {
  180. if (LogsParsers.JSON.test(line)) {
  181. parser = LogsParsers.JSON;
  182. }
  183. } catch (error) {}
  184. if (!parser && LogsParsers.logfmt.test(line)) {
  185. parser = LogsParsers.logfmt;
  186. }
  187. return parser;
  188. }
  189. export function filterLogLevels(logs: LogsModel, hiddenLogLevels: Set<LogLevel>): LogsModel {
  190. if (hiddenLogLevels.size === 0) {
  191. return logs;
  192. }
  193. const filteredRows = logs.rows.reduce((result: LogRow[], row: LogRow, index, list) => {
  194. if (!hiddenLogLevels.has(row.logLevel)) {
  195. result.push(row);
  196. }
  197. return result;
  198. }, []);
  199. return {
  200. ...logs,
  201. rows: filteredRows,
  202. };
  203. }
  204. export function makeSeriesForLogs(rows: LogRow[], intervalMs: number): TimeSeries[] {
  205. // currently interval is rangeMs / resolution, which is too low for showing series as bars.
  206. // need at least 10px per bucket, so we multiply interval by 10. Should be solved higher up the chain
  207. // when executing queries & interval calculated and not here but this is a temporary fix.
  208. // intervalMs = intervalMs * 10;
  209. // Graph time series by log level
  210. const seriesByLevel = {};
  211. const bucketSize = intervalMs * 10;
  212. for (const row of rows) {
  213. if (!seriesByLevel[row.logLevel]) {
  214. seriesByLevel[row.logLevel] = { lastTs: null, datapoints: [], alias: row.logLevel };
  215. }
  216. const levelSeries = seriesByLevel[row.logLevel];
  217. // Bucket to nearest minute
  218. const time = Math.round(row.timeEpochMs / bucketSize) * bucketSize;
  219. // Entry for time
  220. if (time === levelSeries.lastTs) {
  221. levelSeries.datapoints[levelSeries.datapoints.length - 1][0]++;
  222. } else {
  223. levelSeries.datapoints.push([1, time]);
  224. levelSeries.lastTs = time;
  225. }
  226. }
  227. return Object.keys(seriesByLevel).reduce((acc, level) => {
  228. if (seriesByLevel[level]) {
  229. const gs = new TimeSeries(seriesByLevel[level]);
  230. gs.setColor(LogLevelColor[level]);
  231. acc.push(gs);
  232. }
  233. return acc;
  234. }, []);
  235. }