0% found this document useful (0 votes)
78 views

Angular Logging Made Simple With Ngx-Logger - Onthecode

Angular Logging Made Simple with ngx-logger
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
78 views

Angular Logging Made Simple With Ngx-Logger - Onthecode

Angular Logging Made Simple with ngx-logger
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 13

(https://onthecode.co.

uk/)

Home (https://onthecode.co.uk/) Blog (https://onthecode.co.uk/blog)

About (https://onthecode.co.uk/about)  (https://onthecode.co.uk/#)

Angular Logging Made Simple with


ngx-logger

Privacy - Terms
 Umut Esen (https://onthecode.co.uk/blog/author/umutesen)  11 mins read
 16 Comments (https://onthecode.co.uk/blog/angular-logging-made-easy-with-ngx-
logger#comments)

 4 likes

In my previous post (https://onthecode.co.uk/handle-all-errors-in-your-angular-app/), I talked


about catching all errors in Angular with a global error handler. If you want to keep the errors
you capture, you need to implement a reliable logging mechanism. Today, I want to explain
how to enable Angular logging in your applications with ngx logger
(https://github.com/dbfannin/ngx-logger) package.

Importance of logging

As a developer, you are responsible for every line of code you write. If a bug surfaces in the
application, you need to pinpoint the issue and provide a fix for it.

Undoubtedly, this is easier said than done within a real-world project. In most cases, it can
take hours (if not days) to reproduce the issue before you can even fix it.

When implemented properly, logging can save your as* big time. Not only will logging save
you hours of debugging in the long run but also give you confidence about your solutions.

Basic logging in JavaScript

Logging in vanilla JavaScript (/blog/category/javascript) is pretty simple – just use the console
object as shown below.

JavaScript

console.log('info log');
console.warn('warning log');

Although very simple, the console logging can limit what you can do with your logs. Think
about it, you are going to be adding log statements all over the project.

What if…
you want to disable logging temporarily
enable logging only in production
ignore certain log levels
send logs to server

It is possible to implement these requirements by hand. You could provide it as a service in


your Angular application.

However, infrastructure concerns like logging are essential in any application and you
shouldn’t really spend your time building and maintaining these features. Unless there are
strict company policies, you should make use of libraries instead of re-inventing the wheel.

Getting started with ngx-logger

ngx-logger (https://github.com/dbfannin/ngx-logger) is a very simple logging library for


Angular applications.

It offers the following features:

Pretty printing to the console


Enable logging based on the level specified
Control log level based on the current environment
Send log messages to server via HTTP for centralised logging
Indicates log location and line number

Getting up and running with ngx-logger is easy, just create a new Angular app
(https://onthecode.co.uk/getting-started-with-angular-7/) and pull the package from npm:

Bash

npm install ngx-logger

Import the library in the root module i.e. app.module.ts :

TypeScript

import { LoggerModule, NgxLoggerLevel } from 'ngx-logger';

Finally, import LoggerModule.forRoot in your application module. This is where we can configure
the logger:
TypeScript

@NgModule({
imports: [
BrowserModule,
HttpClientModule,
LoggerModule.forRoot({
serverLoggingUrl: 'http://localhost:68552/', // Replace with YOUR API
level: NgxLoggerLevel.TRACE,
serverLogLevel: NgxLoggerLevel.ERROR,
disableConsoleLogging: false
})
],
declarations: [AppComponent],
bootstrap: [AppComponent]
})
export class AppModule { }

With the above configuration in place, we can start logging anywhere in the application.

TypeScript

export class AppComponent {


constructor(private logger: NGXLogger) {
this.logger.debug("Debug message");
this.logger.info("Info message");
this.logger.log("Default log message");
this.logger.warn("Warning message");
this.logger.error("Error message");
}
}

Here we are injecting the NGXLogger as a dependency to the component class, giving us
access to the NGXLogger instance.

When you run the application, you will see the log messages in the browser console.
Console Output from ngx-logger

You will notice that there are errors relating to the server-side logging. This is because we
told ngxlogger to send errors to the server at /api/logs end-point. Since this URL does not
exist, we get an error message.

Angular logging configuration

Let’s take a closer look at the configuration object:

TypeScript

LoggerModule.forRoot({
serverLoggingUrl: 'http://localhost:68552/', // Replace with YOUR API,
level: NgxLoggerLevel.TRACE,
serverLogLevel: NgxLoggerLevel.ERROR,
disableConsoleLogging: false
})

level defines the minimum log level in the browser. Available levels are: TRACE, DEBUG, INFO,
LOG, WARN, ERROR, FATAL and OFF. These values come from NgxLoggerLevel class.

serverLoggingUrl is where you give the full path to your api end-point for logging to server.
This is optional, if you don’t need logs to be sen’t to server, delete this line.

serverLogLevel defines the minimum log level for server-side logging.

disableConsoleLogging is a flag which helps you to turn console logging completely off.
Environment specific logging in Angular

A common requirement in a real-wold application is environment specific logging. This simply


means that you want to configure logging differently, depending on the environment the app
is running.

For example, you may wish to only log errors in production environment while keeping all log
levels enabled in development environment.

To do this, we need to use environment variables of our Angular application.

Let’s import environment object in app.component.ts , which allows us to initialise logging


configuration with environment-specific details.

TypeScript

import { environment } from 'src/environments/environment';

@NgModule({
imports: [
BrowserModule,
HttpClientModule,
LoggerModule.forRoot({
serverLoggingUrl: `${environment.apiUrl}api/logs`,
level:environment.logLevel,
serverLogLevel: environment.serverLogLevel,
disableConsoleLogging: false
})
],
declarations: [AppComponent],
bootstrap: [AppComponent]
})
export class AppModule { }

There are two environments in a cli-generated Angular application: development and


production . These environments are defined in the Angular.json file, and located under src
folder of the project.

The idea is that the same variable exists in each environment file, providing different values
corresponding to the environment.
Let’s update the development environment:

TypeScript

import { NgxLoggerLevel } from 'ngx-logger';

export const environment = {


production: false,
apiUrl: 'http://localhost:68552/', // Replace with local API
logLevel: NgxLoggerLevel.WARN,
serverLogLevel: NgxLoggerLevel.OFF
};

When you run the application with ng serve , the development environment configuration will
be used: only the warn logs & above will be logged on the browser. The server-side logging is
turned off as we just want to see the errors in the console during development.

Let’s also update the production environment (environment.prod.ts):

TypeScript

import { NgxLoggerLevel } from 'ngx-logger';

export const environment = {


production: true,
apiUrl: 'http://api.myservice.com/api/', // Replace with remote API
logLevel: NgxLoggerLevel.OFF,
serverLogLevel: NgxLoggerLevel.ERROR
};

Our production configuration states that there will be no browser logging and only errors will
be logged to the server at the specified API URL.

You can test this by starting your application in production mode via ng serve --
configuration=production .

Logging to server

Logging in Angular happens within the browser of each user, which we cannot access.
Sending logs to the server allows us to store them somewhere safe like log files or even a
database.
I think this is the most useful feature of ngx-logger .

In order for this feature to work, you need an API that exposes a POST endpoint for accepting
a log object.

ngx-logger POST s an object for each log message your API endpoint.

For example:

JSON / JSON with Comments

{
"level": 5,
"additional": [],
"message": "Error",
"timestamp": "2020-02-02T11:42:40.153Z",
"fileName": "main.js",
"lineNumber": 87,
"columnNumber": 26
}

Please ensure you import HttpClientModule and set the serverLoggingUrl correctly.

Your API implementation will vary depending on the server stack. Here is an example
endpoint for .NET Core Web API :

C#

[HttpPost]
public IActionResult Post([FromBody] LogDto dto)
{
var msg = $"MESSAGE: {dto.Message} - " +
$"FILE: {dto.FileName} - " +
$"LEVEL: {dto.Level} - " +
$"LINENUMBER: {dto.LineNumber} - " +
$"TIMESTAMP: {dto.Timestamp:F}" +
$"USER: {User.Identity.Name}";
_logger.LogError(msg);
return Ok();
}
And there you have it! You can checkout the code on GitHub
(https://github.com/umutesen/angular-ngx-logger-demo).

I would like to find out how you perform logging in your apps, let me know in the comments.

Umut Esen
(Https://Onthecode.Co.Uk/Blog/Author/Umutesen)
Software Engineer specialising in full-stack web application

(https://onthecode.co.uk/blog development.

/author/umutesen)

Leave a Reply

Your comment here...

Name (required) E-mail (required) Website

 Notify me via e-mail if anyone answers my comment.

Post C o m m e n t

 THIS POST HAS 16 COMMENTS

Asif FEBRUARY 9, 2022 REPLY

Do these logs print when you make an IPA, install it on iPhone and then
connect via XCode? We are having trouble doing that.

Umut Esen (https://onthecode.co.uk) FEBRUARY 15, 2022 REPLY


Unfortunately no, I would suggest something like Azure Application Insights
(https://onthecode.co.uk/monitoring-live-angular-apps-with-azure-
application-insights/).

Mikec711 NOVEM BER 25, 2021 REPLY

So, config question (may be more angular scoped but) … a customer calls and i
want to change the log level for that customer. Can I have the customer export
(unix) into their own environment and pick it up from there? ie: i want customer
A to go to debug but want the rest of the world to stay at warning. Thanks

Terry J. Davis JUNE 10, 2021 REPLY

Just pulled down the app. I’m running Angular 9.


this.logger.debug does not write to the console. I have to use this.logger.warn
instead.
environment.ts:
export const environment = {
production: false,
name: ‘dev’,
logLevel: NgxLoggerLevel.DEBUG,
serverLogLevel: NgxLoggerLevel.OFF
};
app.module.ts:
LoggerModule.forRoot({
level: environment.logLevel,
serverLogLevel: environment.serverLogLevel,
disableConsoleLogging: false
})

Taufique FEBRUARY 27, 2021 REPLY


Hello Umut Esen,
I have followed line by line everything is working for me, but my concern is that
I want to send these logs to the node server please help me if possible.

ปั้มไลค์ (https://www.xn--42c9bsq2d4f7a2a.com/) JULY 4, 2020 REPLY

Like!! I blog quite often and I genuinely thank you for your information. The
article has truly peaked my interest.

Asad Naeem M AY 27, 2020 REPLY

After following your example line by line. I found these errors in the browser. I
am using Angular 9.
core.js:6185 ERROR NullInjectorError: R3InjectorError(AppModule)[NGXLogger
-> NGXMapperService -> HttpBackend -> HttpBackend -> HttpBackend]:
NullInjectorError: No provider for HttpBackend!

Umut Esen (https://onthecode.co.uk) JULY 20, 2020 REPLY

NGXLogger requires an Http client to post logs to APIs so you would need
to provide that dependency in your root/core module.

Neeraj OCTOBER 3, 2021 REPLY

Any Update, I am also facing same issue, i want to call my interceptor


but due to HttpBackend its skipping my interceptor.

Elijah SEPTEM BER 7, 2021 REPLY

I’m learning this, what was the exact solution to getting past this
NullInjectorError?
amit APRIL 19, 2020 REPLY

I tried with latest `ngx-logger` npm and somehow I’m not getting an error that
POST http://localhost:4200/api/logs/ (http://localhost:4200/api/logs/) not
found.
Is this dependent on specific version?

StormTroopersBrother M ARCH 24, 2020 REPLY

Looks like it’s deprecated?


https://www.npmjs.com/package/ngx-logger
(https://www.npmjs.com/package/ngx-logger)

Umut Esen (https://onthecode.co.uk) M AY 28, 2020 REPLY

Nope, it is still going strong! I have however started using Azure Application
insights for automatic logging!

gaurav M ARCH 15, 2020 REPLY

how can we pass the payload from the angular, can you send the code snippet
, thanks for your response

gaurav M ARCH 12, 2020 REPLY

our api is of get or post ? my api is not getting called , can you help
Umut Esen (https://onthecode.co.uk) M ARCH 15, 2020 REPLY

Thanks for your comment. I have added an example POST API


(htt
implementation in the post. ps:/
/sta
(htt cko (htt
ps:/ verf ps:/
/lin low. /git
ked co hub
in.c m/u
Home (https://onthecode.co.uk/) om/ser .co
m/u
Blog (https://onthecode.co.uk/blog) in/u s/2 mut
mut 093 ese
About (https://onthecode.co.uk/about) ese 029 n)
n) /um
ute
sen
Copyright © 2023 onthecode. All rights reserved.
)

You might also like