File size: 1,250 Bytes
4327358
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
import { Job } from 'bullmq';
import { Logger } from 'pino';

import { ILogger } from './ILogger';

/**
 * JobLoggerWrapper is a wrapper around the BullMQ Job class that provides
 * a logger with the job ID as a child context.
 * It allows logging messages to the job's log
 * and also to the logger itself.
 */
export class JobLoggerWrapper implements ILogger {
  private readonly logger: Logger;

  constructor(
    private job: Job,
    logger: Logger,
  ) {
    this.logger = logger.child({ jobId: job.id });
  }

  fatal(log: string): void {
    this.log(log, 'fatal');
  }

  error(log: string): void {
    this.log(log, 'error');
  }

  warn(log: string): void {
    this.log(log, 'warn');
  }

  info(log: string): void {
    this.log(log, 'info');
  }

  debug(log: string): void {
    this.log(log, 'debug');
  }

  trace(log: string): void {
    this.log(log, 'trace');
  }

  private log(msg: string, level: string) {
    if (!this.logger.isLevelEnabled(level)) {
      return;
    }
    this.logger[level](msg);
    const timestamp = new Date().toISOString();
    this.job
      .log(`[${timestamp}] ${level.toUpperCase()}: ${msg}`)
      .catch((err) => {
        this.logger.error('Error logging message to job', err);
      });
  }
}