File tree Expand file tree Collapse file tree 2 files changed +53
-0
lines changed Expand file tree Collapse file tree 2 files changed +53
-0
lines changed Original file line number Diff line number Diff line change @@ -66,6 +66,7 @@ module.exports = class File extends TransportStream {
66
66
console . warn ( 'options.stream will be removed in winston@4. Use winston.transports.Stream' ) ;
67
67
throwIf ( 'stream' , 'filename' , 'maxsize' ) ;
68
68
this . _dest = this . _stream . pipe ( this . _setupStream ( options . stream ) ) ;
69
+ this . dirname = path . dirname ( this . _dest . path ) ;
69
70
// We need to listen for drain events when write() returns false. This
70
71
// can make node mad at times.
71
72
} else {
@@ -88,6 +89,7 @@ module.exports = class File extends TransportStream {
88
89
this . _opening = false ;
89
90
this . _ending = false ;
90
91
92
+ if ( this . dirname ) this . _createLogDirIfNotExist ( this . dirname ) ;
91
93
this . open ( ) ;
92
94
}
93
95
@@ -685,4 +687,12 @@ module.exports = class File extends TransportStream {
685
687
) ;
686
688
} ) ;
687
689
}
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
+ }
688
698
} ;
Original file line number Diff line number Diff line change
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
+ } ) ;
You can’t perform that action at this time.
0 commit comments