collect-pm2-error-logs.js 4.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184
  1. #!/usr/bin/env node
  2. import fs from 'node:fs';
  3. import fsp from 'node:fs/promises';
  4. import os from 'node:os';
  5. import path from 'node:path';
  6. import { recordError } from '../src/util/errorLogger.js';
  7. const logDir = process.env.PM2_ERROR_LOG_DIR || path.join(os.homedir(), '.pm2', 'logs');
  8. const stateFile = process.env.PM2_ERROR_LOG_STATE_FILE || path.join(process.cwd(), '.pm2-error-log-cursors.json');
  9. const pollIntervalMs = Number(process.env.PM2_ERROR_LOG_POLL_INTERVAL_MS || 30000);
  10. const readExisting = process.env.PM2_ERROR_LOG_READ_EXISTING === 'true';
  11. const includeLogNames = parseNameList(process.env.PM2_ERROR_LOG_NAMES || 'app-24');
  12. const excludeLogNames = parseNameList(process.env.PM2_ERROR_LOG_EXCLUDE_NAMES || '');
  13. function parseNameList(value) {
  14. return new Set(
  15. String(value || '')
  16. .split(',')
  17. .map((item) => item.trim())
  18. .filter(Boolean)
  19. .flatMap((item) => item.endsWith('-error.log') ? [item] : [item, `${item}-error.log`])
  20. );
  21. }
  22. function shouldCollectLogFile(file) {
  23. if (!file.endsWith('-error.log')) {
  24. return false;
  25. }
  26. if (excludeLogNames.has(file)) {
  27. return false;
  28. }
  29. return includeLogNames.size === 0 || includeLogNames.has(file);
  30. }
  31. async function loadState() {
  32. try {
  33. return JSON.parse(await fsp.readFile(stateFile, 'utf8'));
  34. } catch (error) {
  35. return {};
  36. }
  37. }
  38. async function saveState(state) {
  39. await fsp.writeFile(stateFile, JSON.stringify(state, null, 2));
  40. }
  41. async function listPm2ErrorLogs() {
  42. try {
  43. const files = await fsp.readdir(logDir);
  44. return files
  45. .filter(shouldCollectLogFile)
  46. .map((file) => path.join(logDir, file));
  47. } catch (error) {
  48. console.error(`[pm2-error-log-collector] cannot read log dir ${logDir}:`, error.message || error);
  49. return [];
  50. }
  51. }
  52. async function readRange(filePath, start, end) {
  53. if (end < start) {
  54. return '';
  55. }
  56. let content = '';
  57. const stream = fs.createReadStream(filePath, {
  58. start,
  59. end,
  60. encoding: 'utf8',
  61. });
  62. for await (const chunk of stream) {
  63. content += chunk;
  64. }
  65. return content;
  66. }
  67. function splitErrorBlocks(content) {
  68. const lines = content.replace(/\r\n/g, '\n').split('\n');
  69. const blocks = [];
  70. let current = [];
  71. const startsNewBlock = (line) => {
  72. return (
  73. /^\d{4}-\d{2}-\d{2}[ T]\d{2}:\d{2}:\d{2}/.test(line) ||
  74. /^(Error|TypeError|ReferenceError|SyntaxError|RangeError|UnhandledPromiseRejection|uncaughtException|unhandledRejection)\b/.test(line)
  75. );
  76. };
  77. for (const line of lines) {
  78. if (startsNewBlock(line) && current.length > 0) {
  79. blocks.push(current.join('\n').trim());
  80. current = [];
  81. }
  82. current.push(line);
  83. }
  84. if (current.length > 0) {
  85. blocks.push(current.join('\n').trim());
  86. }
  87. return blocks.filter(Boolean);
  88. }
  89. function getMessageFromBlock(block) {
  90. const line = block
  91. .split('\n')
  92. .map((item) => item.trim())
  93. .find((item) => item && !item.startsWith('at '));
  94. return line
  95. ? line.replace(/^\d{4}-\d{2}-\d{2}[ T]\d{2}:\d{2}:\d{2}(?:\.\d+)?(?:Z|[+-]\d{2}:?\d{2})?\s*/, '')
  96. : 'PM2 error log';
  97. }
  98. function shouldIgnoreBlock(block) {
  99. return (
  100. /ECONNRESET/.test(block) &&
  101. /write ECONNRESET/.test(block) &&
  102. /clb-healthcheck/i.test(block)
  103. );
  104. }
  105. async function collectOnce(state) {
  106. const files = await listPm2ErrorLogs();
  107. for (const filePath of files) {
  108. let stat;
  109. try {
  110. stat = await fsp.stat(filePath);
  111. } catch (error) {
  112. continue;
  113. }
  114. const previousOffset = state[filePath];
  115. if (previousOffset === undefined && !readExisting) {
  116. state[filePath] = stat.size;
  117. continue;
  118. }
  119. const start = Math.min(previousOffset || 0, stat.size);
  120. const content = await readRange(filePath, start, stat.size - 1);
  121. state[filePath] = stat.size;
  122. for (const block of splitErrorBlocks(content)) {
  123. if (shouldIgnoreBlock(block)) {
  124. continue;
  125. }
  126. await recordError(new Error(getMessageFromBlock(block)), null, {
  127. source: 'pm2-log',
  128. stack: block,
  129. message: getMessageFromBlock(block),
  130. extra: { logFile: filePath },
  131. });
  132. }
  133. }
  134. await saveState(state);
  135. }
  136. async function main() {
  137. console.log(`[pm2-error-log-collector] watching ${logDir}`);
  138. console.log(`[pm2-error-log-collector] include logs: ${includeLogNames.size ? [...includeLogNames].join(', ') : 'all'}`);
  139. if (excludeLogNames.size > 0) {
  140. console.log(`[pm2-error-log-collector] exclude logs: ${[...excludeLogNames].join(', ')}`);
  141. }
  142. const state = await loadState();
  143. await collectOnce(state);
  144. setInterval(() => {
  145. collectOnce(state).catch((error) => {
  146. console.error('[pm2-error-log-collector] collect failed:', error);
  147. });
  148. }, pollIntervalMs);
  149. }
  150. main().catch((error) => {
  151. console.error('[pm2-error-log-collector] fatal:', error);
  152. process.exit(1);
  153. });