logging.ts 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. import winston from "winston";
  2. import nodemailer from "nodemailer";
  3. import TransportStream from "winston-transport";
  4. import Mail from "nodemailer/lib/mailer";
  5. export const logger = winston.createLogger({
  6. level: "debug",
  7. transports: [
  8. new winston.transports.Console({
  9. handleExceptions: true,
  10. level: "debug",
  11. debugStdout: true,
  12. format: winston.format.combine(
  13. winston.format.splat(),
  14. winston.format.cli()
  15. ),
  16. }),
  17. ]
  18. });
  19. process.on("unhandledRejection", (reason) => {
  20. throw reason;
  21. });
  22. interface LogMessage {
  23. message: string;
  24. }
  25. class EmailTransport extends TransportStream {
  26. private mailer: Mail;
  27. constructor(opts?: TransportStream.TransportStreamOptions) {
  28. super(opts);
  29. this.mailer = nodemailer.createTransport({
  30. host: "smtp.gmail.com",
  31. port: 465,
  32. secure: true,
  33. auth: {
  34. user: process.env.GMAIL_NAME,
  35. pass: process.env.GMAIL_PASSWORD
  36. }
  37. });
  38. }
  39. log(info: LogMessage, next: () => void): void {
  40. setImmediate(() => {
  41. this.emit("logged", info);
  42. });
  43. this.mailer.sendMail({
  44. from: `${process.env.GMAIL_NAME}@gmail.com`,
  45. to: process.env.ERRORS_ADDR,
  46. subject: `Error at ${new Date().toISOString()}`,
  47. text: `Received error data: ${info.message}`
  48. }).catch(err => console.log(`Failed to send email! ${err}`));
  49. next();
  50. }
  51. }
  52. if (process.env.NODE_ENV == "production") {
  53. logger.add(new EmailTransport({
  54. level: "error",
  55. handleExceptions: true,
  56. format: winston.format.combine(
  57. winston.format.splat(),
  58. winston.format.simple()
  59. )
  60. }));
  61. }