背景
我们在开发时都很喜欢使用console.*来打印出日志信息以方便我们调试代码,但是在上线时肯定是需要去除所有的console;但是大多数情况下开发者都会忘记移除console输出,这会带来生产日志风险。
编写
- 新增一个日志组件:logger
ionic g provier logger
- 修改logger.ts的内容如下:
import {Injectable} from '@angular/core';
import {Constants} from "../Constants";
@Injectable()
export class Logger {
constructor() {
}
/**
* Logs messages or objects with the debug level.
* Works the same as console.log().
*/
public log(...objects: any[]) {
this.log_real(console.log, LogLevel.Debug, objects);
}
/**
* Logs messages or objects with the debug level.
* Works the same as console.debug().
*/
public debug(...objects: any[]) {
this.log_real(console.log, LogLevel.Debug, objects);
}
/**
* Logs messages or objects with the info level.
* Works the same as console.info().
*/
public info(...objects: any[]) {
this.log_real(console.info, LogLevel.Info, objects);
}
/**
* Logs messages or objects with the warning level.
* Works the same as console.warn().
*/
public warn(...objects: any[]) {
this.log_real(console.warn, LogLevel.Warning, objects);
}
/**
* Logs messages or objects with the error level.
* Works the same as console.error().
*/
public error(...objects: any[]) {
this.log_real(console.error, LogLevel.Error, objects);
}
protected async log_real(func: Function, level: LogLevel, objects: any[]) {
const env = Constants.ENVIRONMENT || 'development';
if (env !== 'production') {
func.apply(console, objects);
}
}
}
export enum LogLevel {
Error,
Warning,
Info,
Debug,
}
- 在app.module.ts中引入Logger组件:
import {Logger} from "../common/logger/logger";
......
providers: [
Logger,
]
......
使用:
- 在Constants中新增一个变量:
export const Constants = {
ENVIRONMENT: 'development',//app环境,开发时为development,正式发布时需求注掉或者改为production
}
- 在需要打印日志的地方引用
import {Injectable} from "@angular/core";
import {RequestPreviewHandler} from "../RequestPreviewHandler";
import {HttpRequest} from "@angular/common/http";
import {Logger} from "../../../../common/logger/logger";
@Injectable()
export class DefaultRequestPreviewHandler extends RequestPreviewHandler {
constructor(private logger: Logger) {
super();
}
handle(request: HttpRequest<any>): HttpRequest<any> {
this.logger.warn("未注入自定义请求前置处理类,使用默认前置处理");
return request;
}
}
效果与使用console一致,如下:
- 生产发版
只需要将Constants中ENVIRONMENT的值为production即可去除所有日志输出
export const Constants = {
ENVIRONMENT: 'production',//app环境,开发时为development,正式发布时需求注掉或者改为production
}
;
避免了还需要手动删除console相关代码的问题。