dateFile.js 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  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. // eslint-disable-next-line no-console
  12. console.error('log4js.dateFileAppender - Writing to file %s, error happened ', filename, err);
  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(
  29. filename,
  30. pattern,
  31. layout,
  32. options,
  33. timezoneOffset
  34. ) {
  35. // the options for file appender use maxLogSize, but the docs say any file appender
  36. // options should work for dateFile as well.
  37. options.maxSize = options.maxLogSize;
  38. const writer = openTheStream(filename, pattern, options);
  39. const app = function (logEvent) {
  40. if (!writer.writable) {
  41. return;
  42. }
  43. if (!writer.write(layout(logEvent, timezoneOffset) + eol, "utf8")) {
  44. process.emit("log4js:pause", true);
  45. }
  46. };
  47. app.shutdown = function (complete) {
  48. writer.end('', 'utf-8', complete);
  49. };
  50. return app;
  51. }
  52. function configure(config, layouts) {
  53. let layout = layouts.basicLayout;
  54. if (config.layout) {
  55. layout = layouts.layout(config.layout.type, config.layout);
  56. }
  57. if (!config.alwaysIncludePattern) {
  58. config.alwaysIncludePattern = false;
  59. }
  60. // security default (instead of relying on streamroller default)
  61. config.mode = config.mode || 0o600;
  62. return appender(
  63. config.filename,
  64. config.pattern,
  65. layout,
  66. config,
  67. config.timezoneOffset
  68. );
  69. }
  70. module.exports.configure = configure;