]> git.r.bdr.sh - rbdr/cologne/blobdiff - lib/loggers/file.js
Update the code.
[rbdr/cologne] / lib / loggers / file.js
diff --git a/lib/loggers/file.js b/lib/loggers/file.js
new file mode 100644 (file)
index 0000000..50a251e
--- /dev/null
@@ -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);
+  }
+};