aboutsummaryrefslogtreecommitdiff
path: root/services/docker/mail-server/aws-sendmail/logger.ts
blob: 3a0cff6a68ca99bda4b574707a098d252c5e556a (plain)
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
60
61
62
import * as path from "@std/path";
import { generateTimeStringForFileName } from "./base.ts";



export class Logger {
  constructor(public readonly path: string) {}

  warn(message: string) {
    console.log(message);
  }

  generateLogFilePath(
    prefix: string = "",
    suffix: string = "",
    instant?: Temporal.Instant | Date,
  ): string {
    return path.join(
      this.path,
      `${prefix}-${generateTimeStringForFileName(instant)}-${suffix}`,
    );
  }

  openLogFile(
    prefix: string = "",
    suffix: string = "",
    instant?: Temporal.Instant | Date,
  ): Promise<Deno.FsFile> {
    const logPath = this.generateLogFilePath(prefix, suffix, instant);
    return Deno.open(logPath, {
      read: false,
      write: true,
      append: true,
      create: true,
    });
  }

  async logProgramOutput(
    process: Deno.ChildProcess,
    program: string,
    instant?: Temporal.Instant | Date,
  ): Promise<void> {
    const stdoutFile = await this.openLogFile(program, "stdout", instant);
    const stderrFile = await this.openLogFile(program, "stderr", instant);

    process.stdout.pipeTo(stdoutFile.writable);
    process.stderr.pipeTo(stderrFile.writable);
  }
}

let _logger: Logger | null = null;

export function getLogger(): Logger {
  if (_logger == null) {
    throw new Error("No logger is set now.");
  }
  return _logger;
}

export function setLogger(logger: Logger | null) {
  _logger = logger;
}