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

How to use Ngx-Charts in Angular ?

Charts helps us to visualize large amount of data in an easy to understand and interactive way. This helps businesses to grow more by taking important decisions from the data. For example, e-commerce can have charts or reports for product sales, with various categories like product type, year, etc. In angular, we have various charting libraries to create charts.  Ngx-charts  is one of them. Check out the list of  best angular chart libraries .  In this article, we will see data visualization with ngx-charts and how to use ngx-charts in angular application ? We will see, How to install ngx-charts in angular ? Create a vertical bar chart Create a pie chart, advanced pie chart and pie chart grid Introduction ngx-charts  is an open-source and declarative charting framework for angular2+. It is maintained by  Swimlane . It is using Angular to render and animate the SVG elements with all of its binding and speed goodness and uses d3 for the excellent math functio...

Understand Angular’s forRoot and forChild

  forRoot   /   forChild   is a pattern for singleton services that most of us know from routing. Routing is actually the main use case for it and as it is not commonly used outside of it, I wouldn’t be surprised if most Angular developers haven’t given it a second thought. However, as the official Angular documentation puts it: “Understanding how  forRoot()  works to make sure a service is a singleton will inform your development at a deeper level.” So let’s go. Providers & Injectors Angular comes with a dependency injection (DI) mechanism. When a component depends on a service, you don’t manually create an instance of the service. You  inject  the service and the dependency injection system takes care of providing an instance. import { Component, OnInit } from '@angular/core'; import { TestService } from 'src/app/services/test.service'; @Component({ selector: 'app-test', templateUrl: './test.component.html', styleUrls: ['./test.compon...

How to solve Puppeteer TimeoutError: Navigation timeout of 30000 ms exceeded

During the automation of multiple tasks on my job and personal projects, i decided to move on  Puppeteer  instead of the old school PhantomJS. One of the most usual problems with pages that contain a lot of content, because of the ads, images etc. is the load time, an exception is thrown (specifically the TimeoutError) after a page takes more than 30000ms (30 seconds) to load totally. To solve this problem, you will have 2 options, either to increase this timeout in the configuration or remove it at all. Personally, i prefer to remove the limit as i know that the pages that i work with will end up loading someday. In this article, i'll explain you briefly 2 ways to bypass this limitation. A. Globally on the tab The option that i prefer, as i browse multiple pages in the same tab, is to remove the timeout limit on the tab that i use to browse. For example, to remove the limit you should add: await page . setDefaultNavigationTimeout ( 0 ) ;  COPY SNIPPET The setDefaultNav...