All files / src Logger.ts

0% Statements 0/32
0% Branches 0/10
0% Functions 0/5
0% Lines 0/31

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106                                                                                                                                                                                                                   
import bunyan, { LogLevelString, levelFromName } from "bunyan";
import { CommonEnv } from "./Env";
import Logger from "bunyan";
import BunyanSlack from "bunyan-slack";
 
const LogLevelStrings = ["trace", "debug", "info", "warn", "error", "fatal"];
 
export function isLogLevelString(s: string): s is LogLevelString {
  return LogLevelStrings.some((v) => v === s);
}
 
export function toLogLevel(s: string): number {
  Iif (isLogLevelString(s)) {
    return levelFromName[s];
  }
  throw new Error(`cannot convert to log level, string[${s}] is not supported`);
}
 
export function createLogger(env: CommonEnv): Logger {
  return bunyan.createLogger({
    name: env.appName,
    streams: [
      {
        stream: process.stdout,
      },
      {
        type: "raw",
        stream: new BunyanSlack({
          webhookUrl: env.slackWebhookUrl,
          customFormatter: formatSlack,
        }),
        level: env.slackLogLevel,
      },
    ],
    level: env.logLevel,
  });
}
 
type LogRecord = {
  msg: string;
  name?: string;
  err?: Error;
};
 
type SlackMessage = {
  attachments: any[];
};
 
function formatSlack(
  record: LogRecord,
  levelName: LogLevelString
): SlackMessage {
  let color: string = "";
  switch (levelName) {
    case "trace":
    case "debug":
      color = "#F4FBFE";
      break;
    case "info":
      color = "#36a64f";
      break;
    case "warn":
      color = "#ffd900";
      break;
    case "error":
      color = "#ff0000";
      break;
    case "fatal":
      color = "#000000";
      break;
  }
 
  const fields = [];
  Iif (record.name) {
    fields.push({
      title: "name",
      value: record.name,
      short: true,
    });
  }
  Iif (levelName) {
    fields.push({
      title: "level",
      value: String(levelName),
      short: true,
    });
  }
  Iif (record.err?.stack) {
    fields.push({
      title: "stack trace",
      value: record.err.stack,
      short: false,
    });
  }
 
  return {
    attachments: [
      {
        text: record.msg,
        color: color,
        fields: fields,
      },
    ],
  };
}