file-tailrolling.test.js 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100
  1. var assert = require('assert'),
  2. rimraf = require('rimraf'),
  3. fs = require('fs'),
  4. path = require('path'),
  5. winston = require('../../lib/winston'),
  6. helpers = require('../helpers');
  7. const asyncSeries = require('async/series');
  8. const { MESSAGE, LEVEL } = require('triple-beam');
  9. //
  10. // Remove all log fixtures
  11. //
  12. function removeFixtures(done) {
  13. rimraf(path.join(__dirname, '..', 'fixtures', 'logs', 'testtailrollingfiles*'), done);
  14. }
  15. let tailrollTransport = null;
  16. describe('winston/transports/file/tailrolling', function(){
  17. describe("An instance of the File Transport", function(){
  18. before(removeFixtures);
  19. after(removeFixtures);
  20. it('init logger AFTER cleaning up old files', function(){
  21. tailrollTransport = new winston.transports.File({
  22. timestamp: false,
  23. json: false,
  24. filename: path.join(__dirname, '..', 'fixtures', 'logs', 'testtailrollingfiles.log'),
  25. maxsize: 4096,
  26. maxFiles: 3,
  27. tailable: true
  28. })
  29. .on('open', console.log)
  30. });
  31. it("and when passed more files than the maxFiles", function(done){
  32. let created = 0;
  33. let loggedTotal = 0;
  34. function data(ch, kb) {
  35. return String.fromCharCode(65 + ch).repeat(kb*1024 - 1);
  36. };
  37. function logKbytes(kbytes, txt) {
  38. const toLog = {};
  39. toLog[MESSAGE] = data(txt, kbytes)
  40. tailrollTransport.log(toLog);
  41. }
  42. tailrollTransport.on('logged', function (info) {
  43. loggedTotal += info[MESSAGE].length + 1
  44. if (loggedTotal >= 14*1024) { // just over 3 x 4kb files
  45. return done();
  46. }
  47. if(loggedTotal % 4096 === 0) {
  48. created ++;
  49. }
  50. setTimeout(() => logKbytes(1, created), 100);
  51. });
  52. logKbytes(1, created);
  53. });
  54. it("should be 3 log files, base to maxFiles - 1", function () {
  55. var file, fullpath;
  56. for (var num = 0; num < 4; num++) {
  57. file = !num ? 'testtailrollingfiles.log' : 'testtailrollingfiles' + num + '.log';
  58. fullpath = path.join(__dirname, '..', 'fixtures', 'logs', file);
  59. if (num == 3) {
  60. return assert.ok(!fs.existsSync(fullpath));
  61. }
  62. assert.ok(fs.existsSync(fullpath));
  63. }
  64. return false;
  65. });
  66. it("should have files in correct order", function () {
  67. var file, fullpath, content;
  68. ['D', 'C', 'B'].forEach(function (letter, i) {
  69. file = !i ? 'testtailrollingfiles.log' : 'testtailrollingfiles' + i + '.log';
  70. content = fs.readFileSync(path.join(__dirname, '..', 'fixtures', 'logs', file), 'ascii');
  71. content = content.replace(/\s+/g, '');
  72. assert(content.match(new RegExp(letter, 'g'))[0].length, content.length);
  73. });
  74. });
  75. })
  76. })