Skip to content

Commit

Permalink
[fix] support to create log directory if it doesn't exist for file tr…
Browse files Browse the repository at this point in the history
…ansport (#1556)

* feat: support to create log dir if it doesn't exist for file transport

* test: add test cases
  • Loading branch information
adoyle-h authored and indexzero committed Jan 26, 2019
1 parent b4ced89 commit 0da77d4
Show file tree
Hide file tree
Showing 2 changed files with 53 additions and 0 deletions.
10 changes: 10 additions & 0 deletions lib/winston/transports/file.js
Original file line number Diff line number Diff line change
Expand Up @@ -66,6 +66,7 @@ module.exports = class File extends TransportStream {
console.warn('options.stream will be removed in winston@4. Use winston.transports.Stream');
throwIf('stream', 'filename', 'maxsize');
this._dest = this._stream.pipe(this._setupStream(options.stream));
this.dirname = path.dirname(this._dest.path);
// We need to listen for drain events when write() returns false. This
// can make node mad at times.
} else {
Expand All @@ -88,6 +89,7 @@ module.exports = class File extends TransportStream {
this._opening = false;
this._ending = false;

if (this.dirname) this._createLogDirIfNotExist(this.dirname);
this.open();
}

Expand Down Expand Up @@ -685,4 +687,12 @@ module.exports = class File extends TransportStream {
);
});
}

_createLogDirIfNotExist(dirPath) {
/* eslint-disable no-sync */
if (!fs.existsSync(dirPath)) {
fs.mkdirSync(dirPath, { recursive: true });
}
/* eslint-enable no-sync */
}
};
43 changes: 43 additions & 0 deletions test/transports/file-create-dir-test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
'use strict';

const fs = require('fs');
const assert = require('assert');
const path = require('path');
const winston = require('../../lib/winston');

/* eslint-disable no-sync */

describe('winston/transports/file/createLogDir', function () {
const logDir = path.resolve(__dirname, '../fixtures/temp_logs');

beforeEach(function () {
fs.rmdirSync(logDir);
});

it('should create directory if it does not exist', function () {
winston.createLogger({
transports: [
new winston.transports.File({
filename: path.join(logDir, 'file.log')
})
]
});

assert(fs.existsSync(logDir));
});

it('should create directory if it does not exist when write to the stream', function () {
const streamfile = path.join(logDir, 'simple-stream.log');
const stream = fs.createWriteStream(streamfile);

winston.createLogger({
transports: [
new winston.transports.File({
stream: stream
})
]
});

assert(fs.existsSync(logDir));
});
});

0 comments on commit 0da77d4

Please sign in to comment.