config.ts 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  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. if (timestamp === new Date(timestamp).toISOString())
  30. // eslint-disable-next-line no-param-reassign
  31. timestamp = new Date(timestamp).toLocaleString();
  32. } catch (error) {
  33. // eslint-disable-next-line no-empty
  34. }
  35. const color =
  36. nestLikeColorScheme[level] || ((text: string): string => text);
  37. const stringifiedMeta = JSON.stringify(meta);
  38. const formattedMeta = options?.prettyPrint
  39. ? inspect(JSON.parse(stringifiedMeta), { colors: true, depth: null })
  40. : stringifiedMeta;
  41. return (
  42. `${color(`[${appName}]`)} ` + // eslint-disable-line prefer-template
  43. `${clc.yellow(level.charAt(0).toUpperCase() + level.slice(1))}\t` + // eslint-disable-line prefer-template
  44. (typeof timestamp !== 'undefined' ? `${timestamp} ` : '') + // eslint-disable-line prefer-template
  45. (typeof context !== 'undefined' // eslint-disable-line prefer-template
  46. ? `${clc.yellow('[' + context + ']')} ` // eslint-disable-line prefer-template
  47. : '') + // eslint-disable-line prefer-template
  48. `${color(message)}` + // eslint-disable-line prefer-template
  49. (formattedMeta && formattedMeta !== '{}' ? ` - ${formattedMeta}` : '') + // eslint-disable-line prefer-template
  50. (typeof ms !== 'undefined' ? ` ${clc.yellow(ms)}` : '') // eslint-disable-line prefer-template
  51. );
  52. },
  53. );
  54. }