C# Serilog config in ASP.NET Core 6.

huangapple go评论98阅读模式
英文:

C# Serilog config in ASP.NET Core 6

问题

"Serilog": {
    "Using": [],
    "MinimumLevel": {
      "Default": "Information",
      "Override": {
        "Microsoft.AspNetCore": "Warning",
        "System": "Warning" // These namespaces will also come as Information.
      }
    },
    "Enrich": [ "FromLogContext", "WithMachineName", "WithProcessId", "WithThreadId" ],
    "WriteTo": [
      { "Name": "Console" }
    ]
  }

我尝试为我的引导应用程序添加Serilog,但什么都没有很好地工作 :(. 它没有记录到控制台。

英文:

I have the following in appsettings.json for Serilog:

"Serilog": {
    "Using": [],
    "MinimumLevel": {
      "Default": "Information",
      "Override": {
        "Microsoft.AspNetCore": "Warning",
        "System": "Warning" //Amik ezekből a névterekből jönnek is Informationok lesznek.
      }
    },
    "Enrich": [ "FromLogContext", "WithMachineName", "WithProcessId", "WithThreadId" ],
    "WriteTo": [
      { "Name": "Console" }
    ]
  },

I tried to add Serilog for my bootstrap app, but nothing worked well :(.

It is not logging to the console.

答案1

得分: 4

appsettings.json中,我尝试为我的引导应用程序添加Serilog,但效果不佳。它没有记录到控制台。

很明显,不太清楚您是否已按照所有步骤进行操作。根据您分享的appsettings.json,您的配置部分正确。如果在using块内部没有定义任何内容,最好省略它。此外,您还没有定义您的“Args”参数,需要记录的是路径。此外,您是否已安装所需的NuGet包并在程序.cs文件中包含了所需的代码片段。

因此,您可以按照以下步骤正确实施它。

先决条件:

  1. Serilog Nuget包
  2. appsettings.json 配置

1. Serilog Nuget包

要为asp.net core配置Serilog,无论其版本如何,您需要在应用程序引用中添加以下包。

serilog.aspnetcore, serilog.sinks.seq, serilog.expressions

您可以从Nuget包管理器中添加它们,如下所示:

C# Serilog config in ASP.NET Core 6.

安装了所有必需的包后,它应该如下所示:

C# Serilog config in ASP.NET Core 6.

此外,您还可以使用Nuget包管理器控制台命令,如下所示:

dotnet add package serilog.aspnetcore
dotnet add package serilog.sinks.seq
dotnet add package serilog.expressions

2. appsettings.json 配置

请按照以下方式替换您的appsettings.json文件以配置Serilog。

{
  "Serilog": {
    "MinimumLevel": {
      "Default": "Information",
      "Override": {
        "Microsoft": "Warning",
        "Microsoft.Hosting.Lifetime": "Information"
      }
    },
    "WriteTo": [
      {
        "Name": "Console",
        "Args": {
          "path": "./logs/log-.txt",
          "rollingInterval": "Day"
        }
      }
    }
  },
  "AllowedHosts": "*"
}

Program.cs文件

在Program.cs文件中:

using Serilog;

Log.Logger = new LoggerConfiguration()
    .WriteTo.Console()
    .CreateBootstrapLogger();
Log.Information("Staring up logging");

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

    builder.Host.UseSerilog((context, logConfig) => logConfig
        .WriteTo.Console()
        .ReadFrom.Configuration(context.Configuration));

    // 将服务添加到容器中

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

    var app = builder.Build();

    // 配置HTTP请求管道

    if (app.Environment.IsDevelopment())
    {
        app.UseSwagger();
        app.UseSwaggerUI();
    }

    app.UseSerilogRequestLogging();
    app.UseHttpsRedirection();
    app.UseAuthorization();
    app.MapControllers();
    app.Run();
}
catch (Exception ex)
{
    Log.Fatal(ex, "Unhandled Exception");
}
finally
{
    Log.Information("Log Complete");
    Log.CloseAndFlush();
}

输出:

C# Serilog config in ASP.NET Core 6.

注意: 如果您想了解更多关于asp.net core中的日志记录的细节,您可以在此处查看官方文档

英文:

> I have the following settings in appsettings.json for Serilog. I tried to add Serilog for my bootstrap app, but nothing worked well
> It is not logging into console.

Well, its not quite clear if you have followed all the steps accordingly. Based on your shared appsettings.json it appreared that your configuration is partially correct. If you don't define anything inside using block its better to ommit that. In addition to this, you haven't defined your "Args" parameter where need to log what I mean is the path. Furthermore, whether you have install the required nuget package and included the required code snippet in your program.cs file

Therefore, you can follow the steps below to implement it correctly.

Prerequisite:

  1. Serilog Nuget Package
  2. appsettings.json configuration

1. Serilog Nuget Package

To configure Serilog for asp.net core reagrdless of its version, you need to following package in your application reference.

serilog.aspnetcore, serilog.aspnetcore and serilog.expressions

You can add from your Nuget Package Manager as following:

C# Serilog config in ASP.NET Core 6.

Once all the required package installed accordingly it should look like below:

C# Serilog config in ASP.NET Core 6.

In addititon, you even can using nuget package manager console command which are like below:

dotnet add package serilog.aspnetcore
dotnet add package serilog.sinks.seq
dotnet add package serilog.expressions

2. appsettings.json configuration

Please replace your appsettings.json file as following for serilog.

{
  "Serilog": {
    "MinimumLevel": {
      "Default": "Information",
      "Override": {
        "Microsoft": "Warning",
        "Microsoft.Hosting.Lifetime": "Information"
      }
    },
   
    "WriteTo": [
      {
        "Name": "Console",
        "Args": {
          "path": "./logs/log-.txt",
          "rollingInterval": "Day"
        }
      }
      
    ]
  },
  "AllowedHosts": "*"
}

Program.cs file

using Serilog;



Log.Logger =  new LoggerConfiguration()
    .WriteTo.Console().CreateBootstrapLogger();
Log.Information("Staring up logging");

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

    builder.Host.UseSerilog((context, logConfig) => logConfig
        .WriteTo.Console()
        .ReadFrom.Configuration(context.Configuration));

    // Add services to the container.

    builder.Services.AddControllers();
    // Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
    builder.Services.AddEndpointsApiExplorer();
    builder.Services.AddSwaggerGen();



    var app = builder.Build();

    // Configure the HTTP request pipeline.
    if (app.Environment.IsDevelopment())
    {
        app.UseSwagger();
        app.UseSwaggerUI();
    }

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

    app.UseAuthorization();

    app.MapControllers();

    app.Run();

}
catch (Exception ex)
{

    Log.Fatal(ex,"Unhandled Exception");
}

finally
{
    Log.Information("Log Complete");
    Log.CloseAndFlush();
}

Output:

C# Serilog config in ASP.NET Core 6.

Note: If you would like to know more details about logging in asp.net core you could check the official document here

答案2

得分: 0

以下是代码的翻译部分:

Program.cs

builder.Logging.ClearProviders().AddSerilog(CustomLoggerConfiguration.Configure());

CustomLoggerConfiguration

public class CustomLoggerConfiguration
{
    public static Logger Configure()
    {
        return new LoggerConfiguration()
              .MinimumLevel.Information()
              .MinimumLevel.Override("Microsoft", LogEventLevel.Warning)
              .Enrich.FromLogContext()
              .WriteTo.File("logs/log.txt", rollingInterval: RollingInterval.Day).CreateLogger();
    }
}
英文:

this solution worked for me in .net 7

Program.cs

builder.Logging.ClearProviders().AddSerilog(CustomLoggerConfiguration.Configure());

CustomLoggerConfiguration

 public class CustomLoggerConfiguration
{
    public static Logger Configure()
    {
        return new LoggerConfiguration()
              .MinimumLevel.Information()
              .MinimumLevel.Override("Microsoft", LogEventLevel.Warning)
              .Enrich.FromLogContext()
              .WriteTo.File("logs/log.txt", rollingInterval: RollingInterval.Day).CreateLogger();
    }

}

huangapple
  • 本文由 发表于 2023年2月16日 06:53:19
  • 转载请务必保留本文链接:https://go.coder-hub.com/75466179.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定