result_transformer.ts 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. import _ from 'lodash';
  2. import moment from 'moment';
  3. import { LogLevel, LogsModel, LogRow } from 'app/core/logs_model';
  4. export function getLogLevel(line: string): LogLevel {
  5. if (!line) {
  6. return undefined;
  7. }
  8. let level: LogLevel;
  9. Object.keys(LogLevel).forEach(key => {
  10. if (!level) {
  11. const regexp = new RegExp(`\\b${key}\\b`, 'i');
  12. if (regexp.test(line)) {
  13. level = LogLevel[key];
  14. }
  15. }
  16. });
  17. return level;
  18. }
  19. export function getSearchMatches(line: string, search: string) {
  20. // Empty search can send re.exec() into infinite loop, exit early
  21. if (!line || !search) {
  22. return [];
  23. }
  24. const regexp = new RegExp(`(?:${search})`, 'g');
  25. const matches = [];
  26. let match = regexp.exec(line);
  27. while (match) {
  28. matches.push({
  29. text: match[0],
  30. start: match.index,
  31. length: match[0].length,
  32. });
  33. match = regexp.exec(line);
  34. }
  35. return matches;
  36. }
  37. export function processEntry(entry: { line: string; timestamp: string }, stream): LogRow {
  38. const { line, timestamp } = entry;
  39. const { labels } = stream;
  40. const key = `EK${timestamp}${labels}`;
  41. const time = moment(timestamp);
  42. const timeFromNow = time.fromNow();
  43. const timeLocal = time.format('YYYY-MM-DD HH:mm:ss');
  44. const searchMatches = getSearchMatches(line, stream.search);
  45. const logLevel = getLogLevel(line);
  46. return {
  47. key,
  48. logLevel,
  49. searchMatches,
  50. timeFromNow,
  51. timeLocal,
  52. entry: line,
  53. timestamp: timestamp,
  54. };
  55. }
  56. export function processStreams(streams, limit?: number): LogsModel {
  57. const combinedEntries = streams.reduce((acc, stream) => {
  58. return [...acc, ...stream.entries.map(entry => processEntry(entry, stream))];
  59. }, []);
  60. const sortedEntries = _.chain(combinedEntries)
  61. .sortBy('timestamp')
  62. .reverse()
  63. .slice(0, limit || combinedEntries.length)
  64. .value();
  65. return { rows: sortedEntries };
  66. }