Home > Software engineering >  How to log to a file in asp.net core web app - wtihout any third party tools
How to log to a file in asp.net core web app - wtihout any third party tools

Time:05-23

I am currently have an application running where I want the logs to be sinked into a file, such that Datadog is able to fetch them.

I currently just uses the sourcegenerator to log, but how do i get these log down to a file?

I tried altered the web.config to and deploy it to iis, but nothing seem to logged to a file, i then manually created the log folder, and still nothing seemed to be put inside.

<?xml version="1.0" encoding="utf-8"?>
<configuration>

  <!-- To customize the asp.net core module uncomment and edit the following section. 
  For more info see https://go.microsoft.com/fwlink/?linkid=838655 -->
    
  <system.webServer>
    <handlers>
      <remove name="aspNetCore"/>
      <add name="aspNetCore" path="*" verb="*" modules="AspNetCoreModuleV2" resourceType="Unspecified"/>
    </handlers>
    <aspNetCore processPath="%LAUNCHER_PATH%" arguments="%LAUNCHER_ARGS%" stdoutLogEnabled="true" stdoutLogFile=".\logs\stdout" />
  </system.webServer>


</configuration>

so how do i get my logs down to a file?

How i currently log

public partial class RequestResponseLoggerMiddleware
{
    private readonly RequestDelegate _next;
    private readonly ILogger _logger;

    public RequestResponseLoggerMiddleware(RequestDelegate next,
                                    ILoggerFactory loggerFactory)
    {
        _next = next;
        _logger = loggerFactory
                  .CreateLogger<RequestResponseLoggerMiddleware>();
    }

    [LoggerMessage(0, LogLevel.Information, "{requestUrl} proxied to {proxiedUrl}")]
    partial void LogRequest(string requestUrl, string proxiedUrl);

    public async Task Invoke(HttpContext context)
    {
        //code dealing with the request
        string requestUrl = context.Request.GetDisplayUrl();
        string path = context.Request.Path;          
        
        await _next(context);

        var proxyFeature = context.GetReverseProxyFeature();
        Yarp.ReverseProxy.Model.DestinationState? destination = proxyFeature.ProxiedDestination;
        if (destination != null)
        {
            string proxiedUrl = destination.Model.Config.Address   path;

            //code dealing with the response
            LogRequest(requestUrl, proxiedUrl);
        }
        else
        {
            LogRequest(requestUrl, string.Empty);
        }
    }

}

program.cs

var builder = WebApplication.CreateBuilder(args);
builder.Services.AddReverseProxy().LoadFromConfig(builder.Configuration.GetSection("ReverseProxy"));

var app = builder.Build();
app.MapReverseProxy(proxyPipeline =>
{
    proxyPipeline.UseRequestResponseLogging();
});
app.UseHttpsRedirection();
app.Run();

appsettings.json

{
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft.AspNetCore": "Warning"
    }
  },
  "AllowedHosts": "*",
  "ReverseProxy": {
    "Routes": {
      "force": {
        "ClusterId": "old-site",
        "Match": {
          "Path": "{**catch-all}"
        }
      },
      "azure": {
        "ClusterId": "new-site",
        "Match": {
          "Path": "yarpb"
        }
      }
    },
    "Clusters": {
      "old-site": {
        "Destinations": {
          "force": {
            "Address": "https://example.com/"
          }
        }
      },
      "new-site": {
        "Destinations": {
          "yarpb": {
            "Address": "https://localhost:61000/"
          }
        }
      }
    }
  }
}

CodePudding user response:

Issue http://github.com/aspnet/Logging/issues/441 is closed and MS officially recommends to use 3rd party file loggers. Please see answers from: How to log to a file without using third party logger in .Net Core?

CodePudding user response:

You can use .NET Trace Listeners for this.

https://www.daveoncsharp.com/2009/09/create-a-logger-using-the-trace-listener-in-csharp/

  • Related