dateFile.js 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. const streams = require('streamroller');
  2. const os = require('os');
  3. const eol = os.EOL;
  4. function openTheStream(filename, pattern, options) {
  5. const stream = new streams.DateRollingFileStream(
  6. filename,
  7. pattern,
  8. options
  9. );
  10. stream.on('error', (err) => {
  11. console.error('log4js.dateFileAppender - Writing to file %s, error happened ', filename, err); //eslint-disable-line
  12. });
  13. stream.on("drain", () => {
  14. process.emit("log4js:pause", false);
  15. });
  16. return stream;
  17. }
  18. /**
  19. * File appender that rolls files according to a date pattern.
  20. * @param filename base filename.
  21. * @param pattern the format that will be added to the end of filename when rolling,
  22. * also used to check when to roll files - defaults to '.yyyy-MM-dd'
  23. * @param layout layout function for log messages - defaults to basicLayout
  24. * @param options - options to be passed to the underlying stream
  25. * @param timezoneOffset - optional timezone offset in minutes (default system local)
  26. */
  27. function appender(
  28. filename,
  29. pattern,
  30. layout,
  31. options,
  32. timezoneOffset
  33. ) {
  34. // the options for file appender use maxLogSize, but the docs say any file appender
  35. // options should work for dateFile as well.
  36. options.maxSize = options.maxLogSize;
  37. const writer = openTheStream(filename, pattern, options);
  38. const app = function (logEvent) {
  39. if (!writer.writable) {
  40. return;
  41. }
  42. if (!writer.write(layout(logEvent, timezoneOffset) + eol, "utf8")) {
  43. process.emit("log4js:pause", true);
  44. }
  45. };
  46. app.shutdown = function (complete) {
  47. writer.end('', 'utf-8', complete);
  48. };
  49. return app;
  50. }
  51. function configure(config, layouts) {
  52. let layout = layouts.basicLayout;
  53. if (config.layout) {
  54. layout = layouts.layout(config.layout.type, config.layout);
  55. }
  56. if (!config.alwaysIncludePattern) {
  57. config.alwaysIncludePattern = false;
  58. }
  59. // security default (instead of relying on streamroller default)
  60. config.mode = config.mode || 0o600;
  61. return appender(
  62. config.filename,
  63. config.pattern,
  64. layout,
  65. config,
  66. config.timezoneOffset
  67. );
  68. }
  69. module.exports.configure = configure;