aboutsummaryrefslogtreecommitdiff
path: root/lib/loggers/file.js
blob: 50a251e1c58ab7a500b322c1aa76de91c990e324 (plain)
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
'use strict';

const Fs = require('fs');
const Utilities = require('../utilities');

/**
 * Logger for files.
 *
 * @memberof Loggers
 * @implements ILogger
 * @class File
 */
module.exports = class FileLogger {
  constructor(config) {

    /**
     * Path to the file it will write to, must be readable.
     *
     * @name file
     * @instance
     * @memberof Loggers.File
     * @type string
     * @default null
     */
    this.file = null;

    /**
     * The formatter it will use to output the log. If not present it
     * will output raw JSON
     *
     * @name formatter
     * @instance
     * @memberof Loggers.File
     * @type IFormatter
     * @default null
     */
    this.formatter = null;

    Object.assign(this, config);

    this._stream = Fs.createWriteStream(this.file, { flags: 'a' });
  }

  /**
   * Main entry point, for each incoming argument it will attempt to
   * format and send to the stream to be written.
   *
   * @function log
   * @instance
   * @memberof Loggers.File
   * @return {undefined}
   */
  log(...logs) {

    for (const log of logs) {
      this._stream.write(this._format(log) + '\n');
    }
  }

  _format(logObject) {

    if (this.formatter) {
      return this.formatter.format(logObject);
    }

    return Utilities.stringify(logObject);
  }
};