Skip to content

Commit

Permalink
added interceptor logging
Browse files Browse the repository at this point in the history
  • Loading branch information
nasraldin committed Jul 27, 2020
1 parent e5713fd commit 9f465e6
Show file tree
Hide file tree
Showing 10 changed files with 209 additions and 26 deletions.
8 changes: 8 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,11 @@ NGX N Logger is a simple logging module for angular (v6 and above). It allows "p

<img src="https://raw.githubusercontent.com/nasraldin/ngx-n-logger/master/img/ngx-n-logger.png">

- Interceptor Logging
<img src="https://raw.githubusercontent.com/nasraldin/ngx-n-logger/master/img/interceptor1.jpg">

<img src="https://raw.githubusercontent.com/nasraldin/ngx-n-logger/master/img/interceptor2.jpg">

# Key Features:

- 📌 Log Levels Labels (All, Debug, Info, Warn, Error, Fatal, Off)
Expand All @@ -16,6 +21,7 @@ NGX N Logger is a simple logging module for angular (v6 and above). It allows "p
- 📌 Debug RxJS Observable Stream using debugOperator() operator function
- 📌 Can configure each setting
- 📌 Environment Specific Log Level Restriction. eg. if you set logLevel to LogLevel.WARNING, it will only show logs for WARNING and ERROR
- 📌 Interceptor Logging
- 📌 .....

## Options will support in next release
Expand Down Expand Up @@ -48,11 +54,13 @@ The only remaining part is to list the imported module in your application modul
...,
NgxNLoggerModule,
// NgxNLoggerModule.forRoot({
// enableInterceptorLogging: true,
// isProduction: false,
// applicationName: 'Ngx N Logger',
// showStyles: false,
// showLabel: true,
// showTime: true,
// textColor: { [LoggerLevel.Debug]: 'red', [LoggerLevel.Info]: '#fff' },
// }),
]
bootstrap: [AppComponent]
Expand Down
Binary file added img/interceptor1.jpg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added img/interceptor2.jpg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
3 changes: 3 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -44,5 +44,8 @@
"ts-node": "~8.3.0",
"tslint": "~6.1.0",
"typescript": "~3.9.5"
},
"publishConfig": {
"registry": "https://npm.pkg.github.com/"
}
}
108 changes: 97 additions & 11 deletions projects/ngx-n-logger/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,23 +2,109 @@

This library was generated with [Angular CLI](https://github.com/angular/angular-cli) version 10.0.5.

## Code scaffolding
NGX N Logger is a simple logging module for angular (v6 and above). It allows "pretty print" to the console, as well as make debugging easier with more readable and full configurable fancy logs.

Run `ng generate component component-name --project ngx-n-logger` to generate a new component. You can also use `ng generate directive|pipe|service|class|guard|interface|enum|module --project ngx-n-logger`.
> Note: Don't forget to add `--project ngx-n-logger` or else it will be added to the default project in your `angular.json` file.
<img src="https://raw.githubusercontent.com/nasraldin/ngx-n-logger/master/img/ngx-n-logger.png">

## Build
- Interceptor Logging

Run `ng build ngx-n-logger` to build the project. The build artifacts will be stored in the `dist/` directory.
<img src="https://raw.githubusercontent.com/nasraldin/ngx-n-logger/master/img/interceptor1.jpg">

## Publishing
<img src="https://raw.githubusercontent.com/nasraldin/ngx-n-logger/master/img/interceptor2.jpg">

After building your library with `ng build ngx-n-logger`, go to the dist folder `cd dist/ngx-n-logger` and run `npm publish`.
# Key Features:

## Running unit tests
- 📌 Log Levels Labels (All, Debug, Info, Warn, Error, Fatal, Off)
- 📌 Config isProduction, Can Disable all Logs
- 📌 Show/Hide Styles, Log Time, Labels, Emoji 😎 for each log level,
- 📌 Log Level colors and emojis are configurable
- 📌 Show Header on console configurable
- 📌 Debug RxJS Observable Stream using debugOperator() operator function
- 📌 Can configure each setting
- 📌 Environment Specific Log Level Restriction. eg. if you set logLevel to LogLevel.WARNING, it will only show logs for WARNING and ERROR
- 📌 Interceptor Logging
- 📌 .....

Run `ng test ngx-n-logger` to execute the unit tests via [Karma](https://karma-runner.github.io).
## Options will support in next release

## Further help
- 📌 log writers to Endpoint, Loggly, Logstash, LocalStorage, Files

To get more help on the Angular CLI use `ng help` or go check out the [Angular CLI README](https://github.com/angular/angular-cli/blob/master/README.md).
## Dependencies

- @angular/common
- @angular/core

## Installation

```shell
npm install --save ngx-n-logger
```

Once installed you need to import our main module:

```typescript
import { NgxNLoggerModule } from 'ngx-n-logger';
```

The only remaining part is to list the imported module in your application module, passing in a config to intialize the logger.

```typescript
@NgModule({
...,
imports: [
...,
NgxNLoggerModule,
// NgxNLoggerModule.forRoot({
// enableInterceptorLogging: true,
// isProduction: false,
// applicationName: 'Ngx N Logger',
// showStyles: false,
// showLabel: true,
// showTime: true,
// textColor: { [LoggerLevel.Debug]: 'red', [LoggerLevel.Info]: '#fff' },
// }),
]
bootstrap: [AppComponent]
})
export class AppModule {
}
```

## Usage

To use the Logger, you will need import it locally, then call one of the logging functions

```typescript
import { Component } from '@angular/core';
import { NgxNLoggerService } from 'ngx-n-logger';

@Component({
selector: 'your-component',
templateUrl: './your.component.html',
styleUrls: ['your.component.scss'],
})
export class YourComponent {
info = {
auther: {
email: '[email protected]',
website: 'http://nasraldin.com',
twitter: 'https://twitter.com/_nasraldin',
},
git: 'https://github.com/nasraldin/ngx-n-logger',
npm: 'https://www.npmjs.com/package/ngx-n-logger',
};

constructor(private logger: NgxNLoggerService) {
logger.clear();
logger.header('ngx-n-logger is running! - faster logging 😎');
logger.log(this.info);
logger.debug('log debug', this.info);
logger.info('log info', this.info);
logger.warn('log warn', this.info);
logger.error('log error', this.info);
logger.fatal('log fatal', this.info);
logger.trace('log trace', this.info);
logger.table('log trace', this.info);
}
}
```
2 changes: 1 addition & 1 deletion projects/ngx-n-logger/package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "ngx-n-logger",
"version": "0.0.1",
"version": "0.0.2",
"description": "ngx-n-logger is part of n-console",
"author": {
"name": "Nasr Aldin",
Expand Down
13 changes: 7 additions & 6 deletions projects/ngx-n-logger/src/lib/logger.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,13 +6,14 @@ export class LoggerConfig {
isProduction?: boolean;
environment?: string;
logLevel ? = LoggerLevel.All;
enableInterceptorLogging ? = false;
showStyles ? = true;
showTime ? = true;
showEmoji ? = true;
showLabel ? = true;
disableLogs ? = false;
fontSize?: number;
textColor?: {
labelColor?: {
[logLevel: number]: string;
} = {};
bgColor?: {
Expand All @@ -24,12 +25,12 @@ export class LoggerConfig {
}

export const DefaultColors = {
[LoggerLevel.Trace]: '#000000',
[LoggerLevel.Trace]: '#fff',
[LoggerLevel.Debug]: '#000000',
[LoggerLevel.Info]: '#000000',
[LoggerLevel.Warn]: '#000000',
[LoggerLevel.Error]: '#000000',
[LoggerLevel.Fatal]: '#000000',
[LoggerLevel.Warn]: '#fff',
[LoggerLevel.Error]: '#fff',
[LoggerLevel.Fatal]: '#fff',
};

export const DefaultLableColors = {
Expand All @@ -42,7 +43,7 @@ export const DefaultLableColors = {
};

export const DefaultBGColors = {
[LoggerLevel.Trace]: '#000080',
[LoggerLevel.Trace]: '#e42c64',
[LoggerLevel.Debug]: '#00BFFE',
[LoggerLevel.Info]: '#1ee3cf',
[LoggerLevel.Warn]: '#FF6419',
Expand Down
66 changes: 66 additions & 0 deletions projects/ngx-n-logger/src/lib/ngx-n-logger.interceptor.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
import {
HttpEvent,
HttpHandler,
HttpInterceptor,
HttpRequest,
HttpResponse,
} from '@angular/common/http';
import { finalize, tap } from 'rxjs/operators';

import { Injectable } from '@angular/core';
import { Observable } from 'rxjs';

@Injectable()
export class NgxNLoggerInterceptor implements HttpInterceptor {
intercept(
req: HttpRequest<unknown>,
next: HttpHandler,
): Observable<HttpEvent<unknown>> {
const startTime = Date.now();
let status: string;
let response: any;
let errors: any;

return next.handle(req).pipe(
tap(
(event) => {
if (event instanceof HttpResponse) {
status = 'Succeeded';
response = event;
}
},
(error) => {
status = 'Failed';
errors = error;
},
),
finalize(() => {
const elapsedTime = Date.now() - startTime;
const message =
req.method +
' ' +
req.urlWithParams +
' ' +
status +
' in ' +
elapsedTime +
'ms';

this.logDetails(message);
if (response) {
this.logDetails(response);
}
if (errors) {
this.logDetails(errors);
}
}),
);
}
private logDetails(msg: any): void {
console.log(
`%c👁‍🗨 [DEBUG] Interceptor Logging @ ${new Date().toLocaleTimeString()}`,
'background-color:#00BFFE;font-weight:bold',
msg,
);
}
}
18 changes: 17 additions & 1 deletion projects/ngx-n-logger/src/lib/ngx-n-logger.module.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,20 @@
import { ModuleWithProviders, NgModule } from '@angular/core';

import { HTTP_INTERCEPTORS } from '@angular/common/http';
import { LoggerConfig } from './logger.config';
import { NgxNLoggerInterceptor } from './ngx-n-logger.interceptor';
import { NgxNLoggerService } from './ngx-n-logger.service';

export function enableInterceptorLogging(config: LoggerConfig): any {
if (config.enableInterceptorLogging) {
return {
provide: HTTP_INTERCEPTORS,
useClass: NgxNLoggerInterceptor,
multi: true,
};
}
}

@NgModule({
providers: [NgxNLoggerService],
})
Expand All @@ -13,8 +25,12 @@ export class NgxNLoggerModule {
return {
ngModule: NgxNLoggerModule,
providers: [
{ provide: LoggerConfig, useValue: config || {} },
{
provide: LoggerConfig,
useValue: config || {},
},
NgxNLoggerService,
enableInterceptorLogging(config),
],
};
}
Expand Down
17 changes: 10 additions & 7 deletions projects/ngx-n-logger/src/lib/ngx-n-logger.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -59,13 +59,13 @@ export class NgxNLoggerService {
}

private getStyles = (level: LoggerLevel) =>
`font-size: ${this.config.fontSize || 13}px; color:${
DefaultColors[level]
}; background-color:${
this.config.bgColor[level] || DefaultBGColors[level]
}; padding: 0px 2px; border-radius: 2px`;
`font-size: ${this.config.fontSize || 13}px;
color: ${this.config.labelColor[level] || DefaultColors[level]};
background-color: ${this.config.bgColor[level] || DefaultBGColors[level]};
padding: 0px 2px; border-radius: 2px`

private labelColors = (level: LoggerLevel) => `color:${DefaultLableColors[level]};`;
private labelColors = (level: LoggerLevel) =>
`color: ${this.config.labelColor[level] || DefaultLableColors[level]};`

private logger(level: LoggerLevel, ...args: any[]): void {
if (this.config.isProduction) {
Expand Down Expand Up @@ -165,5 +165,8 @@ export class NgxNLoggerService {
debugOperator = <T>(
message?: string,
logLevel = LoggerLevel.Debug,
): MonoTypeOperatorFunction<T> => tap((data) => { this.logger(logLevel, message || '', data); })
): MonoTypeOperatorFunction<T> =>
tap((data) => {
this.logger(logLevel, message || '', data);
})
}

0 comments on commit 9f465e6

Please sign in to comment.