# All files / lib/winston/transports file.js

53.25% Statements 131/246
45.52% Branches 66/145
63.04% Functions 29/46
53.33% Lines 128/240

Press n or j to go to the next uncovered block, b, p or k for the previous block.

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    92
    93
    94
    95
    96
    97
    98
    99
    100
    101
    102
    103
    104
    105
    106
    107
    108
    109
    110
    111
    112
    113
    114
    115
    116
    117
    118
    119
    120
    121
    122
    123
    124
    125
    126
    127
    128
    129
    130
    131
    132
    133
    134
    135
    136
    137
    138
    139
    140
    141
    142
    143
    144
    145
    146
    147
    148
    149
    150
    151
    152
    153
    154
    155
    156
    157
    158
    159
    160
    161
    162
    163
    164
    165
    166
    167
    168
    169
    170
    171
    172
    173
    174
    175
    176
    177
    178
    179
    180
    181
    182
    183
    184
    185
    186
    187
    188
    189
    190
    191
    192
    193
    194
    195
    196
    197
    198
    199
    200
    201
    202
    203
    204
    205
    206
    207
    208
    209
    210
    211
    212
    213
    214
    215
    216
    217
    218
    219
    220
    221
    222
    223
    224
    225
    226
    227
    228
    229
    230
    231
    232
    233
    234
    235
    236
    237
    238
    239
    240
    241
    242
    243
    244
    245
    246
    247
    248
    249
    250
    251
    252
    253
    254
    255
    256
    257
    258
    259
    260
    261
    262
    263
    264
    265
    266
    267
    268
    269
    270
    271
    272
    273
    274
    275
    276
    277
    278
    279
    280
    281
    282
    283
    284
    285
    286
    287
    288
    289
    290
    291
    292
    293
    294
    295
    296
    297
    298
    299
    300
    301
    302
    303
    304
    305
    306
    307
    308
    309
    310
    311
    312
    313
    314
    315
    316
    317
    318
    319
    320
    321
    322
    323
    324
    325
    326
    327
    328
    329
    330
    331
    332
    333
    334
    335
    336
    337
    338
    339
    340
    341
    342
    343
    344
    345
    346
    347
    348
    349
    350
    351
    352
    353
    354
    355
    356
    357
    358
    359
    360
    361
    362
    363
    364
    365
    366
    367
    368
    369
    370
    371
    372
    373
    374
    375
    376
    377
    378
    379
    380
    381
    382
    383
    384
    385
    386
    387
    388
    389
    390
    391
    392
    393
    394
    395
    396
    397
    398
    399
    400
    401
    402
    403
    404
    405
    406
    407
    408
    409
    410
    411
    412
    413
    414
    415
    416
    417
    418
    419
    420
    421
    422
    423
    424
    425
    426
    427
    428
    429
    430
    431
    432
    433
    434
    435
    436
    437
    438
    439
    440
    441
    442
    443
    444
    445
    446
    447
    448
    449
    450
    451
    452
    453
    454
    455
    456
    457
    458
    459
    460
    461
    462
    463
    464
    465
    466
    467
    468
    469
    470
    471
    472
    473
    474
    475
    476
    477
    478
    479
    480
    481
    482
    483
    484
    485
    486
    487
    488
    489
    490
    491
    492
    493
    494
    495
    496
    497
    498
    499
    500
    501
    502
    503
    504
    505
    506
    507
    508
    509
    510
    511
    512
    513
    514
    515
    516
    517
    518
    519
    520
    521
    522
    523
    524
    525
    526
    527
    528
    529
    530
    531
    532
    533
    534
    535
    536
    537
    538
    539
    540
    541
    542
    543
    544
    545
    546
    547
    548
    549
    550
    551
    552
    553
    554
    555
    556
    557
    558
    559
    560
    561
    562
    563
    564
    565
    566
    567
    568
    569
    570
    571
    572
    573
    574
    575
    576
    577
    578
    579
    580
    581
    582
    583
    584
    585
    586
    587
    588
    589
    590
    591
    592
    593
    594
    595
    596
    597
    598
    599
    600
    601
    602
    603
    604
    605
    606
    607
    608
    609
    610
    611
    612
    613
    614
    615
    616
    617
    618
    619
    620
    621
    622
    623
    624

    6x
    6x
    6x
    6x
    6x
    6x
    6x
    6x
    6x
    6x

    6x

    22x

    22x

    22x
    1x

    22x
    22x

    22x

    22x
    21x
    21x

    21x
    21x
    1x

    1x
    1x
    1x

    22x
    22x
    22x
    22x
    22x
    22x

    22x
    22x
    22x
    22x
    22x

    22x

    14856x

    14856x
    8x
    8x
    8x

    8x

    14848x
    14848x

    14848x
    14848x

    14848x
    14848x

    14845x
    3x

    14842x
    14837x

    5x

    14848x
    14848x

    14848x
    14848x
    7242x
    7242x
    7242x
    7242x

    7606x

    14848x

    14848x

    27x
    26x

    26x

    26x
    25x

    25x
    25x
    25x
    25x

    26x
    26x

    26x
    25x
    14x

    14x
    14x

    11x

    11x

    11x
    11x

    4x

    4x
    4x

    4x
    4x

    14857x
    14857x

    1x

    1x

    5x

    5x

    5x

    5x
    5x
    5x
    5x

    25x

    25x
    25x

    1x
    9x

    24x
    24x
    24x

    24x

    25x
    25x

    25x

    5x
    5x
    5x

    5x
    5x
    5x

    26x
    26x
    26x

    26x

    26x

    5x
    5x

     /**
     * file.js: Transport for outputting to a local log file.
     *
     * (C) 2010 Charlie Robbins
     * MIT LICENCE
     */

    'use strict';

    const fs = require('fs');
    const path = require('path');
    const asyncSeries = require('async/series');
    const zlib = require('zlib');
    const { MESSAGE } = require('triple-beam');
    const { Stream, PassThrough } = require('readable-stream');
    const TransportStream = require('winston-transport');
    const debug = require('diagnostics')('winston:file');
    const os = require('os');
    const tailFile = require('../tail-file');

    /**
     * Transport for outputting to a local log file.
     * @type {File}
     * @extends {TransportStream}
     */
    module.exports = class File extends TransportStream {
      /**
       * Constructor function for the File transport object responsible for
       * persisting log messages and metadata to one or more files.
       * @param {Object} options - Options for this instance.
       */
      constructor(options = {}) {
        super(options);

        // Expose the name of this Transport on the prototype.
        this.name = 'file';

        // Helper function which throws an `Error` in the event that any of the
        // rest of the arguments is present in `options`.
        function throwIf(target, ...args) {
          args.slice(1).forEach(name => {
            Iif (options[name]) {
              throw new Error(`Cannot set ${name} and ${target} together`);
            }
          });
        }

        // Setup the base stream that always gets piped to to handle buffering.
        this._stream = new PassThrough();
        this._stream.setMaxListeners(30);

        // Bind this context for listener methods.
        this._onError = this._onError.bind(this);

        if (options.filename || options.dirname) {
          throwIf('filename or dirname', 'stream');
          this._basename = this.filename = options.filename
            ? path.basename(options.filename)
            : 'winston.log';

          this.dirname = options.dirname || path.dirname(options.filename);
          this.options = options.options || { flags: 'a' };
        } else Eif (options.stream) {
          // eslint-disable-next-line no-console
          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));
          // We need to listen for drain events when write() returns false. This
          // can make node mad at times.
        } else {
          throw new Error('Cannot log to file without filename or stream.');
        }

        this.maxsize = options.maxsize || null;
        this.rotationFormat = options.rotationFormat || false;
        this.zippedArchive = options.zippedArchive || false;
        this.maxFiles = options.maxFiles || null;
        this.eol = options.eol || os.EOL;
        this.tailable = options.tailable || false;

        // Internal state variables representing the number of files this instance
        // has created and the current size (in bytes) of the current logfile.
        this._size = 0;
        this._pendingSize = 0;
        this._created = 0;
        this._drain = false;
        this._opening = false;

        this.open();
      }

      /**
       * Core logging method exposed to Winston. Metadata is optional.
       * @param {Object} info - TODO: add param description.
       * @param {Function} callback - TODO: add param description.
       * @returns {undefined}
       */
      log(info, callback = () => {}) {
        // Remark: (jcrugzz) What is necessary about this callback(null, true) now
        // when thinking about 3.x? Should silent be handled in the base
        // TransportStream _write method?
        Iif (this.silent) {
          callback();
          return true;
        }

        // Output stream buffer is full and has asked us to wait for the drain event
        if (this._drain) {
          this._stream.once('drain', () => {
            this._drain = false;
            this.log(info, callback);
          });
          return;
        }

        // Grab the raw string and append the expected EOL.
        const output = `${info[MESSAGE]}${this.eol}`;
        const bytes = Buffer.byteLength(output);

        // After we have written to the PassThrough check to see if we need
        // to rotate to the next file.
        //
        // Remark: This gets called too early and does not depict when data
        // has been actually flushed to disk.
        function logged() {
          this._size += bytes;
          this._pendingSize -= bytes;

          debug('logged %s %s', this._size, output);
          this.emit('logged', info);

          // Do not attempt to rotate files while opening
          if (this._opening) {
            return;
          }

          // Check to see if we need to end the stream and create a new one.
          if (!this._needsNewFile()) {
            return;
          }

          // End the current stream, ensure it flushes and create a new one.
          // This could potentially be optimized to not run a stat call but its
          // the safest way since we are supporting `maxFiles`.
          this._endStream(() => this._rotateFile());
        }

        // Keep track of the pending bytes being written while files are opening
        // in order to properly rotate the PassThrough this._stream when the file
        // eventually does open.
        this._pendingSize += bytes;
        Iif (this._opening
          && !this.rotatedWhileOpening
          && this._needsNewFile(this._size + this._pendingSize)) {
          this.rotatedWhileOpening = true;
        }

        const written = this._stream.write(output, logged.bind(this));
        if (!written) {
          this._drain = true;
          this._stream.once('drain', () => {
            this._drain = false;
            callback();
          });
        } else {
          callback(); // eslint-disable-line callback-return
        }

        debug('written', written, this._drain);

        return written;
      }

      /**
       * Query the transport. Options object is optional.
       * @param {Object} options - Loggly-like query options for this instance.
       * @param {function} callback - Continuation to respond to when complete.
       * TODO: Refactor me.
       */
      query(options, callback) {
        if (typeof options === 'function') {
          callback = options;
          options = {};
        }

        options = this.normalizeQuery(options);
        const file = path.join(this.dirname, this.filename);
        let buff = '';
        let results = [];
        let row = 0;

        const stream = fs.createReadStream(file, {
          encoding: 'utf8'
        });

        stream.on('error', err => {
          if (stream.readable) {
            stream.destroy();
          }
          if (!callback) {
            return;
          }

          return err.code !== 'ENOENT' ? callback(err) : callback(null, results);
        });

        stream.on('data', data => {
          data = (buff + data).split(/\n+/);
          const l = data.length - 1;
          let i = 0;

          for (; i < l; i++) {
            if (!options.start || row >= options.start) {
              add(data[i]);
            }
            row++;
          }

          buff = data[l];
        });

        stream.on('close', () => {
          if (buff) {
            add(buff, true);
          }
          if (options.order === 'desc') {
            results = results.reverse();
          }

          // eslint-disable-next-line callback-return
          if (callback) callback(null, results);
        });

        function add(buff, attempt) {
          try {
            const log = JSON.parse(buff);
            if (check(log)) {
              push(log);
            }
          } catch (e) {
            if (!attempt) {
              stream.emit('error', e);
            }
          }
        }

        function push(log) {
          if (
            options.rows &&
            results.length >= options.rows &&
            options.order !== 'desc'
          ) {
            if (stream.readable) {
              stream.destroy();
            }
            return;
          }

          if (options.fields) {
            log = options.fields.reduce((obj, key) => {
              obj[key] = log[key];
              return obj;
            }, {});
          }

          if (options.order === 'desc') {
            if (results.length >= options.rows) {
              results.shift();
            }
          }
          results.push(log);
        }

        function check(log) {
          if (!log) {
            return;
          }

          if (typeof log !== 'object') {
            return;
          }

          const time = new Date(log.timestamp);
          if (
            (options.from && time < options.from) ||
            (options.until && time > options.until) ||
            (options.level && options.level !== log.level)
          ) {
            return;
          }

          return true;
        }
      }

      /**
       * Returns a log stream for this transport. Options object is optional.
       * @param {Object} options - Stream options for this instance.
       * @returns {Stream} - TODO: add return description.
       * TODO: Refactor me.
       */
      stream(options = {}) {
        const file = path.join(this.dirname, this.filename);
        const stream = new Stream();
        const tail = {
          file,
          start: options.start
        };

        stream.destroy = tailFile(tail, (err, line) => {
          if (err) {
            return stream.emit('error', err);
          }

          try {
            stream.emit('data', line);
            line = JSON.parse(line);
            stream.emit('log', line);
          } catch (e) {
            stream.emit('error', e);
          }
        });

        return stream;
      }

      /**
       * Checks to see the filesize of.
       * @returns {undefined}
       */
      open() {
        // If we do not have a filename then we were passed a stream and
        // don't need to keep track of size.
        if (!this.filename) return;
        Iif (this._opening) return;

        this._opening = true;

        // Stat the target file to get the size and create the stream.
        this.stat((err, size) => {
          Iif (err) {
            return this.emit('error', err);
          }

          debug('stat done: %s { size: %s }', this.filename, size);
          this._size = size;
          this._dest = this._createStream(this._stream);
          this._opening = false;
        });
      }

      /**
       * Stat the file and assess information in order to create the proper stream.
       * @param {function} callback - TODO: add param description.
       * @returns {undefined}
       */
      stat(callback) {
        const target = this._getFile();
        const fullpath = path.join(this.dirname, target);

        fs.stat(fullpath, (err, stat) => {
          if (err && err.code === 'ENOENT') {
            debug('ENOENT ok', fullpath);
            // Update internally tracked filename with the new target name.
            this.filename = target;
            return callback(null, 0);
          }

          Iif (err) {
            debug(`err ${err.code} ${fullpath}`);
            return callback(err);
          }

          Iif (!stat || this._needsNewFile(stat.size)) {
            // If `stats.size` is greater than the `maxsize` for this
            // instance then try again.
            return this._incFile(() => this.stat(callback));
          }

          // Once we have figured out what the filename is, set it
          // and return the size.
          this.filename = target;
          callback(null, stat.size);
        });
      }

      /**
       * Closes the stream associated with this instance.
       * @param {function} cb - TODO: add param description.
       * @returns {undefined}
       */
      close(cb) {
        Iif (!this._stream) {
          return;
        }

        this._stream.end(() => {
          Iif (cb) {
            cb(); // eslint-disable-line callback-return
          }
          this.emit('flush');
          this.emit('closed');
        });
      }

      /**
       * TODO: add method description.
       * @param {number} size - TODO: add param description.
       * @returns {undefined}
       */
      _needsNewFile(size) {
        size = size || this._size;
        return this.maxsize && size >= this.maxsize;
      }

      /**
       * TODO: add method description.
       * @param {Error} err - TODO: add param description.
       * @returns {undefined}
       */
      _onError(err) {
        this.emit('error', err);
      }

      /**
       * TODO: add method description.
       * @param {Stream} stream - TODO: add param description.
       * @returns {mixed} - TODO: add return description.
       */
      _setupStream(stream) {
        stream.on('error', this._onError);

        return stream;
      }

      /**
       * TODO: add method description.
       * @param {Stream} stream - TODO: add param description.
       * @returns {mixed} - TODO: add return description.
       */
      _cleanupStream(stream) {
        stream.removeListener('error', this._onError);

        return stream;
      }

      /**
       * TODO: add method description.
       */
      _rotateFile() {
        this._incFile(() => this.open());
      }

      /**
       * Unpipe from the stream that has been marked as full and end it so it
       * flushes to disk.
       *
       * @param {function} callback - Callback for when the current file has closed.
       * @private
       */
      _endStream(callback) {
        this._stream.unpipe(this._dest);
        this._dest.end(() => {
          this._cleanupStream(this._dest);
          callback();
        });
      }

      /**
       * Returns the WritableStream for the active file on this instance. If we
       * should gzip the file then a zlib stream is returned.
       *
       * @param {ReadableStream} source – PassThrough to pipe to the file when open.
       * @returns {WritableStream} Stream that writes to disk for the active file.
       */
      _createStream(source) {
        const fullpath = path.join(this.dirname, this.filename);

        debug('create stream start', fullpath, this.options);
        const dest = fs.createWriteStream(fullpath, this.options)
          // TODO: What should we do with errors here?
          .on('error', err => debug(err))
          .on('close', () => debug('close', dest.path, dest.bytesWritten))
          .on('open', () => {
            debug('file open ok', fullpath);
            this.emit('open', fullpath);
            source.pipe(dest);

            // If rotation occured during the open operation then we immediately
            // start writing to a new PassThrough, begin opening the next file
            // and cleanup the previous source and dest once the source has drained.
            Iif (this.rotatedWhileOpening) {
              this._stream = new PassThrough();
              this._stream.setMaxListeners(30);
              this._rotateFile();
              this.rotatedWhileOpening = false;
              this._cleanupStream(dest);
              source.end();
            }
          });

        debug('create stream ok', fullpath);
        Iif (this.zippedArchive) {
          const gzip = zlib.createGzip();
          gzip.pipe(dest);
          return gzip;
        }

        return dest;
      }

      /**
       * TODO: add method description.
       * @param {function} callback - TODO: add param description.
       * @returns {undefined}
       */
      _incFile(callback) {
        debug('_incFile', this.filename);
        const ext = path.extname(this._basename);
        const basename = path.basename(this._basename, ext);

        Eif (!this.tailable) {
          this._created += 1;
          this._checkMaxFilesIncrementing(ext, basename, callback);
        } else {
          this._checkMaxFilesTailable(ext, basename, callback);
        }
      }

      /**
       * Gets the next filename to use for this instance in the case that log
       * filesizes are being capped.
       * @returns {string} - TODO: add return description.
       * @private
       */
      _getFile() {
        const ext = path.extname(this._basename);
        const basename = path.basename(this._basename, ext);
        const isRotation = this.rotationFormat
          ? this.rotationFormat()
          : this._created;

        // Caveat emptor (indexzero): rotationFormat() was broken by design When
        // combined with max files because the set of files to unlink is never
        // stored.
        const target = !this.tailable && this._created
          ? `${basename}${isRotation}${ext}`
          : `${basename}${ext}`;

        return this.zippedArchive
          ? `${target}.gz`
          : target;
      }

      /**
       * Increment the number of files created or checked by this instance.
       * @param {mixed} ext - TODO: add param description.
       * @param {mixed} basename - TODO: add param description.
       * @param {mixed} callback - TODO: add param description.
       * @returns {undefined}
       * @private
       */
      _checkMaxFilesIncrementing(ext, basename, callback) {
        // Check for maxFiles option and delete file.
        Eif (!this.maxFiles || this._created < this.maxFiles) {
          return setImmediate(callback);
        }

        const oldest = this._created - this.maxFiles;
        const isOldest = oldest !== 0 ? oldest : '';
        const isZipped = this.zippedArchive ? '.gz' : '';
        const filePath = `${basename}${isOldest}${ext}${isZipped}`;
        const target = path.join(this.dirname, filePath);

        fs.unlink(target, callback);
      }

      /**
       * Roll files forward based on integer, up to maxFiles. e.g. if base if
       * file.log and it becomes oversized, roll to file1.log, and allow file.log
       * to be re-used. If file is oversized again, roll file1.log to file2.log,
       * roll file.log to file1.log, and so on.
       * @param {mixed} ext - TODO: add param description.
       * @param {mixed} basename - TODO: add param description.
       * @param {mixed} callback - TODO: add param description.
       * @returns {undefined}
       * @private
       */
      _checkMaxFilesTailable(ext, basename, callback) {
        const tasks = [];
        if (!this.maxFiles) {
          return;
        }

        // const isZipped = this.zippedArchive ? '.gz' : '';
        const isZipped = this.zippedArchive ? '.gz' : '';
        for (let x = this.maxFiles - 1; x > 0; x--) {
          tasks.push(function (i) {
            return cb => {
              let fileName = `${basename}${(i - 1)}${ext}${isZipped}`;
              const tmppath = path.join(this.dirname, fileName);

              fs.exists(tmppath, exists => {
                if (!exists) {
                  return cb(null);
                }

                fileName = `${basename}${i}${ext}${isZipped}`;
                fs.rename(tmppath, path.join(this.dirname, fileName), cb);
              });
            };
          }.bind(this, x));
        }

        asyncSeries(tasks, () => {
          fs.rename(
            path.join(this.dirname, `${basename}${ext}`),
            path.join(this.dirname, `${basename}1${ext}`),
            callback
          );
        });
      }
    };