Angular Logging

From bibbleWiki
Jump to navigation Jump to search

Introduction

This is just an approach to logging not the approach

ngx-logger

Install

npm install ngx-logger --save

Configure

import { HttpClientModule } from '@angular/common/http';
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { LoggerModule, NgxLoggerLevel } from 'ngx-logger';

import { AppComponent } from './app.component';

@NgModule({
  declarations: [AppComponent],
  imports: [
    BrowserModule,
    HttpClientModule,
    LoggerModule.forRoot({
      serverLoggingUrl: '/loggingApi/logging/getLogs',
      level: NgxLoggerLevel.DEBUG,
      serverLogLevel: NgxLoggerLevel.DEBUG,
      colorScheme: ['purple', 'teal', 'gray', 'gray', 'red', 'red', 'red'],
    }),
  ],
  providers: [],
  bootstrap: [AppComponent],
})
export class AppModule {}
  • LoggerModule.forRoot

We have added the logger module at the root of our application. Now, every exported class, components, services, etc. are available throughout the application.

  • serverLoggingUrl

This is needed to specify the endpoint where we need to post the logs from the Angular application. It can be a URL, or if you are using a proxy, then it can be the endpoint as well.

  • level

The level defines the logs configuration level we need to print on the browser's console. This level can be DEBUG, ERROR, WARN, INFO, etc. If the value is set as OFF, it will disable the browser's console logs.

  • serverLogLevel

This level defines the log configuration level which we need to post to the backend service or any API which is consuming the logging information. This level can be DEBUG, ERROR, WARN, INFO, etc. If the value is set as OFF, it will disable the server level logs.

NgxLoggerLevels: TRACE|DEBUG|INFO|LOG|WARN|ERROR|FATAL|OFF

Usage

Here is an example of usage

import { Component, OnInit } from '@angular/core';
import { NGXLogger } from 'ngx-logger';

@Component({
  selector: 'app-users',
  templateUrl: './user-list.component.html',
  styleUrls: ['./user-list.component.css'],
})
export class UserListComponent implements OnInit {
  constructor(private logger: NGXLogger) {
    this.logger.debug('Test message');
  }

  // eslint-disable-next-line class-methods-use-this
  ngOnInit(): void {
    this.logger.debug('Method not implemented.');
  }
}

Server

Here is a sample server

const express = require('express');
const delay = require('delay');

const router = express.Router();

module.exports = router;

router.post('/logging/getLogs', async (req, res) => {
  const logData = req.body;
  console.log(logData.message);
  return res.status(200);
})

router.get('/logging/getData', async (req, res) => {

  data = {};
  data = {
    Message: "Dummy Message"
  };
  return res.status(200).send(data);
})