Ashish Chettri
Ashish Chettri

Reputation: 35

Not able to write to application insights serilog when using Azure functions with dotnet-isolated runtime

I have an Azure Function app that's built using .NET 6 and uses the dotnet-isolated runtime. The default logger pushes logs to app insights, however, wasn't capturing custom dimensions, etc.

Based on the ticket [https://learn.microsoft.com/en-us/answers/questions/371873/ilogger-structured-loggig-with-application-insight][1], I moved to Serilog.

The program.cs looks something like this:

var configuration = new ConfigurationBuilder()
     .SetBasePath(Directory.GetCurrentDirectory())
     .AddJsonFile("logConfig.json", optional: false, reloadOnChange: true)
     .Build();
var host = new HostBuilder()
.ConfigureFunctionsWorkerDefaults()
.ConfigureServices(services =>
{
    var logger = new LoggerConfiguration()
    .ReadFrom.Configuration(configuration)
    .WriteTo.ApplicationInsights(new TraceTelemetryConverter())
    .CreateLogger();
     services.AddLogging(logging =>
    {       
        logging.ClearProviders();
        logging.AddSerilog(logger);
    });
}).Build();
await host.RunAsync();

Sample of the logger used in code:

_logger.LogInformation("xxxxxxx with invoice number: {invoiceNumber}", invoiceNumber);

The logConfig.json looks like this:

{
  "Serilog": {
    "MinimumLevel": {
      "Default": "Information",
      "Override": {
        "Microsoft.AspNetCore": "Warning"
      }
    },
    "WriteTo": [
      {
        "Name": "Console"
      },
      {
        "Name": "ApplicationInsights",
        "Args": {          
          "telemetryConverter": "Serilog.Sinks.ApplicationInsights.TelemetryConverters.TraceTelemetryConverter, Serilog.Sinks.ApplicationInsights"
        }
      }
    ],
    "Enrich": [ "FromLogContext", "WithMachineName", "WithThreadId" ],
    "Properties": {
      "Application": "SerilogTestApplication"
    }
  }
}

Upvotes: 1

Views: 1023

Answers (2)

Qiang Fu
Qiang Fu

Reputation: 8651

An interesting thing is that you do not even need to write to applicationInsights. Just write to console with json format . After published to azure, you will see your enriched properties.
program.cs

internal class Program
{
    private static void Main(string[] args)
    {
        var host = new HostBuilder()
    .ConfigureFunctionsWorkerDefaults()

                .ConfigureServices(s =>
                {
                    Log.Logger = new LoggerConfiguration()
                               .Enrich.WithProperty("MyCustomProperty1", "123456789")
                               .WriteTo.Console(new JsonFormatter())
                   .CreateLogger();
                    s.AddLogging(lb => lb.AddSerilog(Log.Logger));
                })
           .Build();

        host.Run();
    }
}

Function1.cs (No need DI for _logger)

    public class Function1
    {
        [Function("Function1")]
        public HttpResponseData Run([HttpTrigger(AuthorizationLevel.Function, "get", "post")] HttpRequestData req)
        {
            Log.Information("C# HTTP trigger function processed a request.");


            var response = req.CreateResponse(HttpStatusCode.OK);
            response.Headers.Add("Content-Type", "text/plain; charset=utf-8");
            response.WriteString("Welcome to Azure Functions!");
            return response;
        }
    }
}

enter image description here

Upvotes: 0

Harshitha
Harshitha

Reputation: 7347

Iam able to log traces as well as Custom Properties to Application Insights.

I have done few changes in the logConfig.json and Program.cs files.

I can see the custom properties for my traces as well.

My traces:

enter image description here

Thanks @camerondwyer for the code.

Followed the same code from the link which you have provided to log the Custom Properties using TelemetryClient.

Remove the MinimumLevelfrom the configuration file.

My logConfig.json file:

{
  "ApplicationInsights": {
    "ConnectionString": "InstrumentationKey=**********;IngestionEndpoint=https://westus2-2.in.applicationinsights.azure.com/;LiveEndpoint=https://westus2.livediagnostics.monitor.azure.com/"
  },
  "Serilog": {
    "Using": [
      "Serilog.Sinks.ApplicationInsights"
    ],
    "WriteTo": [
      {
        "Name": "Console"
      },
      {
        "Name": "ApplicationInsights",
        "Args": {
          "telemetryConverter": "Serilog.Sinks.ApplicationInsights.TelemetryConverters.TraceTelemetryConverter, Serilog.Sinks.ApplicationInsights"
        }
      }
    ],
    "Enrich": [ "FromLogContext", "WithMachineName", "WithThreadId" ],
    "Properties": {
      "Application": "SerilogTestApplication"
    }
  }
}

  • In Program.cs file, add the below line.
 .WriteTo.ApplicationInsights(Conn,new TraceTelemetryConverter())

Program.cs file:

using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Serilog;
using Serilog.Sinks.ApplicationInsights.TelemetryConverters;

var configuration = new ConfigurationBuilder()
     .SetBasePath(Directory.GetCurrentDirectory())
     .AddJsonFile("logConfig.json", optional: false, reloadOnChange: true)
     .Build();

var Conn = configuration["ApplicationInsights:ConnectionString"];


var host = new HostBuilder()
    .ConfigureFunctionsWorkerDefaults()
    .ConfigureServices(services =>
    {
        var logger = new LoggerConfiguration()
        .ReadFrom.Configuration(configuration)
        .WriteTo.ApplicationInsights(Conn,new TraceTelemetryConverter())
        .CreateLogger();
        services.AddLogging(logging =>
        {
            logging.ClearProviders();
            logging.AddSerilog(logger);
        });
    }).Build();

host.Run();

Function1.cs file

TelemetryConfiguration configuration = TelemetryConfiguration.CreateDefault();
configuration.InstrumentationKey = "**********";

TelemetryClient telemetryClient = new TelemetryClient(configuration);

telemetryClient.TrackTrace("Hello World!");
Dictionary<string, string> properties = new Dictionary<string, string>()
{
    {"FirstName", "Harshitha" },
    {"LastName", "Veeramalla" },
};
telemetryClient.TrackTrace("User Details",SeverityLevel.Information, properties);

.csproj file:

<PackageReference Include="Serilog.AspNetCore" Version="6.1.0" />
<PackageReference Include="Serilog.Sinks.ApplicationInsights" Version="4.0.0" />

Output: enter image description here

Click on the Trace.

Custom Properties: enter image description here

Upvotes: 1

Related Questions