Angular Logging Made Simple With Ngx-Logger - Onthecode
Angular Logging Made Simple With Ngx-Logger - Onthecode
uk/)
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
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.
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
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 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
TypeScript
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
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.
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.
disableConsoleLogging is a flag which helps you to turn console logging completely off.
Environment specific logging in Angular
For example, you may wish to only log errors in production environment while keeping all log
levels enabled in development environment.
TypeScript
@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 { }
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
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.
TypeScript
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:
{
"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
Post C o m m e n t
Do these logs print when you make an IPA, install it on iPhone and then
connect via XCode? We are having trouble doing that.
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
Like!! I blog quite often and I genuinely thank you for your information. The
article has truly peaked my interest.
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!
NGXLogger requires an Http client to post logs to APIs so you would need
to provide that dependency in your root/core module.
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?
Nope, it is still going strong! I have however started using Azure Application
insights for automatic logging!
how can we pass the payload from the angular, can you send the code snippet
, thanks for your response
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