4

I am trying to connect Serilog logging with Application Insights, using this: Serilog Sinks

I am not sure why it doesn't seem to be logging to ApplicationInsights at all, while the file-logging portion works as intended.

This is my code from Program.cs:

public static int Main(string[] args)
    {
        var config = ConfigurationHelper.GetConfiguration();
        var loggerConfiguration = new LoggerConfiguration()
             .ReadFrom.Configuration(config);
        var telemetryConfiguration = TelemetryConfiguration
               .CreateDefault();
        telemetryConfiguration.InstrumentationKey = config["ApplicationInsights:InstrumentationKey"];

        //loggerConfiguration.WriteTo.File("log-files/libtester-web-.log",
        //    outputTemplate: "[{Timestamp:HH:mm:ss} {Level:u3}] {Message:lj} {Properties:j}{NewLine}{Exception}",
        //    rollingInterval: RollingInterval.Day);

        Log.Logger = loggerConfiguration
            .WriteTo.ApplicationInsights(telemetryConfiguration, TelemetryConverter.Events)
            .ReadFrom.Configuration(config)
            .Enrich.WithMachineName()
            .Enrich.WithProcessId()
            .Enrich.FromLogContext()
            .CreateLogger();

        try
        {
            Log.Information("Starting web host");
            CreateHostBuilder(args).Build().Run();
            return 0;
        }
        catch (Exception ex)
        {
            Log.Fatal(ex, "Host terminated unexpectedly");
            return 1;
        }
        finally
        {
            Log.CloseAndFlush();
        }
    }

    public static IHostBuilder CreateHostBuilder(string[] args) =>
       Host.CreateDefaultBuilder(args)
           .ConfigureWebHostDefaults(webBuilder =>
           {
               webBuilder.UseStartup<Startup>();
           })
           .UseSerilog();

The appropriate section from appsettings.json:

  "Serilog": {
"Using": [
  "Serilog.Sinks.ApplicationInsights"
],
"MinimumLevel": {
  "Default": "Debug",
  "Override": {
    "Microsoft": "Information"
  }
},
"WriteTo": [
  {
    "Name": "ApplicationInsights",
    "Args": {
      "restrictedToMinimumLevel": "Information",
      "telemetryConverter": "Serilog.Sinks.ApplicationInsights.Sinks.ApplicationInsights.TelemetryConverters.TraceTelemetryConverter, Serilog.Sinks.ApplicationInsights"
    }
  },
  {
    "Name": "File",
    "Args": {
      "path": "log-files/libtester-web-.log",
      "outputTemplate": "[{Timestamp:HH:mm:ss} {Level:u3}] {Message:lj} {Properties:j}{NewLine}{Exception}",
      "rollingInterval": "Day",
      "shared": true
    }
  }
],
"Enrich": [ "FromLogContext" ],
"Properties": {
  "Application": "LibTester.Web"
}

}

It logs fine to the log-files directory, but my resource in AppInsights isn't getting the same logs.

I get these two messages in Output from adding this: 'Serilog.Debugging.SelfLog.Enable(msg => Debug.WriteLine(msg));'

Application Insights Telemetry (unconfigured): {"name":"AppTraces","time":"2020-10-22T15:06:06.1140795Z","tags":{"ai.cloud.roleInstance":"MSI-970","ai.operation.id":"1b296d7eaa070941b54ef0b5019a7e18","ai.operation.parentId":"41f0aa970096b14a","ai.internal.sdkVersion":"dotnetc:2.15.0-44797"},"data":{"baseType":"MessageData","baseData":{"ver":2,"message":"Request finished in 628.7215ms 200 application/json; charset=utf-8","severityLevel":"Information","properties":{"ContentType":"application/json; charset=utf-8","ProcessId":"57840","ElapsedMilliseconds":"628.7215","SpanId":"41f0aa970096b14a","Application":"LibTester.Web","RequestPath":"/weatherforecast","StatusCode":"200","ParentId":"0000000000000000","MessageTemplate":"{HostingRequestFinishedLog:l}","MachineName":"MSI-970","EventId":"{"Id":2}","TraceId":"1b296d7eaa070941b54ef0b5019a7e18","RequestId":"80000032-0003-fe00-b63f-84710c7967bb","HostingRequestFinishedLog":"Request finished in 628.7215ms 200 application/json; charset=utf-8","SourceContext":"Microsoft.AspNetCore.Hosting.Diagnostics"}}}} Application Insights Telemetry: {"name":"AppRequests","time":"2020-10-22T15:06:05.4273838Z","iKey":"e1281822-9ed6-4db3-8bad-0de7ce3689a7","tags":{"ai.application.ver":"0.0.1.0","ai.cloud.roleInstance":"MSI-970","ai.user.id":"POM78vd9lDKUjMr10/Qhgc","ai.operation.id":"1b296d7eaa070941b54ef0b5019a7e18","ai.operation.name":"GET WeatherForecast/Get","ai.location.ip":"::1","ai.internal.sdkVersion":"aspnet5c:2.15.0+2c60e729d6512c31e5791ec93c9f7796d54fe426","ai.internal.nodeName":"MSI-970"},"data":{"baseType":"RequestData","baseData":{"ver":2,"id":"41f0aa970096b14a","name":"GET WeatherForecast/Get","duration":"00:00:00.7411718","success":true,"responseCode":"200","url":"https://localhost:44337/weatherforecast","properties":{"DeveloperMode":"true","_MS.ProcessedByMetricExtractors":"(Name:'Requests', Ver:'1.1')","AspNetCoreEnvironment":"Development"}}}}

8
  • Did you enable the self log? Commented Oct 21, 2020 at 17:06
  • I tried adding 'Serilog.Debugging.SelfLog.Enable(msg => Debug.WriteLine(msg));' to my Program.cs, but I don't notice anything different from not having it. Commented Oct 22, 2020 at 15:21
  • Did you then attach the debugger and monitor the debug output? Commented Oct 22, 2020 at 15:23
  • 1
    @JasonWard, In the output, I see there is a messageApplication Insights Telemetry (unconfigured):, which means that the instumetation key for application insights is not configured correctly. Commented Oct 26, 2020 at 2:41
  • 1
    Hi, @JasonWard! Did you manage to make it work in the end? I'm facing a similar issue. Thanks! Commented Oct 1, 2021 at 9:47

1 Answer 1

1

Please try to remove this section in appsettings.json:

  {
    "Name": "ApplicationInsights",
    "Args": {
      "restrictedToMinimumLevel": "Information",
      "telemetryConverter": "Serilog.Sinks.ApplicationInsights.Sinks.ApplicationInsights.TelemetryConverters.TraceTelemetryConverter, Serilog.Sinks.ApplicationInsights"
    }
  },

After remove it, I can see the logs are in azure portal -> application insights.

Here is appsettings.json in my test:

{
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft": "Warning",
      "Microsoft.Hosting.Lifetime": "Information"
    }
  },
  "AllowedHosts": "*",
  "ApplicationInsights": {
    "InstrumentationKey": "xxxxxxxxx"
  },
  "Serilog": {
    "Using": [
      "Serilog.Sinks.ApplicationInsights"
    ],
    "MinimumLevel": {
      "Default": "Debug",
      "Override": {
        "Microsoft": "Information"
      }
    },
    "WriteTo": [    
      {
        "Name": "File",
        "Args": {
          "path": "log-files/libtester-web-.log",
          "outputTemplate": "[{Timestamp:HH:mm:ss} {Level:u3}] {Message:lj} {Properties:j}{NewLine}{Exception}",
          "rollingInterval": "Day",
          "shared": true
        }
      }
    ],
    "Enrich": [ "FromLogContext" ],
    "Properties": {
      "Application": "LibTester.Web"
    }
   }
  }
Sign up to request clarification or add additional context in comments.

1 Comment

Hi, @Ivan Yang! How removing Serilog writer to ApplicationInsights makes sending logs to Azure? On my end didn't fix it.. Any thoughts on this? Thanks!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.