dateFile.js 2.1 KB

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