log_parser.h 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. #pragma once
  2. #include <yql/essentials/utils/log/log.h>
  3. #include <library/cpp/testing/unittest/registar.h>
  4. #include <util/datetime/base.h>
  5. #include <regex>
  6. namespace NYql {
  7. namespace NLog {
  8. struct TLogRow {
  9. TInstant Time;
  10. ELevel Level;
  11. TString ProcName;
  12. pid_t ProcId;
  13. ui64 ThreadId;
  14. EComponent Component;
  15. TString FileName;
  16. ui32 LineNumber;
  17. TString Message;
  18. };
  19. static TLogRow ParseLogRow(const TString& str) {
  20. static std::regex rowRe(
  21. "^([0-9]{4}-[0-9]{2}-[0-9]{2} [0-9]{2}:[0-9]{2}:[0-9]{2}\\.[0-9]{3}) " // (1) time
  22. "([A-Z ]{5}) " // (2) level
  23. "([a-zA-Z0-9_\\.-]+)" // (3) process name
  24. ".pid=([0-9]+)," // (4) process id
  25. " tid=(0?x?[0-9a-fA-F]+). " // (5) thread id
  26. ".([a-zA-Z0-9_\\. ]+). " // (6) component name
  27. "([^:]+):" // (7) file name
  28. "([0-9]+): " // (8) line number
  29. "([^\n]*)\n?$" // (9) message
  30. , std::regex_constants::extended);
  31. std::cmatch match;
  32. bool isMatch = std::regex_match(str.c_str(), match, rowRe);
  33. UNIT_ASSERT_C(isMatch, "log row does not match format: '" << str << '\'');
  34. UNIT_ASSERT_EQUAL_C(match.size(), 10, "expected 10 groups in log row: '" << str << '\'');
  35. TLogRow logRow;
  36. logRow.Time = TInstant::ParseIso8601(match[1].str()) - TDuration::Hours(4);
  37. logRow.Level = ELevelHelpers::FromString(match[2].str());
  38. logRow.ProcName = match[3].str();
  39. logRow.ProcId = FromString<pid_t>(match[4].str());
  40. logRow.ThreadId = match[5].str().substr(0, 2) == "0x" ?
  41. IntFromString<ui64, 16, TStringBuf>(match[5].str().substr(2)) :
  42. IntFromString<ui64, 10, TStringBuf>(match[5].str());
  43. logRow.Component = EComponentHelpers::FromString(match[6].str());
  44. logRow.FileName = match[7].str();
  45. logRow.LineNumber = FromString<ui32>(match[8].str());
  46. logRow.Message = match[9].str();
  47. return logRow;
  48. }
  49. } // namspace NLog
  50. } // namspace NYql