serilog-contrib / serilog-sinks-applicationinsights

A Serilog sink that writes events to Microsoft Azure Application Insights
Apache License 2.0
220 stars 72 forks source link

ILogger traces not showing up in Application Insights, but TelemetryClient.TrackTrace does show up for a .net core 3.1 console application #165

Closed CarlosOnline closed 3 years ago

CarlosOnline commented 3 years ago

Application Insights works, configured through services.AddApplicationInsightsTelemetryWorkerService();. See app insights flowing.

telemetryClient.TrackTrace("Shows up in application insights") works. this.logger.LogInformation("Doesn't show up in Application Insights")

Debug out shows that App Insights is unconfigured.

Application Insights Telemetry (unconfigured): {"name":"AppTraces","time":"2021-06-07T03:39:50.4753195Z"

Any idea why Serilog is not finding the configured Application Insights?

Program.cs

var config = new ConfigurationBuilder()
    .SetBasePath(Directory.GetCurrentDirectory())
        .AddJsonFile("appsettings.json")
        .AddJsonFile($"appsettings.{Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT") ?? "Production"}.json", true)
        .AddJsonFile("loggerConfig.json")
        .Build();

Log.Logger = new LoggerConfiguration()
            .ReadFrom.Configuration(config)

            .CreateLogger();

return Host.CreateDefaultBuilder(args)
    .UseSerilog()
    .ConfigureServices(services =>
    {
        ConfigureServices(services);
    });

csproj:

<Project Sdk="Microsoft.NET.Sdk">

  <PropertyGroup>
    <OutputType>Exe</OutputType>
    <TargetFramework>netcoreapp3.1</TargetFramework>
    <GenerateDocumentationFile>true</GenerateDocumentationFile>
  </PropertyGroup>

  <ItemGroup>
    <PackageReference Include="Microsoft.ApplicationInsights" Version="2.17.0" />
    <PackageReference Include="Microsoft.ApplicationInsights.WorkerService" Version="2.17.0" />
    <PackageReference Include="Microsoft.AspNetCore.Hosting" Version="2.2.7" />
    <PackageReference Include="Serilog.Extensions.Hosting" Version="3.1.0" />
    <PackageReference Include="Serilog.Settings.Configuration" Version="3.1.0" />
    <PackageReference Include="Serilog.Sinks.ApplicationInsights" Version="3.1.0" />
    <PackageReference Include="Serilog.Sinks.Console" Version="3.1.1" />
    <PackageReference Include="Serilog.Sinks.Debug" Version="1.0.1" />
    <PackageReference Include="Serilog.Sinks.File" Version="4.1.0" />
  </ItemGroup>

loggerConfig.json

{
  "Serilog": {
    "Using": [
      "Serilog.Sinks.ApplicationInsights"
    ],
    "MinimumLevel": {
      "Default": "Information",
      "Override": {
        "Microsoft": "Warning",
        "System": "Warning",
        "Microsoft.EntityFrameworkCore": "Warning"
      }
    },
    "WriteTo": [
      {
        "Name": "ApplicationInsights",
        "Args": {
          "restrictedToMinimumLevel": "Information",
          "telemetryConverter": "Serilog.Sinks.ApplicationInsights.Sinks.ApplicationInsights.TelemetryConverters.TraceTelemetryConverter, Serilog.Sinks.ApplicationInsights"
        }
      },
      {
        "Name": "File",
        "Args": {
          "path": "Logs\\SimulatorTool..log",
          "rollingInterval": "Day",
          "rollOnFileSizeLimit": true,
          "outputTemplate": "[{Timestamp:yyyy-MM-dd HH:mm:ss} {Level:u3}] {Message:lj}{NewLine}{Exception}"
        }
      },
      {
        "Name": "Console",
        "Args": {
          "theme": "Serilog.Sinks.SystemConsole.Themes.AnsiConsoleTheme::Code, Serilog.Sinks.Console",
          "outputTemplate": "[{Timestamp:yyyy-MM-dd HH:mm:ss} {Level:u3}] {Message:lj}{NewLine}{Exception}"
        }
      },
      {
        "Name": "Debug"
      }
    ],
    "Enrich": [ "FromLogContext" ],
    "Properties": {
      "Application": "Sample"
    }
  }
}
CarlosOnline commented 3 years ago

Host json issue

poveilleux commented 3 years ago

@CarlosOnline What was your issue exactly? I might have the same thing on my side but can't figure why it happens other than being on version 2.17.0 of Application Insights

calloncampbell commented 3 years ago

I'm having same issue, what did you do @CarlosOnline to resolve?

CarlosOnline commented 3 years ago

I sort of got it working. If I had to do it again, I wouldn't use Serilog for .net core applications. There is no documentation for .net core console apps that actually works. Lots of documentation on web pointing to different solutions but really nothing works right.

        /// <summary>
        /// Configure Serilog logging properly for Application Insights.
        /// NOTE: appsettings.json requires proper entries as well.
        /// </summary>
        /// <param name="hostBuilder">The Microsoft.Extensions.Hosting.IHostBuilder to configure.</param>
        /// <param name="configFiles">Additional config files.</param>
        /// <returns>The same instance of the Microsoft.Extensions.Hosting.IHostBuilder for chaining.</returns>
        public static IHostBuilder UseSerilogWithApplicationInsights(this IHostBuilder hostBuilder, string[] configFiles)
        {
            CreateLogger(configFiles);

            return hostBuilder.ConfigureLogging(loggingBuilder =>
            {
                loggingBuilder.AddSerilog(Log.Logger, dispose: true);
            });
        }

        /// <summary>
        /// Create default logger.
        /// </summary>
        /// <param name="configFiles">Additional config files.</param>
        /// <returns>The created logger.</returns>
        public static ILogger CreateLogger(string[] configFiles)
        {
            var configBuilder = new ConfigurationBuilder()
                .AddJsonFile("serilogconfig.json");

            foreach (var configFile in configFiles)
            {
                configBuilder.AddJsonFile(configFile, true);
            }

            var config = configBuilder.Build();

            var applicationInsightsKey = config.GetValue<string>("APPINSIGHTS_INSTRUMENTATIONKEY");

            Log.Logger = new LoggerConfiguration()
                .ReadFrom.Configuration(config)
                .WriteTo.ApplicationInsights(applicationInsightsKey, new SerilogApplicationInsightsConverter())
                .CreateLogger();

            return Log.Logger;
        }

appsettings.json

{
  "Logging": {
    // Set Application Insights logging levels
    "ApplicationInsights": {
      "LogLevel": {
        "Default": "Information",
        "Microsoft": "Warning"
      }
    },
    // Prevent duplicate logging using default logger. - Don't know why this happens.
    "LogLevel": {
      "Default": "None",
      "Microsoft": "None",
      "Microsoft.Hosting.Lifetime": "None"
    }
  },