Skip to main content

Angular Logging and Log-Back

Advantages of Using Loggers

  • Information at Class Level
  • What timestamp
  • Which user
  • Filename
  • Separate log files for different components.
  • Log levels (like DEBUG, ERROR, WARN, INFO) which can be very handy when you want to track the path followed by your program or log queries, etc.

In this article, we are going to use ngxLogger to achieve logging and log-back in the angular application. First, we need to install the ngxLogger by running the below command at the root of our angular application.

Plain Text

1
npm install ngx-logger --save


Once installed, we need to do the configuration of the ngxLogger in our application. For that, we will be doing the below entries in the app.module.ts file -

TypeScript

1
@NgModule({
2
  declarations: [AppComponent, ...],
3
  imports: [
4
    LoggerModule.forRoot({serverLoggingUrl: '/api/logs', level: NgxLoggerLevel.DEBUG, serverLogLevel: NgxLoggerLevel.ERROR}), 
5
                 ...],
6
  bootstrap: [AppComponent]
7
})
8
export class AppModule {
9
}



This is the configuration part for enabling the logging in our application. Let us understand the meaning of each configuration did for ngxLogging.

  • 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 and we can use it.
  • serverLoggingUrl - This is need 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 which we need to print on the browser's console. This level can be DEBUG, ERROR, WARN, or 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, or 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


Now, we will see the usage of the Logger at the component level.

TypeScript


1
import { Component } from '@angular/core';
2
import { NGXLogger } from 'ngx-logger';
3
 
4
@Component({
5
  selector: 'your-component',
6
  templateUrl: './your.component.html',
7
  styleUrls: ['your.component.scss']
8
})
9
export class YourComponent {
10
  
11
  constructor(private logger: NGXLogger) {
12
    this.logger.debug('Your log message goes here');
13
    this.logger.debug('Multiple', 'Argument', 'support');
14
  }
15
  
16
}



Here, we have injected the NGXLogger in the component. This service class provides us different methods by which we can generate the logs and also we can update the logging configurations. Whenever this component will get loaded, it will simply log the information in the browser's console as well as it can post the logging information to the backend server.

Updating Configuration

We can also change the configuration at the component or service level with the help of updateConfig method of NGXLogger. This will help us to do some configuration change other than the root level and help us to achieve the dynamic behavior of the logging.

TypeScript

1
this.logger.updateConfig({ level: NgxLoggerLevel.ERROR });



Request Payload

The payload body of the request is of type NGXLogInterface. 


code screenshot - requesting payload NGXLogInterface

Request Payload.

Logs at the Browser's Console

[WDS] Live Reloading enabled. 2020-06-17T13:17:32.526Z DEBUG [main.js:213] / loggingApi/logging/getData code screenshot

Logging Using Interceptor

We can also achieve the logging at Interceptor so that whenever there is any request or response coming from the backend server, we can trace that as well and this will help us to identify the flow of the user's request.

TypeScript


1
import { Injectable } from '@angular/core';
2
import {  HttpRequest, HttpHandler, HttpEvent, HttpInterceptor} 
3
from '@angular/common/http';
4
import { Observable } from 'rxjs';
5
import { NGXLogger } from 'ngx-logger';
6
7
@Injectable()
8
export class LoggingInterceptor implements HttpInterceptor {
9
10
  constructor(private logger: NGXLogger) { }
11
12
  intercept(request: HttpRequest<unknown>, next: HttpHandler): Observable<HttpEvent<unknown>> {
13
14
    this.logger.debug(request);
15
    this.logger.error('Any message can be logged');
16
17
    return next.handle(request);
18
  }
19
}
20



With the above code block, we can achieve the logging at the interceptor and keep a track of all the requests and response if needed.

Comments

Popular posts from this blog

4 Ways to Communicate Across Browser Tabs in Realtime

1. Local Storage Events You might have already used LocalStorage, which is accessible across Tabs within the same application origin. But do you know that it also supports events? You can use this feature to communicate across Browser Tabs, where other Tabs will receive the event once the storage is updated. For example, let’s say in one Tab, we execute the following JavaScript code. window.localStorage.setItem("loggedIn", "true"); The other Tabs which listen to the event will receive it, as shown below. window.addEventListener('storage', (event) => { if (event.storageArea != localStorage) return; if (event.key === 'loggedIn') { // Do something with event.newValue } }); 2. Broadcast Channel API The Broadcast Channel API allows communication between Tabs, Windows, Frames, Iframes, and  Web Workers . One Tab can create and post to a channel as follows. const channel = new BroadcastChannel('app-data'); channel.postMessage(data); And oth...

Certbot SSL configuration in ubuntu

  Introduction Let’s Encrypt is a Certificate Authority (CA) that provides an easy way to obtain and install free  TLS/SSL certificates , thereby enabling encrypted HTTPS on web servers. It simplifies the process by providing a software client, Certbot, that attempts to automate most (if not all) of the required steps. Currently, the entire process of obtaining and installing a certificate is fully automated on both Apache and Nginx. In this tutorial, you will use Certbot to obtain a free SSL certificate for Apache on Ubuntu 18.04 and set up your certificate to renew automatically. This tutorial will use a separate Apache virtual host file instead of the default configuration file.  We recommend  creating new Apache virtual host files for each domain because it helps to avoid common mistakes and maintains the default files as a fallback configuration. Prerequisites To follow this tutorial, you will need: One Ubuntu 18.04 server set up by following this  initial ...

Working with Node.js streams

  Introduction Streams are one of the major features that most Node.js applications rely on, especially when handling HTTP requests, reading/writing files, and making socket communications. Streams are very predictable since we can always expect data, error, and end events when using streams. This article will teach Node developers how to use streams to efficiently handle large amounts of data. This is a typical real-world challenge faced by Node developers when they have to deal with a large data source, and it may not be feasible to process this data all at once. This article will cover the following topics: Types of streams When to adopt Node.js streams Batching Composing streams in Node.js Transforming data with transform streams Piping streams Error handling Node.js streams Types of streams The following are four main types of streams in Node.js: Readable streams: The readable stream is responsible for reading data from a source file Writable streams: The writable stream is re...