Home > database >  Asp .net core webapi log to file in Dev write to application insights once deployed in azure
Asp .net core webapi log to file in Dev write to application insights once deployed in azure

Time:11-12

I am creating a new WebApi using .net7 and asp.net core I have used NLog before and know how to set up logging but since I'm deploying to azure and will use Application Insights to do the logging there but I don't want to use it in DEV.

How can it config my app so that it logs to file in dev and APPI once deployed?

CodePudding user response:

Check the below steps to Log traces to a Text file while accessing the App in development environment and to Application Insights when deployed to Azure App Service.

Thanks @Jignesh Trivedi for the nlog.config file.

Configure to send logs to a Text file.

  • Install the NuGet package NLog.Web.AspNetCore.
  • Create a new configuration file and name it as nlog.config.Add the below settings in the file.
<?xml version="1.0" encoding="utf-8" ?>
<nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd"
      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
      autoReload="true"
      internalLogLevel="info"
      internalLogFile="C:\Users\YourPath\NLogs\SampleLogs.txt">
  <extensions>
    <add assembly="NLog.Web.AspNetCore" />
  </extensions>
  <targets>
    <target name="logfile" xsi:type="File"
            fileName="C:\Users\YourPath\NLogs\SampleLogs.txt"
            layout="${longdate} ${level:uppercase=true} ${message}"/>
  </targets>
  <rules>
    <logger name="*" minlevel="Debug" writeTo="logfile" />
    <logger name="*" minlevel="Trace" writeTo="alldata" />
    <logger name="Microsoft.*" maxLevel="Info" final="true" />
    <loggername name="*" minlevel="Trace" writeTo="otherFile-web" />
  </rules>
</nlog>
  • In Program.cs file, add the below lines of code.
using NLog.Web;

var logger = NLog.LogManager.Setup().LoadConfigurationFromAppSettings().GetCurrentClassLogger();

builder.Logging.ClearProviders();
builder.Host.UseNLog();

In WeatherForecastController.cs, add the logs

[HttpGet(Name = "GetWeatherForecast")]
 public IEnumerable<WeatherForecast> Get()
 {
     _logger.LogInformation("Log Information from Weatherforecast.");
     _logger.LogDebug("Debug Message from the Controller Action.");
     _logger.LogWarning("Iam Log Warning.");
     _logger.LogError("Hello, this is Log Error.");

     return Enumerable.Range(1, 5).Select(index => new WeatherForecast
     {
         Date = DateTime.Now.AddDays(index),
         TemperatureC = Random.Shared.Next(-20, 55),
         Summary = Summaries[Random.Shared.Next(Summaries.Length)]
     })
     .ToArray();
}

When I run the app locally and execute the GET method, a new text file is created at the path where I have mentioned in the nlog.config - internalLogFile and target path.

Local Output: enter image description here

Configure logging to Application Insights

  • Create an Application Insights in Azure portal, copy the connection string and paste it in appsetting.json file.
{
  "Logging": {
    "ApplicationInsights": {
      "LogLevel": {
        "Default": "Debug",
        "Microsoft": "Error"
      }
    },
    "LogLevel": {
      "Default": "Information",
      "Microsoft.AspNetCore": "Warning"
    }
  },
  "AllowedHosts": "*",
  "ApplicationInsights": {
  "ConnectionString": "Connection String from Application Insights"
  }
}

Right click on solution explorer => Add Application Insights Telemetry => Azure Application Insights.

  • Add below code in Program.cs file.
builder.Services.AddApplicationInsightsTelemetry(builder.Configuration["APPLICATIONINSIGHTS_CONNECTION_STRING"]);

My Program.cs file

using NLog;
using NLog.Web;

using Microsoft.Extensions.Logging;
using Microsoft.ApplicationInsights.Channel;
using Microsoft.ApplicationInsights.WindowsServer.TelemetryChannel;

var environment = Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT");
var isDevelopment = environment == Environments.Development;
var logger =(dynamic) null;

#region DevLog
if (isDevelopment)
{
    logger = NLog.LogManager.Setup().LoadConfigurationFromAppSettings().GetCurrentClassLogger();
    #endregion
}

try
{
    var builder = WebApplication.CreateBuilder(args);


    #region ApplicationInsights
    if (!isDevelopment)
    {
        builder.Services.AddSingleton(typeof(ITelemetryChannel), new ServerTelemetryChannel());
        builder.Services.AddApplicationInsightsTelemetry();     
    }
    else
    {
        builder.Logging.ClearProviders();
        builder.Host.UseNLog();
    }
    #endregion

    builder.Services.AddControllers();
    builder.Services.AddEndpointsApiExplorer();
    builder.Services.AddSwaggerGen();  

    var app = builder.Build();

    if (app.Environment.IsDevelopment())
    {
        app.UseSwagger();
        app.UseSwaggerUI();
    }
    app.UseHttpsRedirection();
    app.UseAuthorization();
    app.MapControllers();
    app.Run();
}
catch (Exception ex)
{
    logger.Error(ex, "Error in init");
    throw;
}
finally
{
    NLog.LogManager.Shutdown();
}

.csproj file

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

  <PropertyGroup>
    <TargetFramework>net7.0</TargetFramework>
    <Nullable>enable</Nullable>
    <ImplicitUsings>enable</ImplicitUsings>
    <ApplicationInsightsResourceId>/subscriptions/****/resourceGroups/****/providers/microsoft.insights/components/11-40vscode</ApplicationInsightsResourceId>
    <UserSecretsId>****</UserSecretsId>
  </PropertyGroup>

  <ItemGroup>
    <PackageReference Include="Microsoft.ApplicationInsights.AspNetCore" Version="2.21.0" />
    <PackageReference Include="Microsoft.ApplicationInsights.Profiler.AspNetCore" Version="2.4.0" />
    <PackageReference Include="NLog.Web.AspNetCore" Version="5.1.5" />
    <PackageReference Include="Swashbuckle.AspNetCore" Version="6.2.3" />
  </ItemGroup>
</Project>

Deploy the App to Azure and enable Application Insights.

enter image description here

  • Run the Application and check Transaction Search and Logs in Application Insights.

enter image description here

enter image description here

References taken from MSDoc

  • Related