config.ts 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. import * as clc from 'chalk';
  2. import { Format as LogFormat } from 'logform';
  3. import { inspect } from 'util';
  4. import { NestLikeConsoleFormatOptions } from 'nest-winston/dist/winston.interfaces';
  5. import { format } from 'winston';
  6. const nestLikeColorScheme = {
  7. info: clc.greenBright,
  8. error: clc.red,
  9. warn: clc.yellow,
  10. debug: clc.magentaBright,
  11. verbose: clc.cyanBright,
  12. };
  13. /**
  14. * NestLikeConsoleFormat
  15. * {@link https://github.com/gremo/nest-winston/blob/master/winston.utilities.ts}
  16. * @param appName AppName
  17. * @param options Options
  18. */
  19. export function nestLikeConsoleFormat(
  20. appName = 'NestWinston',
  21. options?: NestLikeConsoleFormatOptions,
  22. ): LogFormat {
  23. return format.printf(
  24. ({ context, level, timestamp, message, ms, ...meta }) => {
  25. if (typeof timestamp !== 'undefined')
  26. // Only format the timestamp to a locale representation if it's ISO 8601 format. Any format
  27. // That is not a valid date string will throw, just ignore it (it will be printed as-is).
  28. try {
  29. //@ts-ignore
  30. if (timestamp === new Date(timestamp).toISOString())
  31. // eslint-disable-next-line no-param-reassign
  32. timestamp = new Date(timestamp).toLocaleString();
  33. } catch (error) {
  34. // eslint-disable-next-line no-empty
  35. }
  36. const color =
  37. nestLikeColorScheme[level] || ((text: string): string => text);
  38. const stringifiedMeta = JSON.stringify(meta);
  39. const formattedMeta = options?.prettyPrint
  40. ? inspect(JSON.parse(stringifiedMeta), { colors: true, depth: null })
  41. : stringifiedMeta;
  42. return (
  43. `${color(`[${appName}]`)} ` + // eslint-disable-line prefer-template
  44. `${clc.yellow(level.charAt(0).toUpperCase() + level.slice(1))}\t` + // eslint-disable-line prefer-template
  45. (typeof timestamp !== 'undefined' ? `${timestamp} ` : '') + // eslint-disable-line prefer-template
  46. (typeof context !== 'undefined' // eslint-disable-line prefer-template
  47. ? `${clc.yellow('[' + context + ']')} ` // eslint-disable-line prefer-template
  48. : '') + // eslint-disable-line prefer-template
  49. `${color(message)}` + // eslint-disable-line prefer-template
  50. (formattedMeta && formattedMeta !== '{}' ? ` - ${formattedMeta}` : '') + // eslint-disable-line prefer-template
  51. (typeof ms !== 'undefined' ? ` ${clc.yellow(ms)}` : '') // eslint-disable-line prefer-template
  52. );
  53. },
  54. );
  55. }