官术网_书友最值得收藏!

Implementing LogService

Logging is an important ally that you want during the development lifecycle of your app as well as in production. It can help you debug as well as gain important insights into how your app is used. Having a single pathway to run all logging through also provides an opportunity to reroute all the app logs somewhere else with the flip of a switch. For example, you could use a third-party debug tracking service, such as TrackJS (https://trackjs.com), via Segment (https://segment.com). You will want to run a lot of important aspects of your app through logging and it serves as a great place to have a lot of control and flexibility. 

Let's open app/modules/core/services/log.service.ts and get to work. Let's start by defining a static boolean that will serve as a simple flag we can toggle in our AppModule to enable/disable. Let's also add a few helpful methods:

import { Injectable } from '@angular/core';

@Injectable()
export class LogService {

public static ENABLE: boolean = true;

public debug(msg: any, ...formatParams: any[]) {
if (LogService.ENABLE) {
console.log(msg, formatParams);
}
}

public error(msg: any, ...formatParams: any[]) {
if (LogService.ENABLE) {
console.error(msg, formatParams);
}
}

public inspect(obj: any) {
if (LogService.ENABLE) {
console.log(obj);
console.log('typeof: ', typeof obj);
if (obj) {
console.log('constructor: ', obj.constructor.name);
for (let key in obj) {
console.log(`${key}: `, obj[key]);
}
}
}
}
}
  • debug: This will serve as our most commonly used output API for logging.
  • error: When we know a certain condition is an error, this will help identify those spots in our log.
  • inspect: There are times when viewing an object can help find a bug or help us understand the state of our app at any given moment.

With our LogService implemented, we will now use it throughout our app and the rest of this book instead of using the console directly.

主站蜘蛛池模板: 中超| 杂多县| 乌拉特前旗| 鄱阳县| 舟曲县| 凤凰县| 道孚县| 玛多县| 成武县| 天津市| 哈尔滨市| 基隆市| 磐安县| 乾安县| 沙湾县| 南木林县| 会同县| 南昌县| 霍州市| 民乐县| 如东县| 昌宁县| 莒南县| 扎囊县| 新泰市| 区。| 郎溪县| 丰原市| 东方市| 女性| 宁阳县| 吉安市| 龙州县| 嘉禾县| 永善县| 肇源县| 泸水县| 黑山县| 景德镇市| 汝州市| 河源市|