summaryrefslogtreecommitdiff
path: root/packages/shared/log.ts
blob: 12baabc5ff2cbaeb94d9dcd4c92fb2c763d6461a (plain) (blame)
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
63
64
65
66
67
68
69
70
71
72
/* eslint-disable no-unused-vars */

export enum LogLevel {
  Error = "ERROR",
  Warning = "WARNING",
  Info = "INFO",
  Debug = "DEBUG",
  Trace = "TRACE",
}

const extractUnitFromStack = (stackOffset: number = 2): string | undefined => {
  const callingLine = new Error().stack?.split("\n")[stackOffset]?.trim();
  return (
    callingLine
      ?.match(/packages\/(.*?):\d+/)?.[1]
      ?.replace(/\//g, "::")
      ?.replace(/::src::/, "::")
      ?.replace(/\.ts$/, "") +
    "::" +
    callingLine?.match(/:(\d+):/)?.[1]
  );
};

const createLogWrapper = (
  messageTemplate: (error: unknown) => string,
  level: LogLevel,
  stackOffset: number = 2,
) => {
  return (error: unknown) => {
    const unit = extractUnitFromStack(stackOffset + 2);
    log(messageTemplate(error), level, unit);
  };
};

export const log = (
  message: string,
  level: LogLevel = LogLevel.Info,
  customUnit?: string,
) => {
  const timestamp = new Date().toISOString();
  const levelColors = {
    [LogLevel.Error]: "\x1b[31m",
    [LogLevel.Warning]: "\x1b[33m",
    [LogLevel.Info]: "\x1b[32m",
    [LogLevel.Debug]: "\x1b[34m",
    [LogLevel.Trace]: "\x1b[35m",
  };
  const levelColor = levelColors[level];
  const unit = customUnit ?? extractUnitFromStack(3);

  console.log(
    `\x1b[37m${timestamp}\x1b[0m ${levelColor}${level}\x1b[0m \x1b[1m${unit}\x1b[22m \x1b[37m> ${message}\x1b[0m`,
  );
};

export const logUnexpectedDiscordAPIError = createLogWrapper(
  (error: unknown) =>
    `Unexpected Discord API error: ${error instanceof Error ? error.message : String(error)}`,
  LogLevel.Error,
);

export const logUnexpectedDiscordAPIResult = createLogWrapper(
  (error: unknown) =>
    `Unexpected Discord API result: ${error instanceof Error ? error.message : String(error)}`,
  LogLevel.Error,
);

export const logUnexpectedAIError = createLogWrapper(
  (error: unknown) =>
    `Unexpected AI error: ${error instanceof Error ? error.message : String(error)}`,
  LogLevel.Error,
);