@@ -7,6 +7,17 @@ const os = require('os');
7
7
8
8
const eol = os . EOL || '\n' ;
9
9
10
+ function touchFile ( file , options ) {
11
+ // if the file exists, nothing to do
12
+ if ( fs . existsSync ( file ) ) {
13
+ return ;
14
+ }
15
+
16
+ // touch the file to apply flags (like w to truncate the file)
17
+ const id = fs . openSync ( file , options . flags , options . mode ) ;
18
+ fs . closeSync ( id ) ;
19
+ }
20
+
10
21
class RollingFileSync {
11
22
constructor ( filename , size , backups , options ) {
12
23
debug ( 'In RollingFileStream' ) ;
@@ -22,16 +33,17 @@ class RollingFileSync {
22
33
this . filename = filename ;
23
34
this . size = size ;
24
35
this . backups = backups || 1 ;
25
- this . options = options || { encoding : 'utf8' , mode : parseInt ( '0644' , 8 ) , flags : 'a' } ; // eslint-disable-line
36
+ this . options = options ;
26
37
this . currentSize = 0 ;
27
38
28
39
function currentFileSize ( file ) {
29
40
let fileSize = 0 ;
41
+
30
42
try {
31
43
fileSize = fs . statSync ( file ) . size ;
32
44
} catch ( e ) {
33
45
// file does not exist
34
- fs . appendFileSync ( filename , '' ) ;
46
+ touchFile ( file , options ) ;
35
47
}
36
48
return fileSize ;
37
49
}
@@ -130,8 +142,9 @@ class RollingFileSync {
130
142
* has been reached (default 5)
131
143
* @param timezoneOffset - optional timezone offset in minutes
132
144
* (default system local)
145
+ * @param options - passed as is to fs options
133
146
*/
134
- function fileAppender ( file , layout , logSize , numBackups , timezoneOffset ) {
147
+ function fileAppender ( file , layout , logSize , numBackups , timezoneOffset , options ) {
135
148
debug ( 'fileSync appender created' ) ;
136
149
file = path . normalize ( file ) ;
137
150
numBackups = numBackups === undefined ? 5 : numBackups ;
@@ -145,14 +158,13 @@ function fileAppender(file, layout, logSize, numBackups, timezoneOffset) {
145
158
stream = new RollingFileSync (
146
159
filePath ,
147
160
fileSize ,
148
- numFiles
161
+ numFiles ,
162
+ options
149
163
) ;
150
164
} else {
151
165
stream = ( ( ( f ) => {
152
- // create file if it doesn't exist
153
- if ( ! fs . existsSync ( f ) ) {
154
- fs . appendFileSync ( f , '' ) ;
155
- }
166
+ // touch the file to apply flags (like w to truncate the file)
167
+ touchFile ( f , options ) ;
156
168
157
169
return {
158
170
write ( data ) {
@@ -178,12 +190,19 @@ function configure(config, layouts) {
178
190
layout = layouts . layout ( config . layout . type , config . layout ) ;
179
191
}
180
192
193
+ const options = {
194
+ flags : config . flags || 'a' ,
195
+ encoding : config . encoding || 'utf8' ,
196
+ mode : config . mode || 0o644
197
+ } ;
198
+
181
199
return fileAppender (
182
200
config . filename ,
183
201
layout ,
184
202
config . maxLogSize ,
185
203
config . backups ,
186
- config . timezoneOffset
204
+ config . timezoneOffset ,
205
+ options
187
206
) ;
188
207
}
189
208
0 commit comments