| 1 | 'use strict'; |
| 2 | |
| 3 | const Fs = require('fs'); |
| 4 | const Utilities = require('../utilities'); |
| 5 | |
| 6 | /** |
| 7 | * Logger for files. |
| 8 | * |
| 9 | * @memberof Loggers |
| 10 | * @implements ILogger |
| 11 | * @class File |
| 12 | */ |
| 13 | module.exports = class FileLogger { |
| 14 | constructor(config) { |
| 15 | |
| 16 | /** |
| 17 | * Path to the file it will write to, must be readable. |
| 18 | * |
| 19 | * @name file |
| 20 | * @instance |
| 21 | * @memberof Loggers.File |
| 22 | * @type string |
| 23 | * @default null |
| 24 | */ |
| 25 | this.file = null; |
| 26 | |
| 27 | /** |
| 28 | * The formatter it will use to output the log. If not present it |
| 29 | * will output raw JSON |
| 30 | * |
| 31 | * @name formatter |
| 32 | * @instance |
| 33 | * @memberof Loggers.File |
| 34 | * @type IFormatter |
| 35 | * @default null |
| 36 | */ |
| 37 | this.formatter = null; |
| 38 | |
| 39 | Object.assign(this, config); |
| 40 | |
| 41 | this._stream = Fs.createWriteStream(this.file, { flags: 'a' }); |
| 42 | } |
| 43 | |
| 44 | /** |
| 45 | * Main entry point, for each incoming argument it will attempt to |
| 46 | * format and send to the stream to be written. |
| 47 | * |
| 48 | * @function log |
| 49 | * @instance |
| 50 | * @memberof Loggers.File |
| 51 | * @return {undefined} |
| 52 | */ |
| 53 | log(...logs) { |
| 54 | |
| 55 | for (const log of logs) { |
| 56 | this._stream.write(this._format(log) + '\n'); |
| 57 | } |
| 58 | } |
| 59 | |
| 60 | _format(logObject) { |
| 61 | |
| 62 | if (this.formatter) { |
| 63 | return this.formatter.format(logObject); |
| 64 | } |
| 65 | |
| 66 | return Utilities.stringify(logObject); |
| 67 | } |
| 68 | }; |