winston.ts 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. import appRoot from "app-root-path";
  2. import winston from "winston";
  3. import DailyRotateFile from "winston-daily-rotate-file";
  4. const { combine, colorize, printf, timestamp } = winston.format;
  5. const logFormat = printf(info => {
  6. return `[${info.timestamp}] ${info.level}: ${info.message}`;
  7. });
  8. const rawFormat = printf(info => {
  9. return `[${info.timestamp}] ${info.level}: ${info.message}`;
  10. });
  11. // define the custom settings for each transport (file, console)
  12. const options = {
  13. file: {
  14. level: "info",
  15. filename: `${appRoot}/logs/%DATE%_app.log`,
  16. datePattern: "YYYY-MM-DD",
  17. handleExceptions: true,
  18. json: true,
  19. maxsize: 5242880, // 5MB
  20. maxFiles: "30d", // monthly rotation
  21. colorize: false
  22. },
  23. errorFile: {
  24. level: "error",
  25. name: "file.error",
  26. filename: `${appRoot}/logs/%DATE%_error.log`,
  27. datePattern: "YYYY-MM-DD",
  28. handleExceptions: true,
  29. json: true,
  30. maxsize: 5242880, // 5MB
  31. maxFiles: "30d", // monthly rotation
  32. colorize: true
  33. },
  34. console: {
  35. level: "debug",
  36. handleExceptions: true,
  37. json: false,
  38. format: combine(colorize(), rawFormat)
  39. }
  40. };
  41. // instantiate a new Winston Logger with the settings defined above
  42. export const logger = winston.createLogger({
  43. format: combine(timestamp({ format: "YYYY-MM-DD HH:mm:ss" }), logFormat),
  44. transports: [
  45. new DailyRotateFile(options.file),
  46. new DailyRotateFile(options.errorFile),
  47. new winston.transports.Console(options.console)
  48. ],
  49. exitOnError: false // do not exit on handled exceptions
  50. });
  51. // create a stream object with a 'write' function that will be used by `morgan`
  52. export const stream = {
  53. write: message => {
  54. logger.info(message);
  55. }
  56. };
  57. winston.addColors({
  58. debug: "white",
  59. error: "red",
  60. info: "green",
  61. warn: "yellow"
  62. });