Implement Logging in Angular With REST API (MongoDB)
Hi Friends, This is Lakshman here.
Welcome back to the Series Angular Best Practices
Today, We will Implement Logging for your angular app with REST API.
Pre-requisites:
The pre-requisites are
- Node.JS - Click Here
- Angular CLI - Click Here
- Docker - Click Here
- MongoDB - Click Here
- MongoDB Compass - Click Here
For Code Editor its VS Code.
Implementation:
We will go there the Implementation by Steps,
Step 1: Create the MongoDB Database in Docker or Cloud
For Docker:
docker pull mongo
docker run --name mongodb -p 37017:27017 -d mongo
For Cloud: Click Here
Preferred Option is Docker
Step 2: Create Node.JS REST API with MongoDB.
Fork the Repo: Click Here
else
Connect the API URl: https://ngangularpracticesapi.azurewebsites.net/
Step 3: Copy the MongoDB URI to .env like below,
MONGO_URI = mongodb://localhost:37017/ngAngularPractices
Step 4. Run the API on Local with below commands,
npm run start:dev
Step 5. Add Config to Environment Configuration File as below,
export const environment = {
...
Logging: {
...
IsRestAPI: true
LogLevel: "Warn"
},
RestAPI: {
LoggingUrl: "http://localhost:5000/"
}
};
On Logging we have Feature Flag Concept. If IsRestAPI Set to True it will log to RestAPI vice versa as per the LogLevel.
NOTE: If you already created the Logging Service Files from Previous Blog Implement Logging with FireBase Please check Step 6 and ignore Step 7, 8, 9 & 10.
Step 6. Modify Logger Service to Log on RestAPI.
constructor(..., private http: HttpClient) {}
private writeToLog(
msg: string,
rawdata: Error,
level: LogLevel,
params: any[]
) {
if (this.shouldLog(level)) {
...
if (environment.Logging.IsRestAPI) {
this.LogToRestAPI(value);
}
// Log the value
console.log(value);
}
}
private LogToRestAPI(val: Ilogger) {
const url = environment.RestAPI.LoggingUrl;
this.http.post(url, val).subscribe((data) => {
console.log(data);
});
}
Step 7. Create the Logging Service Files with below command
npm run ng generate service logging
Step 8. Add below code to logger.service.ts
import { Injectable } from "@angular/core";
import { environment } from "src/environments/environment";
@Injectable({
providedIn: "root",
})
export class LoggingService {
level: LogLevel = LogLevel.All;
constructor(private http: HttpClient) {}
debug(msg: string, rawdata?: any, ...optionalParams: any[]) {
this.writeToLog(msg, rawdata, LogLevel.Debug, optionalParams);
}
info(msg: string, rawdata?: any, ...optionalParams: any[]) {
this.writeToLog(msg, rawdata, LogLevel.Info, optionalParams);
}
warn(msg: string, rawdata?: any, ...optionalParams: any[]) {
this.writeToLog(msg, rawdata, LogLevel.Warn, optionalParams);
}
error(msg: string, rawdata: any, ...optionalParams: any[]) {
this.writeToLog(msg, rawdata, LogLevel.Error, optionalParams);
}
fatal(msg: string, rawdata: any, ...optionalParams: any[]) {
this.writeToLog(msg, rawdata, LogLevel.Fatal, optionalParams);
}
log(msg: string, rawdata?: any, ...optionalParams: any[]) {
this.writeToLog(msg, rawdata, LogLevel.All, optionalParams);
}
setlogLevel(level: LogLevel) {
this.level = level;
}
private writeToLog(
msg: string,
rawdata: Error,
level: LogLevel,
params: any[]
) {
if (this.shouldLog(level)) {
let value: Ilogger = {} as Ilogger;
value.LogDate = JSON.stringify(new Date());
value.LogLevel = LogLevel[level];
value.Message = msg;
if (rawdata) {
value.RawData = rawdata.stack;
}
if (params.length) {
value.OptionalParams = JSON.stringify(params).toString();
}
if (environment.Logging.IsRestAPI) {
this.LogToRestAPI(value);
}
// Log the value
console.log(value);
}
}
private shouldLog(level: LogLevel): boolean {
let ret: boolean = false;
if (
(level >= this.level && level !== LogLevel.Off) ||
this.level === LogLevel.All
) {
ret = true;
}
return ret;
}
private LogToRestAPI(val: Ilogger) {
const url = environment.RestAPI.LoggingUrl;
this.http.post(url, val).subscribe((data) => {
console.info(data);
});
}
}
export interface Ilogger {
loggerId: string;
LogDate: string;
LogLevel: string;
Message: string;
OptionalParams: any;
RawData: any;
}
export enum LogLevel {
All = 0,
Debug = 1,
Info = 2,
Warn = 3,
Error = 4,
Fatal = 5,
Off = 6,
}
In the Above Code We have handling the Error Log level to RestAPI and stores all logs in collection logging in Mongo Database.
Step 9. Add Logging Server to Provider as below Code in app.module.ts
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { environment } from 'src/environments/environment';
import { LoggingService } from './logging.service';
@NgModule({
...
imports: [
CommonModule,
...
],
providers: [
...
LoggingService
]
...
})
export class AppModule { }
Step 10. Set the Log Level for Logging Service in App Component as shown in below Code
import { Component, OnInit } from "@angular/core";
import { environment } from "src/environments/environment";
import { LoggingService, LogLevel } from "./logging/logging.service";
@Component({
selector: "app-root",
templateUrl: "./app.component.html",
styleUrls: ["./app.component.scss"],
})
export class AppComponent implements OnInit {
constructor(private logService: LoggingService) {}
title = "ngAngularPractices";
ngOnInit() {
this.logService.level = LogLevel[environment.Logging.LogLevel];
}
}
Once all the steps completed. We can start using this service any across you module with Injection option to log our error. All the logs will be saved to Rest API.
That wrap up the Implementation process of Logging in Angular with Rest API
You may also access to source on GitHub by Click Here
You may also access to API Source on GitHub by Click Here
On-road head, we will discuss a lot of things.
Looking forward to your comments and share your feedback.
Until that, I am Lakshman, Signing Off.
Comments
Post a Comment