DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Related

  • Implementing Micro Frontends in Angular: Step-By-Step Guide
  • Micro Frontends Architecture
  • Difference Between Bootstrap and AngularJS in 2022
  • Login With Google in Angular Firebase Application

Trending

  • 5 AI Security Incidents That Broke Things in Production (and What They Have in Common)
  • Every Cache Miss Is a Tiny Tax on Your Performance
  • Observability for Agents and Workflows: Tracing Prompts, Tool Calls, and Business Outcomes End-to-End
  • Why Stable RAG Answers Can Still Hide Unstable Evidence
  1. DZone
  2. Coding
  3. Frameworks
  4. Angular Logging and Log-Back

Angular Logging and Log-Back

By 
Aakash Jangid user avatar
Aakash Jangid
·
Updated Jun. 22, 20 · Tutorial
Likes (5)
Comment
Save
Tweet
Share
27.6K Views

Join the DZone community and get the full member experience.

Join For Free

In this article, we will see how to do Client-Side Logging and Server Side Log-back in an Angular application. We all enable logging in our application to understand the behavior of the application and to debug unexpected issues or simply tracking events. In the production environment, we can't debug issues without proper log files, as they become the only source of information to debug some intermittent or unexpected errors.

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 an Angular application. First, we need to install the ngxLogger by running the below command at the root of our Angular application.

Plain Text
xxxxxxxxxx
1
 
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
xxxxxxxxxx
1
 
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
}


Here, we will cover the configuration part necessary to enable logging in our application. Let us understand the meaning of each configuration 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.
  • 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

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

TypeScript
xxxxxxxxxx
1
16
 
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 update the logging configurations. Whenever this component will get loaded, it will simply log the information in the browser's console. Additionally, 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 the 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
xxxxxxxxxx
1
 
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

Log at browser's console

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
xxxxxxxxxx
1
20
 
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.

A working example of this code is available at this GitHub repository.

AngularJS application

Opinions expressed by DZone contributors are their own.

Related

  • Implementing Micro Frontends in Angular: Step-By-Step Guide
  • Micro Frontends Architecture
  • Difference Between Bootstrap and AngularJS in 2022
  • Login With Google in Angular Firebase Application

Partner Resources

×

Comments

The likes didn't load as expected. Please refresh the page and try again.

  • RSS
  • X
  • Facebook

ABOUT US

  • About DZone
  • Support and feedback
  • Community research

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 215
  • Nashville, TN 37211
  • [email protected]

Let's be friends:

  • RSS
  • X
  • Facebook