]> git.r.bdr.sh - rbdr/cologne/blame - lib/loggers/file.js
Update docs and tooling
[rbdr/cologne] / lib / loggers / file.js
CommitLineData
bfd26c00
RBR
1'use strict';
2
b3847a2e
RBR
3const Fs = require('fs');
4const Utilities = require('../utilities');
bfd26c00
RBR
5
6/**
7 * Logger for files.
8 *
b3847a2e
RBR
9 * @memberof Loggers
10 * @implements ILogger
bfd26c00
RBR
11 * @class File
12 */
b3847a2e
RBR
13module.exports = class FileLogger {
14 constructor(config) {
bfd26c00
RBR
15
16 /**
17 * Path to the file it will write to, must be readable.
18 *
19 * @name file
20 * @instance
b3847a2e 21 * @memberof Loggers.File
bfd26c00
RBR
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
b3847a2e
RBR
33 * @memberof Loggers.File
34 * @type IFormatter
bfd26c00
RBR
35 * @default null
36 */
37 this.formatter = null;
38
b3847a2e 39 Object.assign(this, config);
bfd26c00 40
b3847a2e 41 this._stream = Fs.createWriteStream(this.file, { flags: 'a' });
bfd26c00
RBR
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
b3847a2e 50 * @memberof Loggers.File
bfd26c00
RBR
51 * @return {undefined}
52 */
b3847a2e 53 log(...logs) {
bfd26c00 54
b3847a2e
RBR
55 for (const log of logs) {
56 this._stream.write(this._format(log) + '\n');
bfd26c00
RBR
57 }
58 }
59
b3847a2e
RBR
60 _format(logObject) {
61
bfd26c00
RBR
62 if (this.formatter) {
63 return this.formatter.format(logObject);
64 }
65
b3847a2e 66 return Utilities.stringify(logObject);
bfd26c00
RBR
67 }
68};