Blog

Superpower Angular Logging with Elasticsearch, Logstash and Kibana — Part 2

#Angular

Illustration de Superpower Angular Logging with Elasticsearch, Logstash and Kibana — Part 2

alt text

Sending logs through the $log service can be very useful: for example, any uncaught exception in angular expressions is delegated to $exceptionHandler, which calls the $log.error method. If you have the $log decorator and the Logstash configuration presented in Part 1, a call to the Angular $exceptionHandler service involves sending the error log to Logstash.

But this method presents some important limits. Angular exceptions are not the only exceptions you can have in a front end application: a node module or a bower component might throw a general JavaScript runtime error or your Angular application might not start at all. In these cases, the $exceptionHandler is not called and the $log service cannot send logs to the server through Logstash.

Moreover, the $log service can send only the message error that the $exceptionHandler passes to it. The $log service can not access natively to the complete user actions trace, i.e. the list of user actions (e.g. mouse clicks, key pressing, URL change) which precede the error.

frontendlogger

To solve this problem, at DonkeyCode we have developed frontendlogger, a pure JS library to collect and send complete user actions traces to a server. This library collects user events (like clicks and key pressings) and sends their logs to the server only when it catches an error (like a syntax error), a critical event, an alert or an emergency. Logs sent to the server are composed of the last events logs (user click events, key pressing events, errors and custom events).

To use this library, you have to install it through npm:

npm install frontendlogger

After that, you have to include it with a script tag in your HTML file:

<script src="path_to_node_modules/frontendlogger/frontendlogger.js"></script>

You have to set the server URL (for example, the address to which the Logstash input plugin HTTP server listens to) before sending any log with the setServerUrl command:

frontendlogger.setServerUrl("http://localhost:8080");

To send logs containing user data, you can use the setUser command:

frontendlogger.setUser(user);

And you can also add custom events with the following methods:

  • frontendlogger.debug
  • frontendlogger.info
  • frontendlogger.notice
  • frontendlogger.warning
  • frontendlogger.error
  • frontendlogger.critical
  • frontendlogger.alert
  • frontendlogger.emergency

For example, we can define a critical event with the following code:

var event = {
  message = "This is a critical event!",
  eventType = "myCriticalEvent"
};
frontendlogger.critical(event);

If you want to read the Readme of the project and the code, go to the project page in GitHub!