angular errors log send to elasticsearch

Viewed 1651

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

My folder stracture

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 Answers

The @elastic/elasticsearch npm package is a NodeJS-only package so you won't be able to use it in your frontend Angular app. It's not safe and thus not supported.

Giving public-ish access to your ES cluster such that people can inspect the underlying ES queries is not recommended. Esp. calls like

this.http.post(`${this.location}/hbizclient/_doc`...

because that endpoint 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 worse, DELETE calls that could clear your logs altogether.

Instead, you could spin up a tiny nodejs 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 your POST /../_doc requests to that service and it'd forward them to ES.

Related