问题
I have an angular project version 10.0.2 I want to log all errors on developer console to elastic search. When I catch an error on the global error handler my handler inside like this.
export class GlobalErrorHandlerService extends ErrorHandler {
constructor(private log: LogService) {
super();
}
handleError(error: any) {
var client = new Client();
if (error instanceof HttpErrorResponse) {
this.log.level = LogLevel.Error;
this.log.error("API/Back-End Proccess request error " + JSON.stringify(error), JSON.stringify(error));
}
else {
this.log.level = LogLevel.Warn;
this.log.warn("Client side error " + JSON.stringify(error), JSON.stringify(error));
}
this.log.publishers.push(error);
}
}
LogService is my custom log service. But I can change it to catch errors i send it elastic like this.
entry:
include error information
log(entry: LogEntry): Observable<boolean> {
var headers = new HttpHeaders();
const date = moment();
let body = {
"@timestamp": date,
"index": "clientapplication",
"body": {
"entry": entry,
"date": date
},
"user": {
"fullname": "ahmetu",
"userrecordno": "190909"
}
}
headers.append('Content-Type', 'application/json');
headers.append('Accept', 'application/json');
return this.hbhttp.post(`${this.location}/hbizclient/_doc`, body, headers)
}
i did this operation in log.elastic.ts
i writen custom a logging operation. my folder stracture as below
Actually i can logging all errors but i just want to learn. how can i use Elasticsearch own npm package then send all error from angular to elastic then i can see all of these on kibana
thanks for suggestions
回答1:
The @elastic/elasticsearch npm package is a NodeJS-only package so you won't be able to use it in your frontend Angular app. The reason being, it's not safe (and actually not even supported).
Giving public-ish access to your ES cluster such that people can inspect the ES queries is not recommended. Esp. something like
this.hbhttp.post(`${this.location}/hbizclient/_doc`...
because that looks like a live ES instance that may or may not be protected from malicious _search
queries that could bring down your cluster, or even DELETE
calls that may clear your logs altogether.
What you could do instead is to spin up a little nodejs backend log-forwarding service (GCP cloud function, AWS Lambda, Netlify, ...) which would utilize the @elastic/elasticsearch
package but sit behind a gateway which you can control. You'd then send post your POST /../_doc
to that service which'd forward the payload to ES.
来源:https://stackoverflow.com/questions/65319221/angular-errors-log-send-to-elasticsearch