In my previous post I’ve described how to use Application Insights and use it within your new web application. Most of us aren’t working in a greenfield project, so new solutions have to be integrated with the old.

The project I’m working on uses log4net for logging messages, exceptions, etc. In order for us to use Application Insights, we had to search for a solution to integrate both. After having done some research on the subject we discovered this wasn’t a big problem.

The software we are working on are Windows Services and Console Applications, so we should not add the Application Insights package for web applications. For these kind of applications it’s enough to just add the core package to your project(s).

image_thumb7

Once added, we are creating the TelemetryClient in the Main of the application.

private static void Main(string[] args)
{
	var telemetryClient = new TelemetryClient { InstrumentationKey = "[InstrumentationKey]" };

	/*Do our application logic*/

	telemetryClient.Flush();
}

You will notice we are setting the InstrumentationKey property explicitly. That’s because we don’t use an ApplicationInsights.config file, like in the web application example and this key has to be specified in order to start logging.

This final flush will make sure all pending messages will be pushed to the Application Insights portal right away.
Now you might not see your messages in the portal right away. We discovered this while testing out the libraries. The reason for this is probably due to some caching in the portal or all messages being handled by some queue mechanism on the backend (assumption on my behalf). So don’t be afraid, your messages will show up within a few seconds/minutes.

After having wired up Application Insights, we still had to add it to log4net. When browsing through the nuget packages we noticed the Log4NetAppender for Application Insights.

After having added this package to our solution, the only thing we had to do is creating a new log4net appender to the configuration.

<root>
    <level value="INFO" />
    <appender-ref ref="LogFileAppender" />
    <appender-ref ref="ColoredConsoleAppender" />
    <appender-ref ref="aiAppender" />
</root>
<appender name="aiAppender" type="Microsoft.ApplicationInsights.Log4NetAppender.ApplicationInsightsAppender, Microsoft.ApplicationInsights.Log4NetAppender">
    <layout type="log4net.Layout.PatternLayout">
        <conversionPattern value="%message%newline" />
    </layout>
</appender>

This appender will make sure all log4net messages will be sent to the Application Insights portal.

As you can see, adding Application Insights to existing software is rather easy. I would really recommend using one of these modern, cloud based, logging solutions. It’s much easier to use this compared to ploughing through endless log files on the disks or creating your own solution.

comments powered by Disqus