@scriptwerx/logger
Version:
Simple console logger for use in your Angular 2 applications.
134 lines (116 loc) • 2.36 kB
text/typescript
import { Injectable } from '@angular/core';
import { ILogLevels, Log } from '../model/constants.model';
export class LoggerService {
/**
*
* @type {ILogLevels}
* @private
*/
private _levels: ILogLevels = Log.LEVELS;
/**
*
* @type {number}
* @private
*/
private _currentLevel: number = this._levels.debug;
/**
*
* @param type
* @param params
* @private
*/
private log(type: string, ...params:any[]) {
let console = window.console,
logFn = console[type] || console.log || function(){ /* empty */ },
hasApply = false;
try {
hasApply = !!logFn.apply;
} catch (e) { /* empty */ }
if (hasApply) {
logFn.apply(console, params[0]);
}
}
/**
*
*/
get level() {
return this._currentLevel;
};
/**
*
* @param level
*/
set level(level: any) {
if (!level) {
level = 'error';
}
switch(level.toLowerCase()) {
case 'debug':
this._currentLevel = this._levels.debug;
break;
case 'info':
this._currentLevel = this._levels.info;
break;
case 'warn':
this._currentLevel = this._levels.warn;
break;
case 'error':
this._currentLevel = this._levels.error;
break;
case 'fatal':
this._currentLevel = this._levels.fatal;
break;
case 'none':
this._currentLevel = this._levels.none;
break;
default:
throw new Error('LoggerService: Invalid level - ' + level + ' is not debug|info|warn|error|fatal|none');
}
}
/**
*
* @param params
*/
debug(...params: any[]) {
if (this.level <= this._levels.debug) {
this.log('debug', params);
}
};
/**
*
* @param params
*/
info(...params: any[]) {
if (this.level <= this._levels.info) {
this.log('info', params);
}
};
/**
*
* @param params
*/
warn(...params: any[]) {
if (this.level <= this._levels.warn) {
this.log('warn', params);
}
};
/**
*
* @param params
*/
error(...params: any[]) {
if (this.level <= this._levels.error) {
this.log('error', params);
}
};
/**
*
* @param params
*/
fatal(...params: any[]) {
if (this.level <= this._levels.fatal) {
this.log('fatal', params);
}
};
}