Logging in Angular Application | Angular Logger Service
Logger or Log Configuration in any code is as important as senses are to human body.
Without senses a human body is dysfunctional and without logger any application is subject to malfunctional.
In this article we will see how we can implement logger in any Angular application irrespective of the structure of the project/app. Also at the end of this article I will be attaching a link of Stackblitz for your reference. So Let’s start without any further due !!! 😎
Step 1 : Creating a model class with different Log Levels
Levels in logs are the senses to code, like human body have sense of Sight, Sound, Smell, Taste, and Touch similarly loggers have levels as None, Info, Debug, Warn, Error. Let’s define them in logelevel.model.ts file
export class LogLevel {
None = 0;
Info = 1;
Verbose = 2;
Warn = 3;
Error = 4;constructor() { }
}
Step 2 : Creating a logger Service class
Now here comes the main part, once the log levels are defined we have to now import them in our service file and create our own logging functions…
Let’s now create logger.service.ts file
import { Injectable } from '@angular/core';
import { LogLevel } from './logLevel.model';@Injectable({
providedIn: 'root',
})
export class LoggerService {
logLevel: LogLevel = new LogLevel();constructor() {}info(msg: string): void {
this.logWith(this.logLevel.Info, msg);
}warn(msg: string): void {
this.logWith(this.logLevel.Warn, msg);
}error(msg: string): void {
this.logWith(this.logLevel.Error, msg);
}private logWith(level: any, msg: string): void {
if (level <= this.logLevel.Error) {
switch (level) {
case this.logLevel.None:
return console.log(msg);
case this.logLevel.Info:
return console.info('%c' + msg, 'color: #6495ED');
case this.logLevel.Warn:
return console.warn('%c' + msg, 'color: #FF8C00');
case this.logLevel.Error:
return console.error('%c' + msg, 'color: #DC143C');
default:
console.debug(msg);
}
}
}
}
In our service file we have first import our logLevel.model.ts file and then created it’s object “logLevel”. After that we have defined 3 functions naming info(), warn() & error() with message as an argument, all of which are a calling a function logWith() with arguments as a message & a log level.
logWith() function will compare the level a user is currently on to the highest level of our logger and it will then call the different functional console outcomes based on a switch case of levels.
Step 3: Assigning colors to our logs
Just to add extra visibility to our logs we can provide colors to different levels of logs, we can do that using the hexa-color-code, for example :
console.info('%c' + msg, 'color: #6495ED');
Step 4: Injecting the logger service in component.ts file
First inject your service in constructor as below :
constructor( private logger: LoggerService ) { }
After this you can handle all of your logs based on your requirement, for an example : if I am stepping into an export function, I will warn my application that I am going to export the data and at the end when my data is exported I will provide an info to my application…
async convertData(fromDate: string, toDate: string, dataCenter: string): Promise<void> {
this.logger.warn('converting data to export');
this.SpinnerService.show();
const exportData = await this.siService.getExportData(dataCenter, fromDate, toDate, 'ACTIVE');
for (const exp of exportData) {
const jiraExport = new JiraExport();
jiraExport.assetId = exp[0];
jiraExport.userCount = exp[1];
jiraExport.userTypeCode = exp[2];
jiraExport.userType = exp[3];
jiraExport.assetName = exp[4];
jiraExport.url = exp[5];
jiraExport.pod = exp[6];
jiraExport.engagementId = exp[8];
jiraExport.projectKey = jiraExport.url === null ? '' : jiraExport.url.substr(jiraExport.url.lastIndexOf('/') + 1);
this.jiraExports.push(jiraExport);
}
this.logger.info('data exported');
this.excelService.exportAsExcelFile(this.jiraExports, 'JIRA');
this.SpinnerService.hide();
}
Conclusion & Demo Project Link
In this article we learned how we can create a logger service with different log levels and how we can inject them to our component.ts file and use them with respect to our requirement, we can also implement logger in our angular life cycle hooks in order to trace a component’s instance…. like ngOnInit(), ngAfterViewInit(), ….. , ngDestroy(). Angular logger is nothing more but a variable instances of console functions.
Below I am providing a simple demo project link :
https://stackblitz.com/edit/angular-ivy-xcx5gu
https://github.com/thesiddharthraghuvanshi/logger-service-in-angular
Hope this article helped you at some extent of logger implementation. Please follow for more such article.
Thankyou!!!