首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >服务器.Net6中的Serilog将错误消息拆分为不同的文件

服务器.Net6中的Serilog将错误消息拆分为不同的文件
EN

Stack Overflow用户
提问于 2022-03-27 19:11:21
回答 1查看 558关注 0票数 0

在serilog中,我需要将信息分成两个文件。也就是说,一个文件应该包含信息,另一个文件应该包含错误。使用下面的代码和配置,信息和错误都会显示在两个文件中,而不是过滤掉。

注意:我正在Serverside Blazor中的.Net6中尝试这一点。请帮帮我们。提前谢谢

代码语言:javascript
运行
复制
    "Serilog": {
    "Using": [ "Serilog.Sinks.Console", "Serilog.Sinks.File", "Serilog.Expressions" ],
    "MinimumLevel": {
      "Default": "Information",
      "Override": {
        "Microsoft": "Warning",
        "System": "Warning"
      }
    },
    "Enrich": [
      "FromLogContext",
      "WithMachineName"
    ],
    "WriteTo": [
      {
        "Name": "Console"
      },
      {
        "Name": "File",
        "Args": {
          "path": "Logs/ex_.log",
          "outputTemplate": "{Timestamp:o} [{Level:u3}] ({SourceContext}) {Message:lj}{NewLine}{Exception}",
          "rollingInterval": "Day",
          "retainedFileCountLimit": 7
        }
      },
      {
        "Name": "Logger",
        "Args": {
          "configureLogger": {
            "Filter": [
              {
                "Name": "ByExcluding",
                "Args": {
                  "expression": "(@Level = 'Information' )"
                }
              }
            ],
            "WriteTo": [
              {
                "Name": "File",
                "Args": {
                  "path": "Logs/ERROR_.log",
                  "outputTemplate": "{Timestamp:yyyy-MM-dd HH:mm:ss.fff} [{Level:u3}] {Message:lj}{NewLine}{Exception}",
                  "rollingInterval": "Day",
                  "retainedFileCountLimit": 7
                }
              }
            ]
          }
        }
      }
    ]
  }

 Log.Logger = new LoggerConfiguration()
.WriteTo.Console()
.CreateBootstrapLogger();

WebApplicationBuilder builder;
try
{
    Log.Information("Application starting .....");
    builder = WebApplication.CreateBuilder(args);

    builder.Host.UseSerilog((ctx, lc) => lc
    .WriteTo.Console()
    .ReadFrom.Configuration(ctx.Configuration));

    // Add services to the container.
    builder.Services.AddRazorPages();
    builder.Services.AddServerSideBlazor();
    builder.Services.AddTelerikBlazor();
    builder.Services.AddSingleton<WeatherForecastService>();

    var app = builder.Build();

    // Configure the HTTP request pipeline.
    if (!app.Environment.IsDevelopment())
    {
        app.UseExceptionHandler("/Error");
        // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
        app.UseHsts();
    }

    app.UseHttpsRedirection();
    app.UseStaticFiles();
    app.UseSerilogRequestLogging();

    app.UseRouting();
    app.MapBlazorHub();
    app.MapFallbackToPage("/_Host");

    app.Run();
}
catch (Exception ex)
{
    Log.Fatal("Application even failed to start....");
}
EN

回答 1

Stack Overflow用户

发布于 2022-05-11 19:32:45

您需要确保安装了以下NuGet包。您可以在GitHub 这里上找到此示例代码。

  1. 西里罗格
  2. Serilog.AspNetCore
  3. Serilog.Settings.Configuration
  4. Serilog.Sinks.File,Serilog.Sinks.* (无论您使用的是什么接收器类型,相关包)
  5. Serilog.Expressions,
  6. 如果您想使用丰富器,请使用Serilog.Enricher.*(此包是可选的)。

我在这里使用的是.Net6示例中的。

代码语言:javascript
运行
复制
Program.cs 
代码语言:javascript
运行
复制
    using Serilog;
    
    var builder = WebApplication.CreateBuilder(args);
    
    var configuration = new ConfigurationBuilder()
        .SetBasePath(Directory.GetCurrentDirectory())
        .AddJsonFile("appsettings.json")
        .Build();
    
    
    Log.Logger = new LoggerConfiguration()
        .ReadFrom.Configuration(configuration)    
        .WriteTo.Console()
        .WriteTo.Logger(lc => lc
                        .Filter.ByIncludingOnly(" @l = 'Debug' or @l = 'Information' or @l = 'Warning'")
                        .WriteTo.File("Logs/Log-Information-{Date}.log", rollingInterval: RollingInterval.Day))
        .WriteTo.Logger(lc => lc
                        .Filter.ByIncludingOnly(" @l = 'Error' or @l = 'Fatal'")
                        .WriteTo.File("Logs/Log-Error-{Date}.log", rollingInterval: RollingInterval.Day))
        .CreateLogger();
    
    Log.Information("Starting up");
    
    
    Serilog.Log.Information("Starting application");
    Serilog.Log.Error("Error");
    Serilog.Log.Fatal("Fatal");
    Serilog.Log.Debug("Debug");
    
    // Add services to the container.
    builder.Services.AddAuthentication(NegotiateDefaults.AuthenticationScheme)
       .AddNegotiate();
    
    builder.Services.AddAuthorization(options =>
    {
        // By default, all incoming requests will be authorized according to the default policy.
        options.FallbackPolicy = options.DefaultPolicy;
    });
    
    builder.Services.AddRazorPages();
    builder.Services.AddServerSideBlazor();
    builder.Services.AddSingleton<WeatherForecastService>();
    
    var app = builder.Build();
代码语言:javascript
运行
复制
Appsettings.json file:
代码语言:javascript
运行
复制
      "Serilog": {
        "MinimumLevel": {
          "Default": "Information",
          "Microsoft.AspNetCore": "Warning",
          "Microsoft.EntityFrameworkCore": "Warning",
          "Microsoft.Extensions.DependencyInjection": "Warning",
        },
        "WriteTo": [
          {
            "Name": "Console",
            "Args": {
              "outputTemplate": "{Timestamp:HH:mm:ss} [{Level}] {SourceContext}{NewLine}{Message}{NewLine}{Exception}"
            }        
          },
          {
            "Name": "File",
            "Args": {
              "Path": "./logs/log.txt",
              "IncludeScopes": true,
              "TimestampFormat": "yyyy-MM-dd HH:mm:ss",
              "RollingInterval": "Day"
            }        
          },
          {
            "Name": "Seq",
            "Args": { "serverUrl":  "http://localhost:5341"}
          }
        ]
      }

根据下面的屏幕快照,上面的代码片段将在“./ log /”路径下生成两个不同的日志文件。

在档案中:

注意:我也在_Imports.razor中添加了"@using“。

我的项目包参考资料:

代码语言:javascript
运行
复制
<ItemGroup>
  <PackageReference Include="Microsoft.AspNetCore.Authentication.Negotiate" Version="6.0.5" />
  <PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="6.0.5" />
  <PackageReference Include="Serilog" Version="2.11.0" />
  <PackageReference Include="Serilog.AspNetCore" Version="5.0.0" />
  <PackageReference Include="Serilog.Expressions" Version="3.3.0" />
  <PackageReference Include="Serilog.Sinks.Seq" Version="5.1.1" />    
  <PackageReference Include="Serilog.Enrichers.AspNetCore.HttpContext" Version="1.0.1" />
  <PackageReference Include="Serilog.Enrichers.AssemblyName" Version="1.0.9" />
  <PackageReference Include="Serilog.Enrichers.Context" Version="4.2.0" />
  <PackageReference Include="Serilog.Enrichers.Environment" Version="2.2.0" />
  <PackageReference Include="Serilog.Enrichers.Memory" Version="1.0.4" />
  <PackageReference Include="Serilog.Enrichers.Process" Version="2.0.2" />
  <PackageReference Include="Serilog.Enrichers.Thread" Version="3.1.0" />
  <PackageReference Include="Serilog.Settings.Configuration" Version="3.3.0" />
  <PackageReference Include="Serilog.Sinks.MSSqlServer" Version="5.7.0" />
   </ItemGroup>
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/71639490

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档