how to configure serilog and applicationinsights in App.config?

1.1k views Asked by At

I was trying to do this to configure serilog to write to application insights. it is in app.config file. But it doesn't work. Is there any alternative approach

<add key="serilog:minimum-level" value="Error"/>
<add key="serilog:using:ApplicationInsights" value="Serilog.Sinks.ApplicationInsights" />
<add key="serilog:write-to:ApplicationInsights" value="fxxx104-dd93-xxxx-8601-xxxxxxxxxxx"/>
1

There are 1 answers

0
Jason Pan On

You should add UseSerilog in Program.cs. You use App.config just want the read keys by code, something like ConfigurationManager.AppSettings["key"].

public static IHostBuilder CreateHostBuilder(string[] args) =>
    Host.CreateDefaultBuilder(args)
        .ConfigureWebHostDefaults(webBuilder =>
        {
            webBuilder.UseStartup<Startup>();
        })
       .UseSerilog((hostingContext, loggerConfiguration) => loggerConfiguration
           .ReadFrom.Configuration(hostingContext.Configuration)
           .WriteTo.ApplicationInsights(new TelemetryConfiguration{ InstrumentationKey = "xxxxxxxxx" },TelemetryConverter.Traces)
        );   

Then you can use Log.Information("log details") in yourController.cs to record logs.

Thanks for Ivan's soultion. For more details, you can refer his answer in below post.

Using serilog with azure application insights and .Net core