Update: to trace message
It's relatively simple to see the trace of any logs you can just add a boolean property isTraceable and then do something like this.
if (isTraceable) {
console.trace(message);
}
By default isTraceable can be set false and you can turn it on only when needed.
Original Answer
I have created a solution for this. As mentioned by many others I am using a service to achieve this. The difference in my solution is that you can also specify log levels. Here is my code
This is my log-level.model.ts file you can add it with your other model files.
export const LOG_LEVELS = {
FATAL: 0,
ERROR: 1,
WARN: 2,
INFO: 3,
DEBUG: 4,
};
export class LogLevel {
static readonly DEBUG = LOG_LEVELS.DEBUG;
static readonly INFO = LOG_LEVELS.INFO;
static readonly WARN = LOG_LEVELS.WARN;
static readonly ERROR = LOG_LEVELS.ERROR;
static readonly FATAL = LOG_LEVELS.FATAL;
}
Now coming to main service this is my log.service.ts file add this with all your other service file and you will be good to go.
import { Injectable } from "@angular/core";
import { LogLevel, LOG_LEVELS } from "../public-api";
@Injectable({
providedIn: "root"
})
export class LogService {
currentLog: LogLevel;
constructor() {
this.currentLog = LOG_LEVELS.DEBUG;
}
setLogLevel(level: LogLevel) {
this.currentLog = level;
}
debug(message: any, param: any = "DEBUG") {
if (this.currentLog >= LOG_LEVELS.DEBUG) {
console.log(param, message);
}
}
info(message: any, param: any = "INFO") {
if (this.currentLog >= LOG_LEVELS.INFO) {
console.log(param, message);
}
}
warn(message: any, param: any = "WARN") {
if (this.currentLog >= LOG_LEVELS.WARN) {
console.warn(param, message);
}
}
error(message: any, param: any = "ERROR") {
if (this.currentLog >= LOG_LEVELS.ERROR) {
console.error(param, message);
}
}
}
There is just one thing left to do now, controlling the log level. This can be done in app.component.ts file by using following piece of code.
environment.production ? this.log.setLogLevel(LOG_LEVELS.ERROR) : this.log.setLogLevel(LOG_LEVELS.DEBUG);
Make sure to import properly. Also you can change log levels as per your need.