Ajay
5 min readMar 1, 2021

--

Application Insights using Azure and VueJs — Error handling and Event Logging in Front End to avoid Console.log in Production

In case you are logging FE Errors using Console.logs, and want to avoid them being seen in Production to end users in their browser console, you would be looking an elegant solution to achieve this.

Here are my findings to do better Error Handling and also log custom Events that are of business/functional importance which will help both Devs and Business to track and improve the app, Proactively.

Requirements:

  • Handle Errors gracefully in Front End and log them into a third party system (and not our own Back End / Database) which is available even when the Back End is down
  • Log important Front End/User/custom events based on technical and business requirements to know the user and application behavior and fix the UI problems proactively
  • Console.log is OK for Development but not for Production. So it has to be configurable per environment.
  • Collect other analytics like browsers, geography, user flow etc to take important technical and functional decisions by business and stakeholders
  • Minimal setup which works in VueJs based Single Page app easily

Candidates:

Some of the most popular Javascript based logging solutions are Winston, Log4Js, Bunyan, Debug etc. I started looking into all of them. Some are pretty simple to start with like Debug and Log4Js, and some are really state of the art like Winston and Bunyan.

And for writing the logs to a Remote system, i found that my org has following offerings:

  • Azure App Insights
  • AppDynamics
  • Splunk
  • UpTrends

Selection:

As i had previous experience with Winston, and it happens to be one of the most popular and feature-rich logging library for NodeJs (and also Browser based JS apps), i shortlisted it for FE logging.

And for remote system to send those logs to, i selected Azure App Insights as its easy to start with, as it also offers SPA specific SDK, has huge variety of analytics and its based on Cloud which i could use straight away without creating any special request to another team for making a account.

Pros:

  • Winston can do various Levels of logging like errors/info/debug
  • Winston highly configurable and hence can do environment specific logging with help of Transports

Cons:

  • It was difficult to integrate Winston with and SPA like that of VueJs without writing extra logic for environment specific configs/transport and integrating with Router
  • I could not find any Out of the Box solution to create a simple transport using Azure App Insight and Winston

So i started looking for VueJs + Azure App insight specific libraries and chose to not use any state of the art library for logging purpose. This also gave me flexibility to write custom error/info objects to remote system without too much formatting fuss.

After doing some research, i finalized https://www.npmjs.com/package/vue-application-insights which is the simplest solution i could find meeting all of my requirements.

Solution:

  • Reach out to your DevOps contact person for Enabling Azure App Insights for your application and also get the App Key (also called Instrumentation Key).
  • Use (or better Inject at runtime thru env configs) environment specific APP KEY in your Front End code. Similar to below:
if (process.env.NODE_ENV === ‘development’) {
APP_INSIGHTS_KEY = ‘’; // no logging to remote in dev mode. if you prefer to see an Exception in Console, leave this as null or undefined.
}
//Prodelse if (process.env.NODE_ENV === ‘production’){
APP_INSIGHTS_KEY = ‘prod_env_app_insight_key’; // get from your app’s Azure portal
}
  • Setup Vue Application Insights library while loading Vue app like following in Main.js:
import VueAppInsights from “vue-application-insights”;
import {APP_INSIGHTS_KEY} from “@/constant/constant”;
Vue.use(VueAppInsights, { id: APP_INSIGHTS_KEY, router});

*ensure that APP_INSIGHTS_KEY is already initiated per the Environment before above is called, else it would be null and you may see exception in console

  • Write a common service that would log Events/Exceptions to remote using Azure App Insights api to suit your need. Similar to following:
logErrorsAndExceptions(location, error) {if (this.$appInsights && this.$appInsights.trackException && APP_INSIGHTS_KEY) { this.$appInsights.trackException({  exception: new Error(location),  properties: error });} else {console.error (location, ‘:’, error)}},logInfoAndDebug(location, message) { if (this.$appInsights && this.$appInsights.trackEvent &&  APP_INSIGHTS_KEY) { this.$appInsights.trackEvent({ name: location, properties: message });} else { console.log(location, ‘:’, message)}}
  • Now, you can start sending custom events/message on important business/functional milestones. e.g. when user has requested for a specific file or reported an incident
  • Or you can send Errors/Exceptions details e.g. when API gives invalid output or fails altogether after some timeout period.
try {
// call api, get response, try to get nested object, get null exception or timeout etc
} catch (error) {
this.
logErrorsAndExceptions(‘approvedList.getReviewDataSets.error’, error);
}

Now, when you encounter above error you should see a ‘track’ call made to Azure service with your app key and possibly a valid response from that service that your data is recorded in App Insights.

Output:

I was able to send custom Events and Errors/Exceptions details to App Insights. With this, business can create dashboards and alerts/automated workflows to take proactive corrective actions rather than doing reactive fixes.

Also extra information like user flow and bottlenecks, conversions etc can be tracked easily.

--

--

Ajay

Javascript, Angular, Vue. Web App is all what I Do. And sometimes getting bored, i write articles and poems too!