log4net Application Insights - not receiving all logs when deployed

25 Views Asked by At

I am using log4net to log data to application insights from my Windows Service. To do this I have the following packages:

  • log4net 2.0.12
  • Microsoft.ApplicationInsights.Log4NetAppender 2.22.0

I have setup the logger like so:

private ILog _logger = LogManager.GetLogger(typeof(MyServiceClass));

and this is setup to use a log4net.config file like so:

string assemblyFolder = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
XmlConfigurator.Configure(new FileInfo(Path.Combine(assemblyFolder, "log4net.config")));

For testing purposes when the service starts I am sending some messages at different levels.

_logger.Debug("This is debug message");
_logger.Info("This is info message");
_logger.Warn("This is warning message");
_logger.Error("This is error message");

Now when I run my application through Visual Studio debugging it works absolutely fine and all data is logged as per the screenshot below.

Application Insights Screenshot

The issue I am having is that when I install the service and run it, the only message I receive is the exception, none of the trace messages, as per the below screenshot.

Application Insights Screenshot 2 - Missing Traces

What have I done so far?

  1. Verified all dependencies and config files are correct (compared installed directory and debug directory - everything is identical)

  2. Enabled log4net internal debugging and there is no mention of any failures.

What can I try next? What could be causing this? Any advice is greatly appreciated.

The appender in my log4net config is below and the ApplicationInsights.config file is the default as came with the NuGet package apart from the updated connection string.

<appender name="aiAppender" type="Microsoft.ApplicationInsights.Log4NetAppender.ApplicationInsightsAppender, Microsoft.ApplicationInsights.Log4NetAppender">
    <layout type="log4net.Layout.PatternLayout">
        <conversionPattern value="%date [%thread] %-5level: %newline %message %newline %newline"/>
    </layout>
</appender>
1

There are 1 best solutions below

0
Ryan Thomas On

Okay, so in true software engineer fashion I have found the solution just after asking the question.

Going to post an answer in-case anyone comes here in the future.

The issue was that the logs were not getting flushed and therefore not sent.

I added the following in the OnStop() method of my service as well as the catch block in OnStart() and now all logs are visible.

LogManager.Flush(TimeSpan.FromSeconds(3).Milliseconds);

However I am not sure why this was only effective the deployed application.