logs_model.ts 9.3 KB

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