Просмотр исходного кода

fix: remove duplicate timestamps in systemd logs

When running as a systemd service, timestamps were duplicated because
both systemd and the application logger added timestamps. This made
logs harder to read and parse.

Before:
Nov 24 15:41:11 server app[6601]: [2025-11-24T15:41:11.974Z] [INFO] ...
                                  ^^^^^^^^^^^^^^^^^^^^^^^^^ (duplicate)

After:
Nov 24 15:41:11 server app[6601]: [INFO] [WebshopScraper] ...
                                  (systemd timestamp only)

Solution:
- Detect systemd environment by checking INVOCATION_ID env var
- Omit application timestamp when running under systemd
- Keep timestamp for development/manual runs (non-systemd)

Changes:
- Update Logger class to detect systemd environment
- Conditionally format log messages with or without timestamp
- Add documentation explaining the behavior

Benefits:
✓ Cleaner logs in systemd/journalctl
✓ No duplicate timestamps
✓ Easier log parsing
✓ Backward compatible with non-systemd environments

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
Fszontagh 8 месяцев назад
Родитель
Сommit
a88becf94e
1 измененных файлов с 15 добавлено и 1 удалено
  1. 15 1
      src/utils/logger.ts

+ 15 - 1
src/utils/logger.ts

@@ -1,17 +1,31 @@
 /**
  * Simple logger that outputs to stdout and stderr
  * Compatible with systemd/journalctl
+ *
+ * When running under systemd, timestamps are omitted since systemd
+ * adds its own timestamps to avoid duplication.
  */
 export class Logger {
   private prefix: string;
+  private isSystemd: boolean;
 
   constructor(prefix: string = 'WebshopScraper') {
     this.prefix = prefix;
+    // Detect if running under systemd by checking for INVOCATION_ID
+    // This environment variable is set by systemd for each service invocation
+    this.isSystemd = !!process.env.INVOCATION_ID;
   }
 
   private formatMessage(level: string, message: string, ...args: any[]): string {
-    const timestamp = new Date().toISOString();
     const formattedArgs = args.length > 0 ? ' ' + JSON.stringify(args) : '';
+
+    // When running under systemd, omit timestamp as systemd adds its own
+    if (this.isSystemd) {
+      return `[${level}] [${this.prefix}] ${message}${formattedArgs}`;
+    }
+
+    // Include timestamp for non-systemd environments (dev, manual runs)
+    const timestamp = new Date().toISOString();
     return `[${timestamp}] [${level}] [${this.prefix}] ${message}${formattedArgs}`;
   }