Search code examples
vb.netazure-application-insightsnlog

Failed to Create Target with Unknown Type-Alias 'ApplicationInsightsTarget' in Release Mode


I'm writing in VB.NET and trying to connect the logging of my WPF application with NLog and Azure Application Insights. I've set everything up, and it works perfectly in debug mode. However, when I switch to release mode or deploy it, it doesn't work. In the NLog log file, I get the following error: 'Failed to create Target with unknown type-alias: 'ApplicationInsightsTarget' - Verify type-alias and check extension is included'. I've used the following packages:

  • Microsoft.ApplicationInsights

  • Microsoft.ApplicationInsights.NLogTarget

  • Microsoft.Extensions.Logging

  • NLog.Extensions.Logging

  • NLog

However, in release mode, it writes to the NLog file without any issues. The .dll files are present in both release and debug mode in the bin folder.

{
  "ActivateExtendedLogging": true,
  "NLog": {
    "internalLogLevel": "Info",
    "internalLogFile": "${basedir}/InternalLogFile/LoggingMessages-nlog.txt",
    "targets": {
      "aiTarget": {
        "type": "ApplicationInsightsTarget",
        "name": "aiTarget",
        "layout": "${message}",
        "instrumentationKey": "0000-000000000-00000-00000"
      },
      "async": true,
      "logfile": {
        "type": "File",
        "fileName": "${basedir}/NLogs/nlog-${shortdate}.log",
        "layout": {
          "type": "JsonLayout",
          "Attributes": [
            {
              "name": "timestamp",
              "layout": "${date:format=o}"
            },
            {
              "name": "level",
              "layout": "${level}"
            },
            {
              "name": "logger",
              "layout": "${logger}"
            },
            {
              "name": "message",
              "layout": "${message:raw=true}"
            },
            {
              "name": "properties",
              "encode": false,
              "layout": {
                "type": "JsonLayout",
                "includeallproperties": "true"
              }
            }
          ]
        }
      },
      "console": {
        "type": "LimitingWrapper",
        "interval": "00:00:01",
        "messageLimit": 100,
        "target": {
          "type": "ColoredConsole",
          "layout": "${longdate}|${event-properties:item=EventId_Id:whenEmpty=0}|${uppercase:${level}}|${logger}|${message} ${exception:format=tostring}|${callsite}",
          "rowHighlightingRules": [
            {
              "condition": "level == LogLevel.Error",
              "foregroundColor": "Red"
            },
            {
              "condition": "level == LogLevel.Fatal",
              "foregroundColor": "Red",
              "backgroundColor": "White"
            }
          ],
          "wordHighlightingRules": [
            {
              "regex": "on|off",
              "foregroundColor": "DarkGreen"
            },
            {
              "condition": "level == LogLevel.Debug",
              "text": "[TEST]",
              "foregroundColor": "Blue"
            }
          ]
        }
      }
    },
    "rules": [
      {
        "logger": "*",
        "minLevel": "Error",
        "writeTo": "logfile"
      },
      {
        "logger": "*",
        "minLevel": "Trace",
        "writeTo": "aiTarget"
      },
      {
        "logger": "*",
        "minLevel": "Debug",
        "writeTo": "console"
      }
    ]
  }
}

And this is the code

Dim PathToJson As String = $"{AppDomain.CurrentDomain.BaseDirectory}bin"
        Dim jsonFilePath As String = Path.Combine(PathToJson, "nlogsettings.json")
        LogError("", jsonFilePath)
        LogError("", AppDomain.CurrentDomain.BaseDirectory)
        If File.Exists(jsonFilePath) Then
            Dim config = New ConfigurationBuilder() _
            .SetBasePath(Directory.GetCurrentDirectory()) _
            .AddJsonFile(jsonFilePath, optional:=False, reloadOnChange:=True) _
            .Build()
            LogManager.Configuration = New NLogLoggingConfiguration(config.GetSection("NLog"))
            Dim activateLogging As Boolean
            If Boolean.TryParse(config("ActivateExtendedLogging"), ActivateExtendedLogging) Then
                Me.ActivateExtendedLogging = ActivateExtendedLogging
            End If
        Else
            WriteLog("NLog Json file does not exist!")
        End If

Solution

  • Failed to create Target with unknown type-alias: ApplicationInsightsTarget - Verify type-alias and check extension is included

    To include a NLog extension, then you must do the following:

    • Add the nuget-package for the NLog extension to the application-project.
    • Add the NLog extension to the NLog configuration.

    The first part you have completed, but the other part can either be done in appsettings.json:

      "NLog": {
        "extensions": [
          { "assembly": "Microsoft.ApplicationInsights.NLogTarget" }
        ],
    

    Alternative you can register from code (Before loading the NLog configuration):

    NLog.LogManager.Setup().SetupExtensions(ext =>
       ext.RegisterTarget<Microsoft.ApplicationInsights.NLogTarget.ApplicationInsightsTarget>("ApplicationInsightsTarget")
    );
    

    See also: https://github.com/NLog/NLog/wiki/Logging-troubleshooting