Angular 15 – Server-Side Logging with ngx-logger Tutorial

Logging plays a crucial role in software applications which adds a vaueable insight into the application. it helps developers to diagnose and fix the critical issues on production environments. We usually perform logging on client side but server side logging is also equally important.

In this guide, we will discuss how to use ngx-logger library to easily integrate a rohust feature in Angular application to log messages on Client as well as Server side. We will walk through easily steps to configure it and use in the application with examples.

Why is Server-Side Logging Important?

Server-side logging provides a centralized location to store log messages and allows developers to easily monitor and analyze application behavior. When an issue arises, developers can quickly search through the logs to identify the source of the problem and take the necessary steps to resolve it.

Server-side logging can also be useful for compliance and auditing purposes, as it provides a record of application activity that can be reviewed by security and compliance teams. This can help organizations meet regulatory requirements and demonstrate that they are following best practices for data security and privacy.

 

How to Add Client and Server Side Logger Service in Angular App?

Follow these quick steps to integrate Logger Service in the Angular application:

Step 1 – Create a New Application

Step 2 – Install ngx-logger and Its Dependencies

Step 3 – Create a Log Service

Step 4 – Create a Log Component

Step 5 – Update the App Module

Step 6 – Update the App Component (Optional)

 

Step 1 – Create a New Application

First, create a new angular application by hitting the following ng command:

ng new ngx-logger-example

 

Step 2 – Install ngx-logger and Its Dependencies

Next, we will install the NGX logger library and its dependencies in the application. Execute the following command to install the packages:

npm install ngx-logger --save
npm install @types/webpack-env --save-dev

 

Step 3 – Create a Log Service

Next, create a new log service which will capture and store log entries. For this create a new file named log.service.ts and put following content in it:

// log.service.ts
import { Injectable } from '@angular/core';
import { Logger } from 'ngx-logger';

@Injectable({
  providedIn: 'root',
})
export class LogService {
  logEntries: any[] = [];

  constructor(private logger: Logger) {
    this.logger.output.subscribe((logEntry) => {
      this.logEntries.push(logEntry);
    });
  }
}

 

Step 4 – Create a Log Component

Thereafter, we will create a exclusive component which sill display the log entries. Create a new file named log.component.ts and update it:

// log.component.ts
import { Component } from '@angular/core';
import { LogService } from './log.service';

@Component({
  selector: 'app-log',
  template: `
    <div *ngFor="let logEntry of logService.logEntries">
      <pre>{{ logEntry | json }}</pre>
    </div>
  `,
})
export class LogComponent {
  constructor(public logService: LogService) {}
}

 

Step 5 – Update the App Module

In this important step, we will update the App Module to provide our LogServer and configure the LoggerModule to use NGX Logger.

Open the app.module.ts file and update it as shown below:

// app.module.ts
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { LoggerModule, NgxLoggerLevel } from 'ngx-logger';

import { AppComponent } from './app.component';
import { LogComponent } from './log.component'; // Import the LogComponent
import { LogService } from './log.service'; // Import the LogService

@NgModule({
  declarations: [AppComponent, LogComponent], // Add LogComponent to declarations
  imports: [
    BrowserModule,
    LoggerModule.forRoot({
      serverLoggingUrl: '/api/logs', // Set your server-side logging URL
      level: NgxLoggerLevel.DEBUG,
      serverLogLevel: NgxLoggerLevel.ERROR,
    }),
  ],
  providers: [LogService], // Provide the LogService
  bootstrap: [AppComponent],
})
export class AppModule {}

 

Step 6 – Update the App Component (Optional)

In this optional step, we can add button control to show or hide the Logs on the view. Update the app.component.ts file:

// app.component.ts
import { Component } from '@angular/core';
import { Logger } from 'ngx-logger';

@Component({
  selector: 'app-root',
  template: `
    <h1>Hello, World!</h1>
    <button (click)="toggleLogDisplay()">Toggle Log</button>
    <app-log *ngIf="showLog"></app-log>
  `,
})
export class AppComponent {
  showLog: boolean = false;

  constructor(private logger: Logger) {}

  toggleLogDisplay() {
    this.showLog = !this.showLog;
  }
}

 

How I can switch to using the server log?

To switch the client-side logging to server-side with ngx-logger we need to set the serverLoggingUrl property in the forRoot() method in the app.module.ts file to the URL of your server-side logging endpoint:

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,
    LoggerModule.forRoot({
      serverLoggingUrl: '/api/logs',
      level: NgxLoggerLevel.DEBUG,
      serverLogLevel: NgxLoggerLevel.ERROR
    })
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule {}

We set the serverLoggingUrl property to '/api/logs'. Replace this value with the URL of your server-side logging endpoint.

We set the serverLogLevel property to NgxLoggerLevel.ERROR so that only log messages with a severity of ERROR or higher will be sent to the server. We can change this value to any of the log levels provided by ngx-logger: TRACE, DEBUG, INFO, WARN, ERROR, or FATAL.

The Logger service can be Injected into the component for logging the messages on the client-side as we already discussed:

import { Component } from '@angular/core';
import { Logger } from 'ngx-logger';

@Component({
  selector: 'app-root',
  template: '<h1>Hello, World!</h1>'
})
export class AppComponent {
  constructor(private logger: Logger) {
    this.logger.debug('Debug message');
    this.logger.info('Info message');
    this.logger.warn('Warn message');
    this.logger.error('Error message');
  }
}

Above, we are logging the messages using the debug(), info(), warn(), and error() methods. These messages will be sent to the server-side logging endpoint that we set up in the forRoot() method.

 

Conclusion

Logging on client or server-side by using the ngx-logger provides very essential feature to monitor and analyse the application behaviour specially on production environments.

We can easily centralize the location for log messages, server-side logging helps developers quickly diagnose and resolve issues. With ngx-logger, it is easy to configure server-side logging in Angular applications, which makes it makes it an handy tool for any development team.

Leave a Comment

Your email address will not be published. Required fields are marked *