Home > Article > Web Front-end > Let’s talk about how Angular+Service improves the logging function
How to improve Angular's log usage? The following article will introduce to you how to use the Service management console output in Angular to improve the logging function. I hope it will be helpful to you!
Angular
Yes A very popular development framework. Front-end developers like to use console
to debug their code in applications. However, due to the need for continuous delivery/deployment, these debugging codes will be deleted and will not enter production. release environment. [Related tutorial recommendations: "angular tutorial"]
##Let Angular help us implement this function
Angular provides us with the function of registering
Services into the application, so that we can reuse some functions in the component.
Service to manage our console output and thereby improve the logging function.
1 : Use Service to manage the console
import { Injectable } from '@angular/core'; @Injectable({ providedIn: 'root' }) export class LogService { constructor() { } trace(...data: any[]): void { console.trace(data); } log(...data: any[]): void { console.log(data); } }Use it in the
AppComponent component::
logService.log('console executed from AppComponent');The above code is easy to understand, but there is a problem, we cannot know whether the log is in the application Which component is printed, unless we indicate it in the log message. For example, the log information in the figure shows that it comes from the
AppComponent component. We hope that the right side of the log can automatically indicate which component it comes from, and It is not the file bit
log.service.ts:xx that defines the entire logging system, and we do not need to manually indicate it in the log message.
1.1: Use logService.trace()
It can be used to trace the source of the log, which looks good, but in fact it will add some unnecessary Logging.2: Enhanced version of logService
import { Injectable } from '@angular/core'; @Injectable({ providedIn: 'root' }) export class LogService { constructor() { } trace(source: string, ...data: any[]): void { console.trace(data); } log(source: string, ...data: any[]): void { console.log(data); } }Compared with the previous one, the enhanced version of the
logService class method receives additional parameters.
logService.log('AppComponent','console executed from AppComponent');Very good
The above is the detailed content of Let’s talk about how Angular+Service improves the logging function. For more information, please follow other related articles on the PHP Chinese website!