简体   繁体   中英

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

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/"
          }
        }
      }
    }
  }
}

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?

A little different approach, but if you're using Datadog consider just writing to the Windows Event Viewer

public void WriteToEventLog(string sLog, string sSource, string message, EventLogEntryType level) {  

  
    if (!EventLog.SourceExists(sSource)) EventLog.CreateEventSource(sSource, sLog);  
  
    EventLog.WriteEntry(sSource, message, level);  
} 

Then with Datadog:

- type: windows_event
  channel_path: System
  source: System
  service: eventlog
  log_processing_rules:
   - type: exclude_at_match
     name: exclude_information_event
     pattern: ^.*[Ll]evel.*Information.* 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM