.net 未在正确目录中创建文件(SeriLog)

s4n0splo  于 2023-03-24  发布在  .NET
关注(0)|答案(2)|浏览(176)

我试图将SeriLog集成到一个项目中,这样我就可以利用结构化日志记录。我试图将文件放在给定的路径中,但日志文件不在我给出的路径中。相反,它们在不同的位置中创建
Program.cs中的SeriLog配置:

var configuration = new ConfigurationBuilder()
        .SetBasePath(Directory.GetCurrentDirectory())
        .AddJsonFile("appsettings.json")
        .AddJsonFile($"appsettings.{Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT") ?? "Production"}.json", true)
        .Build();
var logger = new LoggerConfiguration()
                 .ReadFrom.Configuration(configuration)
                 .Enrich.FromLogContext()
                 .MinimumLevel.Warning()
                 .CreateLogger();
builder.Logging.ClearProviders();
builder.Logging.AddSerilog(logger);

我的appsettings.json:

"Serilog": {
    "Using": [ "Serilog.Sinks.File", "Serilog.Sinks.Console"],
    "MinimumLevel": {
      "Default": "Debug",
      "Override": {
        "Microsoft": "Error",
        "System": "Debug"
      }
    },
    "Enrich": [ "FromLogContext", "WithMachineName", "WithProcessId", "WithThreadId" ],
    "WriteTo": [
      {
        "Name": "Console",
        "Args": {
          "outputTemplate": "[{Timestamp:yyyy/MM/dd HH:mm:ss} {Level:u10}] {Message:lj} {NewLine}{Exception}{NewLine}",
          "theme": "Serilog.Sinks.SystemConsole.Themes.SystemConsoleTheme::Literate, Serilog.Sinks.Console"
        }
      },
      {
        "Name": "File",
        "Args": {
          "path": "Logs\\RestApiLog.log",
          "outputTemplate": "{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz} [{Level}] [{SourceContext}] [{EventId}] {Message}{NewLine}{Exception}",
          "rollOnFileSizeLimit": true,
          "fileSizeLimitBytes": 4194304,
          "retainedFileCountLimit": 15,
          "rollingInterval": "Minute"
        }
      }
    ]
  }

我的appsetting.Development.json:

"Serilog": {
    "Using": [ "Serilog.Sinks.File", "Serilog.Sinks.Console" ],
    "MinimumLevel": {
      "Default": "Debug",
      "Override": {
        "Microsoft": "Error",
        "System": "Debug"
      }
    },
    "Enrich": [ "FromLogContext", "WithMachineName", "WithProcessId", "WithThreadId" ],
    "WriteTo": [
      {
        "Name": "Console",
        "Args": {
          "outputTemplate": "[{Timestamp:yyyy/MM/dd HH:mm:ss} {Level:u10}] {Message:lj} {NewLine}{Exception}{NewLine}",
          "theme": "Serilog.Sinks.SystemConsole.Themes.SystemConsoleTheme::Literate, Serilog.Sinks.Console"
        }
      },
      {
        "Name": "File",
        "Args": {
          "path": "E:\\OneDrive - Octopus Digital\\OC_API\\OmniConnectAPI\\Logs",
          "outputTemplate": "{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz} [{Level}] [{SourceContext}] [{EventId}] {Message}{NewLine}{Exception}",
          "rollOnFileSizeLimit": true,
          "fileSizeLimitBytes": 4194304,
          "retainedFileCountLimit": 15,
          "rollingInterval": "Minute"
        }
      }
    ]
  }

我还实现了一个ExceptionHandlingMiddleWare,我在下面附加了代码:

public class ExceptionHandlingMiddleware
{
    public RequestDelegate requestDelegate;
    private readonly ILogger<ExceptionHandlingMiddleware> logger;
    public ExceptionHandlingMiddleware(RequestDelegate requestDelegate, ILogger<ExceptionHandlingMiddleware> logger)
    {
        this.requestDelegate = requestDelegate;
        this.logger = logger;
    }

    public async Task Invoke(HttpContext context)
    {
        try
        {
            await requestDelegate(context);
        }
        catch (Exception ex)
        {
            await HandleException(context, ex);
        }
    }
    private Task HandleException(HttpContext context, Exception ex)
    {
        logger.LogError(ex.ToString());
        var errorMessageObject = new { Message = ex.Message, Code = "system_error" };

        var errorMessage = JsonConvert.SerializeObject(errorMessageObject);
        context.Response.ContentType = "application/json";
        context.Response.StatusCode = (int)HttpStatusCode.InternalServerError;
        return context.Response.WriteAsync(errorMessage);
    }
}

我还在progam.cs中添加了这一行,以便使用这个中间件:app.UseMiddleware(typeof(ExceptionHandlingMiddleware));
我还附上了一张图片,这样你就可以看到文件应该在哪里创建,以及它们实际上是在哪里创建的:[![未在日志文件夹中创建文件]
(x一个电子零个电子)](x一个电子零个电子)

ve7v8dk2

ve7v8dk21#

我立即注意到的是你的路径有一个“逻辑”错误。
您忘记在"E:\\OneDrive - Octopus Digital\\OC_API\\OmniConnectAPI\\Logs"处关闭路径,它应该看起来像"E:\\OneDrive - Octopus Digital\\OC_API\\OmniConnectAPI\\Logs\\"
您可以在创建的文件中完美地看到这一点,在一开始它说"Logs",程序认为"\\Logs"是文件的开头而不是文件夹。

a2mppw5e

a2mppw5e2#

好吧,这实际上是我犯的一个很基本的错误,而不是我的appsettings.Development.json中的"path": "E:\\OneDrive - Octopus Digital\\OC_API\\OmniConnectAPI\\Logs",,我只需要将其更改为
"path": "E:\\OneDrive - OctopusDigital\\OC_API\\OmniConnectAPI\\Logs\\LogFile_.log"我认为问题是我没有指定我想给文件本身命名的东西。

相关问题