log.js 2.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697
  1. /**
  2. * logger api
  3. *
  4. */
  5. // logger config
  6. let path = require('path');
  7. let util = require('util');
  8. let winston = require('winston');
  9. let fs = require('fs');
  10. let config = process.appConfig || {};
  11. let options = require('../config/loggerConfig');
  12. require('winston-daily-rotate-file');
  13. // DEFAULT config
  14. const DEFAULT = {
  15. json: !1,
  16. timestamp: function () {
  17. let time = new Date();
  18. return util.format(
  19. '%s-%s-%s %s:%s:%s.%s',
  20. time.getFullYear(),
  21. String('0' + (time.getMonth() + 1)).slice(-2),
  22. String('0' + time.getDate()).slice(-2),
  23. String('0' + time.getHours()).slice(-2),
  24. String('0' + time.getMinutes()).slice(-2),
  25. String('0' + time.getSeconds()).slice(-2),
  26. String('00' + time.getMilliseconds()).slice(-3)
  27. );
  28. },
  29. formatter: function (options) {
  30. let arr = [util.format(
  31. '[%s] [%s] - %s',
  32. options.level.toUpperCase().charAt(0),
  33. options.timestamp(),
  34. options.message || ''
  35. )];
  36. if (options.meta && Object.keys(options.meta).length > 0) {
  37. arr.push(util.format(
  38. 'meta -> %s',
  39. JSON.stringify(
  40. options.meta, function (key, value) {
  41. if (value === undefined) {
  42. return '__NOT_DEFINED__';
  43. }
  44. return value;
  45. }
  46. ))
  47. );
  48. }
  49. return arr.join('\n');
  50. }
  51. };
  52. let appRoot = config.appRoot || path.join(__dirname, '../');
  53. let logRoot = path.join(appRoot, options.root);
  54. try {
  55. fs.accessSync(logRoot);
  56. } catch (err) {
  57. fs.mkdirSync(logRoot);
  58. }
  59. // export Logger instance
  60. module.exports = new (winston.Logger)({
  61. level: options.level || 'debug',
  62. transports: [
  63. new winston.transports.Console(DEFAULT),
  64. new winston.transports.File(
  65. Object.assign({}, DEFAULT, {
  66. level: 'warn',
  67. filename: path.join(
  68. logRoot,
  69. '/icon.error.log'
  70. )
  71. })
  72. ),
  73. new (winston.transports.DailyRotateFile)(
  74. Object.assign({}, DEFAULT, {
  75. datePattern: '.yyyyMMdd.log',
  76. filename: path.join(
  77. logRoot,
  78. '/icon'
  79. )
  80. })
  81. )
  82. ],
  83. exceptionHandlers: [
  84. new winston.transports.File(
  85. Object.assign({}, DEFAULT, {
  86. filename: path.join(
  87. logRoot,
  88. '/icon.exception.log'
  89. )
  90. })
  91. )
  92. ],
  93. exitOnError: !1
  94. });