简体   繁体   中英

Can I override message object in ngx-logger

Is it possible to have ngx-logger use a different object to log? Currently all logs are based on the NGXLogInterface below:

export class NGXLogInterface {
  level: NgxLoggerLevel;
  timestamp: string;
  fileName: string;
  lineNumber: string;
  message: string;
  additional: any[];
}

However I need to send my logs to an API which is expecting a body like the one below:

{
  "application": "string",
  "component": "string",
  "area": "string",
  "level": "string",
  "details": "string",
  "executingUser": "string",
}

// this service responsible to send the request is NGXLoggerHttpService so you must provide another one to change the signature of the model.

1 - add the override the service in the same module which you instantiate the LoggerModule ==> LoggerModule.forRoot() ....

2 - Write the new service in charge ton send the request by extending the original one and overriding the logOnServer method

providers: [
  {provide: NGXLoggerHttpService, useClass: MyLoggerHttpService, multi: false}
]

@Injectable()
export class MyLoggerHttpService extends NGXLoggerHttpService {
  public constructor(private readonly _http: HttpBackend) {
    super(_http);
  }
  public logOnServer(url: string, log: NGXLogInterface, options: object): Observable<any> {
    const value: any = JSON.parse(log.message);
    return super.logOnServer(url, value as any, options );
  }

}

You need to customise the body in the logger by overriding the NGXLoggerServerService

Example :

@Injectable()
export class ServerCustomisedService extends NGXLoggerServerService {

  /**
   * Customse the data sent to the API
   * @param metadata the data provided by NGXLogger
   * @returns the data customised
   */
  public customiseRequestBody(metadata: INGXLoggerMetadata): any {
    let body = // edit the body as you like

    return body;
  }
}

And then provide your customised service, see how in the doc : https://github.com/dbfannin/ngx-logger/blob/master/docs/customising.md#example-adds-a-property-to-the-server-log

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM