file.js 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. "use strict";
  2. var layouts = require('../layouts')
  3. , path = require('path')
  4. , fs = require('fs')
  5. , streams = require('../streams')
  6. , os = require('os')
  7. , eol = os.EOL || '\n'
  8. , openFiles = [];
  9. //close open files on process exit.
  10. process.on('exit', function() {
  11. openFiles.forEach(function (file) {
  12. file.end();
  13. });
  14. });
  15. /**
  16. * File Appender writing the logs to a text file. Supports rolling of logs by size.
  17. *
  18. * @param file file log messages will be written to
  19. * @param layout a function that takes a logevent and returns a string
  20. * (defaults to basicLayout).
  21. * @param logSize - the maximum size (in bytes) for a log file,
  22. * if not provided then logs won't be rotated.
  23. * @param numBackups - the number of log files to keep after logSize
  24. * has been reached (default 5)
  25. */
  26. function fileAppender (file, layout, logSize, numBackups) {
  27. var bytesWritten = 0;
  28. file = path.normalize(file);
  29. layout = layout || layouts.basicLayout;
  30. numBackups = numBackups === undefined ? 5 : numBackups;
  31. //there has to be at least one backup if logSize has been specified
  32. numBackups = numBackups === 0 ? 1 : numBackups;
  33. function openTheStream(file, fileSize, numFiles) {
  34. var stream;
  35. if (fileSize) {
  36. stream = new streams.RollingFileStream(
  37. file,
  38. fileSize,
  39. numFiles
  40. );
  41. } else {
  42. stream = fs.createWriteStream(
  43. file,
  44. { encoding: "utf8",
  45. mode: parseInt('0644', 8),
  46. flags: 'a' }
  47. );
  48. }
  49. stream.on("error", function (err) {
  50. console.error("log4js.fileAppender - Writing to file %s, error happened ", file, err);
  51. });
  52. return stream;
  53. }
  54. var logFile = openTheStream(file, logSize, numBackups);
  55. // push file to the stack of open handlers
  56. openFiles.push(logFile);
  57. return function(loggingEvent) {
  58. logFile.write(layout(loggingEvent) + eol, "utf8");
  59. };
  60. }
  61. function configure(config, options) {
  62. var layout;
  63. if (config.layout) {
  64. layout = layouts.layout(config.layout.type, config.layout);
  65. }
  66. if (options && options.cwd && !config.absolute) {
  67. config.filename = path.join(options.cwd, config.filename);
  68. }
  69. return fileAppender(config.filename, layout, config.maxLogSize, config.backups);
  70. }
  71. exports.appender = fileAppender;
  72. exports.configure = configure;