X-Git-Url: https://git.r.bdr.sh/rbdr/cologne/blobdiff_plain/58906d77975b35fe93569f8083b90140124f9c41..ae85c067634676251e812765c81adfdef8f85f9d:/lib/loggers/file.js diff --git a/lib/loggers/file.js b/lib/loggers/file.js new file mode 100644 index 0000000..50a251e --- /dev/null +++ b/lib/loggers/file.js @@ -0,0 +1,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); + } +};