All files / src Logger.ts

92.47% Statements 135/146
80.7% Branches 46/57
100% Functions 35/35
92.31% Lines 132/143

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356                                  1x 1x 1x   1x 1x         1x                 48x   48x   48x 48x   48x           48x 1x     48x   48x       25x       25x       1x       1x       79x       2x       2x       2x       1x 1x 1x         28x 27x     1x         8x       25x 25x   25x 25x     25x           25x 25x 1x     24x 24x 25x 25x       25x       25x 25x       25x 25x       25x 25x   25x       49x       37x       703x       82x       82x 82x   82x   33x 33x   1x 1x   5x 5x   4x 4x   36x 36x   1x 1x         2x 2x     82x 83x   83x 1x     83x 15x     68x     83x 12x       82x       79x   79x       79x 79x 1x     78x           79x 33x     46x 46x 46x         46x       700x 79x 79x       79x         543x       1x       72x       28x       36x       1x       11x 11x   11x 11x           11x 2x     11x 11x 11x       7x 7x   7x   7x 7x     7x 7x 7x       11x 11x 11x 2x 2x   11x       2x       7x 7x 7x       7x       7x      
// Copyright (C) 2017  Norman Breau
 
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
 
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
 
// You should have received a copy of the GNU General Public License
// along with this program.  If not, see <http://www.gnu.org/licenses/>.
 
/* eslint-disable prefer-rest-params */
 
import {EventEmitter} from 'events';
import {LogSeverity} from './LogSeverity';
import {LogEvent} from './LogEvent';
import {ILogEvent} from './ILogEvent';
import * as utils from 'util';
import {getInstance} from './instance';
import { IConfig } from './IConfig';
import { Application } from './Application';
import {Writable} from 'stream';
 
export class Logger extends EventEmitter {
    private name: string;
    private logLevel: LogSeverity;
    private useStdErrForErrors: boolean;
    private _filters: Array<RegExp>;
    private _logStream: Writable;
    private _errorStream: Writable;
 
    public constructor(name: string = '', logLevel?: LogSeverity, useStdErrForErrors: boolean = false) {
        super();
 
        this.name = name;
 
        this._logStream = this._getDefaultLogStream();
        this._errorStream = this._getDefaultErrorStream();
 
        this.logLevel = LogSeverity.DEBUG       |
                        LogSeverity.INFO        |
                        LogSeverity.WARNING     |
                        LogSeverity.ERROR       |
                        LogSeverity.FATAL;
        
        if (logLevel) {
            this.logLevel = logLevel;
        }
 
        this._filters = this._getDefaultLogFilters();
 
        this.useStdErrForErrors = useStdErrForErrors;
    }
 
    protected _getDefaultLogStream(): Writable {
        return process.stdout;
    }
 
    protected _getDefaultErrorStream(): Writable {
        return process.stderr;
    }
 
    public setLogStream(writable: Writable) {
        this._logStream = writable;
    }
 
    public setErrorStream(writable: Writable) {
        this._errorStream = writable;
    }
 
    public getLogStream(): Writable {
        return this._logStream;
    }
 
    public getErrorStream(): Writable {
        return this._errorStream;
    }
 
    public getName(): string {
        return this.name;
    }
 
    public addFilter(reg: RegExp): void {
        this._filters.push(reg);
    }
 
    public removeFilter(reg: RegExp): void {
        let index: number = this._filters.indexOf(reg);
        Eif (index > -1) {
            this._filters.splice(index, 1);
        }
    }
 
    public setFilters(filters: Array<RegExp>): void {
        if (filters) {
            this._filters  = filters.slice();
        }
        else {
            this._filters = [];
        }
    }
 
    public getFilters(): Array<RegExp> {
        return this._filters.slice();
    }
 
    public loadFilters(): void {
        let app: Application = getInstance();
        let config: IConfig = null;
 
        Eif (app) {
            config = app.getConfig();
        }
 
        Iif (!config) {
            this.trace('No config for logger... Using default log filters');
            this.setFilters(this._getDefaultLogFilters());
            return;
        }
 
        let filters: Array<RegExp> = null;
        if (!config.log_filters || (config.log_filters && config.log_filters.length === 0)) {
            filters = this._getDefaultLogFilters();
        }
        else {
            filters = [];
            for (let i: number = 0; i < config.log_filters.length; i++) {
                let logFilter: string = config.log_filters[i];
                filters.push(new RegExp(this._parseRegex(logFilter)));
            }
        }
 
        this.setFilters(filters);
    }
 
    private _parseRegex(strReg: string): RegExp {
        let malformError: Error = new Error('Malformed regex in log_filters');
        Iif (strReg[0] !== '/') {
            throw malformError;
        }
 
        let lastSlashIndex = strReg.lastIndexOf('/');
        Iif (lastSlashIndex === strReg.indexOf('/')) {
            throw malformError;
        }
 
        let reg: string = strReg.slice(1, lastSlashIndex);
        let flags = strReg.slice(lastSlashIndex + 1);
 
        return new RegExp(reg, flags);
    }
 
    protected _getDefaultLogFilters(): Array<RegExp> {
        return [/TokenExpiredError/g];
    }
 
    public setLogLevel(severity: LogSeverity): void {
        this.logLevel = severity;
    }
 
    public getLogLevel(): LogSeverity {
        return this.logLevel;
    }
 
    protected _formatDate(now: Date): string {
        return `${now.getFullYear()}/${now.getMonth() + 1}/${now.getDate()} - ${now.getHours()}:${now.getMinutes()}:${now.getSeconds()}`;
    }
 
    protected _formatString(messages: IArguments, severity: LogSeverity): string {
        let sevText: string = '';
        let str: string = '';
 
        switch (severity) {
            case LogSeverity.TRACE:
                sevText = '[TRACE]';
                break;
            case LogSeverity.DEBUG:
                sevText = '[DEBUG]';
                break;
            case LogSeverity.INFO:
                sevText = '[INFO]';
                break;
            case LogSeverity.WARNING:
                sevText = '[WARN]';
                break;
            case LogSeverity.ERROR:
                sevText = '[ERROR]';
                break;
            case LogSeverity.FATAL:
                sevText = '[FATAL]';
                break;
            case LogSeverity.DEPRECATE:
                sevText = '[DEPRECATE]';
                break;
            default:
                this.warn('Unknown Severity value used.');
                break;
        }
        
        for (let i: number = 0; i < messages.length; i++) {
            let msg: any = messages[i];
 
            if (str.length !== 0) {
                str += ' ';
            }
 
            if (typeof msg !== 'string') {
                str += utils.inspect(msg);
            }
            else {
                str += msg;
            }
 
            if (msg instanceof Error) {
                str = msg.stack + '\n\n';
            }
        }
 
        return `${sevText}[${this.name}][${this._formatDate(new Date())}] ${str}\n`;
    }
 
    protected _logMessages(messages: IArguments, severity: LogSeverity): void {
        let msg: string = this._formatString(messages, severity);
        
        this._logMessage(msg, severity);
    }
 
    protected _logMessage(msg: string, severity: LogSeverity): void {
        Eif (this._shouldLog(msg, severity)) {
            if ((severity & (LogSeverity.ERROR | LogSeverity.FATAL)) && this.useStdErrForErrors) {
                this.getErrorStream().write(msg);
            }
            else {
                this.getLogStream().write(msg);
            }
        }
    }
 
    protected _shouldLog(msg: string, severity: LogSeverity): boolean {
        if (severity === LogSeverity.TRACE) {
            return true;
        }
 
        for (let i: number = 0; i < this._filters.length; i++) {
            let filter: RegExp = this._filters[i];
            Iif (filter.test(msg)) {
                return false;
            }
        }
 
        return true;
    }
 
    protected log(messages: IArguments, severity: LogSeverity): void {
        if (severity & this.getLogLevel()) {
            this._logMessages(messages, severity);
            let logData: ILogEvent = {
                severity : severity,
                messages : messages
            };
            this.emit(LogEvent.LOG, logData);
        }
    }
 
    public trace(message: any): void {
        this.log(arguments, LogSeverity.TRACE);
    }
 
    public debug(message: any): void {
        this.log(arguments, LogSeverity.DEBUG);
    }
 
    public info(message: any): void {
        this.log(arguments, LogSeverity.INFO);
    }
 
    public warn(message: any): void {
        this.log(arguments, LogSeverity.WARNING);
    }
 
    public error(message: any): void {
        this.log(arguments, LogSeverity.ERROR);
    }
 
    public fatal(message: any): void {
        this.log(arguments, LogSeverity.FATAL);
    }
 
    public deprecate(alternative?: string, methodOverride?: string): void {
        let e: Error = new Error();
        let args: any = [];
        
        Eif (!methodOverride) {
            args.push(this._getDeprecatedMethodMessage(e));
        }
        else {
            args.push(methodOverride);
        }
 
        if (alternative) {
            args.push(this._getDeprecatedAlternativeMessage(alternative));
        }
        
        args.push('\n\n');
        args.push(e.stack);
        this.log(args, LogSeverity.DEPRECATE);
    }
 
    public deprecateParameterType(argumentLocation: number, deprecatedType: string, alternative?: string): void {
        let e: Error = new Error();
        let args: any = [];
 
        args.push(this._getDeprecatedParameterMethodMessage(e, argumentLocation, deprecatedType));
 
        Eif (alternative) {
            args.push(this._getDeprecatedParameterAlternativeMessage(alternative,  argumentLocation));
        }
        
        args.push('\n\n');
        args.push(e.stack);
        this.log(args, LogSeverity.DEPRECATE);
    }
    
    private _getDeprecatedMethodMessage(e: Error): string {
        let stack = e.stack.split('\n')[2].replace(/^\s+at\s+(.+?)\s.+/g, '$1');
        let obj: string = 'Method';
        if (stack === "new") {
            stack = e.stack.split('\n')[2].replace(/^\s+at new\s+(.+?)\s.+/g, '$1');
            obj = 'Class';
        }
        return `${obj} ${stack} is deprecated.`
    }
 
    private _getDeprecatedAlternativeMessage(alternative: string): string {
        return `Use ${alternative} instead.`;
    }
 
    private _getDeprecatedParameterMethodMessage(e: Error, argumentLocation: number, parameter: string): string {
        let stack = e.stack.split('\n')[2].replace(/^\s+at\s+(.+?)\s.+/g, '$1');
        let obj: string = 'Method';
        Iif (stack === "new") {
            stack = e.stack.split('\n')[2].replace(/^\s+at new\s+(.+?)\s.+/g, '$1');
            obj = 'Class';
        }
        return `${obj} ${stack} ${parameter} at parameter ${argumentLocation} is deprecated.`
    }
 
    private _getDeprecatedParameterAlternativeMessage(alternative: string, argumentLocation: number): string {
        return `Use ${alternative} at parameter ${argumentLocation} instead.`;
    }
}