Implement Logging in Angular With REST API - lakshmansha/ngAngularPractices GitHub Wiki
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.
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.
We will go there the Implementation by Steps,
For Docker:
docker pull mongo
docker run --name mongodb -p 37017:27017 -d mongo
For Cloud: Click Here
Preferred Option is Docker
Fork the Repo: Click Here
else
Connect the API URl: https://ngangularpracticesapi.azurewebsites.net/
MONGO_URI = mongodb://localhost:37017/ngAngularPracticesnpm run start:devexport 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.
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);
});
}npm run ng generate service logging
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.
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 { }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.