Search code examples
azureazure-application-insightsnlog

Console App using NLog and MicrosoftApplicationInsights.NLogTarget


I have the following NLog.config for my .NET based Console App.

<targets>

  <target xsi:type="File" name="file" fileName="${basedir}/logs/${shortdate}.log"
        layout="${longdate} ${uppercase:${level}} ${message}" />

  <target xsi:type="Console" name="console" 
        layout="${longdate}|${uppercase:${level}}|${message}" />

</targets>

<rules>
  <!-- add your logging rules here -->
  <logger name="*" minlevel="Debug" writeTo="file" />
  <logger name="*" minlevel="Debug" writeTo="console" />
</rules>

I have followed instructions elsewhere and have installed Microsoft.ApplicationInsights.Web and everything works as expected, e.g.

var client = new TelemetryClient();

// logging a custom event using the AI API
client.TrackEvent("AppInsights is now ready for logging");
client.Flush();

This works alongside the NLog output to file and console. However as soon as I add Microsoft.ApplicationInsights.NLogTarget, all NLog console output and file output dissapears and doesn't appear in Application Insights either.

Any ideas? I've tried different settings in my NLog.config, setting targets for the Application Insights, nothing I do makes any difference.


Solution

  • After some research and assistance, I can figure this issue out: the data can be shown on console / file / application insights.

    1. You need to merge the nlog.config with the app.config(after install package Microsoft.ApplicationInsights.NLogTarget). After merging into app.config, you can remove the nlog.config or just leave it there.

    2. You should set the application insights instrument key by this way: TelemetryConfiguration.Active.InstrumentationKey = "xxxx";

    code like below:

        private static Logger logger = LogManager.GetCurrentClassLogger();
        static void Main(string[] args)
        {  
            var client = new TelemetryClient();
            TelemetryConfiguration.Active.InstrumentationKey = "xxxxxxxxxx";
    
            client.TrackEvent("0222: app insights now sending a custom event xxxxxx");
            logger.Trace("0222 Nlog :this is a trace message xxxxxx");
            logger.Debug("0222 Nlog: this is a debug message xxxxxx");
            logger.Info("0222 Nlog: this is a info message xxxxxx");
    
            Console.ReadLine();
        }
    

    Merge the nlog.config into app.config(after install the package Microsoft.ApplicationInsights.NLogTarget), so the new app.config looks like below(and you can then delete nlog.config or just leave it there):

    <?xml version="1.0" encoding="utf-8"?>
    <configuration>
        <configSections>
            <section name="nlog" type="NLog.Config.ConfigSectionHandler, NLog"/>
        </configSections>
        <startup> 
            <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5"/>
        </startup>
    
      <nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd"
          xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
          xsi:schemaLocation="http://www.nlog-project.org/schemas/NLog.xsd NLog.xsd"
          autoReload="true"
          throwExceptions="false"
          internalLogLevel="Off" internalLogFile="c:\temp\nlog-internal.log">
    
        <!-- optional, add some variables
      https://github.com/nlog/NLog/wiki/Configuration-file#variables
      -->
        <variable name="myvar" value="myvalue"/>
        <!--
      See https://github.com/nlog/nlog/wiki/Configuration-file
      for information on customizing logging rules and outputs.
       -->
        <extensions>
          <add assembly="Microsoft.ApplicationInsights.NLogTarget"/>
        </extensions>
        <targets>
          <target xsi:type="File" name="file" fileName="${basedir}/logs/${shortdate}.log"
              layout="${longdate} ${uppercase:${level}} ${message}" />
    
          <target xsi:type="Console" name="console"
                layout="${longdate}|${uppercase:${level}}|${message}" />
    
          <target xsi:type="ApplicationInsightsTarget" name="aiTarget"/>
        </targets>
    
        <rules>
          <logger name="*" minlevel="Trace" writeTo="file" />
          <logger name="*" minlevel="Trace" writeTo="console" />
          <logger name="*" minlevel="Trace" writeTo="aiTarget"/>
        </rules>
    
      </nlog>
    </configuration>
    

    Run your project, you can see the output in console and output window:

    enter image description here

    Then go to the logfile where you defined, you can see the log file is created and has the correct data.

    At last, nav to azure portal -> your app insights -> search, you can see the messages are there(it may take a few minutes):

    enter image description here

    Btw, how to check if the message can be sent to azure portal app insights:

    when run the project in visual studio, check the output window:

    if you see "Application Insights Telemetry (unconfigured):", it means that the instrument key is incorrect or not set correctly. it will be sent to app insights:

    enter image description here

    if it without the unconfigured, then it can be sent to app insights.