Skip to content

Hosting startup for ApplicationInsights.Kubernetes

Saar Shen edited this page Sep 11, 2018 · 7 revisions

In ASP.NET Core 2.0, a new feature of Hosting environments is introduced. It can inject extra package dependencies and execute code during application startup, without the application needing to explicitly take a dependency or call any methods. Reference here for details.

In ApplicationInsights.Kubernetes v1.0.0-beta5, we introduced the NuGet Package, which implemented the IHostingStartup interface. Thus, once the following NuGet Package is added:

Install-Package Microsoft.ApplicationInsights.Kubernetes.HostingStartup -Version 1.0.0-*

Simply set the following environment variable to enable ApplicationInsights.Kubernetes:

ASPNETCORE_HOSTINGSTARTUPASSEMBLIES=Microsoft.ApplicationInsights.Kubernetes.HostingStartup

This is beneficial because in Kubernetes, it is very easy to set an environment variable. It could be in the Docker filer, it could be in the deployment yaml, etc.

Note: Before 1.0.0-beta6, steps are still needed to enable application insights. This won't be necessary after ASP.NET Core 2.0 Web Application, a simple way to do that is calling UseApplicationInsights() in BuildWebHost method of Program.cs:

        public static IWebHost BuildWebHost(string[] args) =>
            WebHost.CreateDefaultBuilder(args)
                .UseStartup<Startup>()
                .UseApplicationInsights()
                .Build();

And then set the application insights key with environment variable of APPINSIGHTS_INSTRUMENTATIONKEY. For example, in a deployment:

apiVersion: extensions/v1beta1
kind: Deployment
metadata:
  name: k8s-debugger
spec:
  replicas: 2
  template:
    metadata:
      labels:
        app: webapp
    spec:
      containers:
        - name: k8s-web
          image: saars/demoapp-in-k8s:0.1.11
          ports:
            - containerPort: 80
          env:
          - name: APPINSIGHTS_INSTRUMENTATIONKEY
            value: Your Application Insights Instrumentation Key
          - name: ASPNETCORE_HOSTINGSTARTUPASSEMBLIES
            value: Microsoft.ApplicationInsights.Kubernetes.HostingStartup

Let us know what do you think and always have fun!