logging.ts 2.2 KB

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