Skip to content

Commit 0da77d4

Browse files
adoyle-hindexzero
authored andcommitted
[fix] support to create log directory if it doesn't exist for file transport (#1556)
* feat: support to create log dir if it doesn't exist for file transport * test: add test cases
1 parent b4ced89 commit 0da77d4

File tree

2 files changed

+53
-0
lines changed

2 files changed

+53
-0
lines changed

lib/winston/transports/file.js

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -66,6 +66,7 @@ module.exports = class File extends TransportStream {
6666
console.warn('options.stream will be removed in winston@4. Use winston.transports.Stream');
6767
throwIf('stream', 'filename', 'maxsize');
6868
this._dest = this._stream.pipe(this._setupStream(options.stream));
69+
this.dirname = path.dirname(this._dest.path);
6970
// We need to listen for drain events when write() returns false. This
7071
// can make node mad at times.
7172
} else {
@@ -88,6 +89,7 @@ module.exports = class File extends TransportStream {
8889
this._opening = false;
8990
this._ending = false;
9091

92+
if (this.dirname) this._createLogDirIfNotExist(this.dirname);
9193
this.open();
9294
}
9395

@@ -685,4 +687,12 @@ module.exports = class File extends TransportStream {
685687
);
686688
});
687689
}
690+
691+
_createLogDirIfNotExist(dirPath) {
692+
/* eslint-disable no-sync */
693+
if (!fs.existsSync(dirPath)) {
694+
fs.mkdirSync(dirPath, { recursive: true });
695+
}
696+
/* eslint-enable no-sync */
697+
}
688698
};
Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
'use strict';
2+
3+
const fs = require('fs');
4+
const assert = require('assert');
5+
const path = require('path');
6+
const winston = require('../../lib/winston');
7+
8+
/* eslint-disable no-sync */
9+
10+
describe('winston/transports/file/createLogDir', function () {
11+
const logDir = path.resolve(__dirname, '../fixtures/temp_logs');
12+
13+
beforeEach(function () {
14+
fs.rmdirSync(logDir);
15+
});
16+
17+
it('should create directory if it does not exist', function () {
18+
winston.createLogger({
19+
transports: [
20+
new winston.transports.File({
21+
filename: path.join(logDir, 'file.log')
22+
})
23+
]
24+
});
25+
26+
assert(fs.existsSync(logDir));
27+
});
28+
29+
it('should create directory if it does not exist when write to the stream', function () {
30+
const streamfile = path.join(logDir, 'simple-stream.log');
31+
const stream = fs.createWriteStream(streamfile);
32+
33+
winston.createLogger({
34+
transports: [
35+
new winston.transports.File({
36+
stream: stream
37+
})
38+
]
39+
});
40+
41+
assert(fs.existsSync(logDir));
42+
});
43+
});

0 commit comments

Comments
 (0)