result_transformer.ts 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  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;
  27. while ((match = regexp.exec(line))) {
  28. matches.push({
  29. text: match[0],
  30. start: match.index,
  31. length: match[0].length,
  32. });
  33. }
  34. return matches;
  35. }
  36. export function processEntry(entry: { line: string; timestamp: string }, stream): LogRow {
  37. const { line, timestamp } = entry;
  38. const { labels } = stream;
  39. const key = `EK${timestamp}${labels}`;
  40. const time = moment(timestamp);
  41. const timeFromNow = time.fromNow();
  42. const timeLocal = time.format('YYYY-MM-DD HH:mm:ss');
  43. const searchMatches = getSearchMatches(line, stream.search);
  44. const logLevel = getLogLevel(line);
  45. return {
  46. key,
  47. logLevel,
  48. searchMatches,
  49. timeFromNow,
  50. timeLocal,
  51. entry: line,
  52. timestamp: timestamp,
  53. };
  54. }
  55. export function processStreams(streams, limit?: number): LogsModel {
  56. const combinedEntries = streams.reduce((acc, stream) => {
  57. return [...acc, ...stream.entries.map(entry => processEntry(entry, stream))];
  58. }, []);
  59. const sortedEntries = _.chain(combinedEntries)
  60. .sortBy('timestamp')
  61. .reverse()
  62. .slice(0, limit || combinedEntries.length)
  63. .value();
  64. return { rows: sortedEntries };
  65. }