简体   繁体   English

Serilog 使用 Microsoft ILogger - 从 .NET Core 中的一个代码记录到不同的位置

[英]Serilog using Microsoft ILogger - logging to different places from one code in .NET Core

I'm using serilog through Microsoft.Extensions.Logging.ILogger.我通过 Microsoft.Extensions.Logging.ILogger 使用 serilog。 This is my configuration in Program.cs:这是我在 Program.cs 中的配置:

public class Program
  {
    public static void Main(string[] args)
    {
      IConfigurationRoot configuration = new ConfigurationBuilder()
                                          .AddJsonFile("appsettings.json")
                                          .Build();
      Log.Logger = new LoggerConfiguration()
                     .ReadFrom.Configuration(configuration)
                     .CreateLogger();
      CreateHostBuilder(args).Build().Run();
    }

    public static IHostBuilder CreateHostBuilder(string[] args) =>
        Host.CreateDefaultBuilder(args)
          .UseSerilog()
          .ConfigureLogging((context, logging) =>
          {
            logging.ClearProviders();
            logging.AddSerilog();
          })
          .ConfigureWebHostDefaults(webBuilder =>
          {
            webBuilder.UseStartup<Startup>();
          });
  }

I use the ILogger through DI.我通过 DI 使用 ILogger。 Everything works fine.一切正常。 Now I want to log some specific log to some file and some specific log to database.现在我想将一些特定的日志记录到一些文件和一些特定的日志到数据库。 For example I want to log info about something to somewhere and info about something else to somewhere else.例如,我想将有关某事的信息记录到某个地方,并将有关其他某事的信息记录到其他地方。

For example: I have a game.例如:我有一个游戏。 I want to log names of connected players and their actions to some file and events in the game and errors to a database.我想将已连接玩家的名称及其操作记录到游戏中的某些文件和事件中,并将错误记录到数据库中。

I know how to log into a db and file, but I dont know how can i separate the logs.我知道如何登录数据库和文件,但我不知道如何分离日志。 How can I do it?我该怎么做?

This is the config file (right now just for the file sink).这是配置文件(现在仅用于文件接收器)。

{
  "Serilog": {
    "Using": [],
    "MinimumLevel": {
      "Default": "Debug",
      "Override": {
        "Microsoft": "Error",
        "System": "Error"
      }
    },
    "Enrich": [ "SomeName" ],
    "WriteTo": [
      { "Name": "Console" },
      {
        "Name": "File",
        "Args": {
          "path": "log.log",
          "rollingInterval": "Day",
          "outputTemplate": "SomeFormat"
        }
      }
    ],
    "Application": "SomeName"
  },

You could try to write your own sinks.您可以尝试编写自己的接收器。 The LogEvent class offered by Serilog has a custom Serilog 提供的 LogEvent class 有一个自定义

readonly Dictionary<string, LogEventPropertyValue> _properties

which you could use to pass some flags.你可以用它来传递一些标志。 Based on the flags, your sinks can decide if they act or not upon your message.根据这些标志,您的接收器可以决定它们是否根据您的消息采取行动。

But this is all at Serilog lvl.但这都是在 Serilog lvl 上。 The integration with ILogger might take more thought.与 ILogger 的集成可能需要更多考虑。

You can store in different sinks by settings filtering exceptions您可以通过设置过滤异常存储在不同的接收器中

You could filter in many different ways.您可以通过许多不同的方式进行过滤。 The one that worked for me was to filter by namespace like:对我有用的是按名称空间过滤,例如:

var isController = Matching.FromSource("MyApp.Controllers");
var isService = Matching.FromSource("MyApp.Services");
Log.Logger = new LoggerConfiguration()
    .MinimumLevel.Verbose()
    .WriteTo.RollingFile("d:/logs/recon-api-all-{Date}.log")
    .WriteTo.Logger(l => l
        .Filter.ByIncludingOnly(isController)
        .WriteTo.RollingFile("d:/logs/recon-api-controller-{Date}.log"))
    .WriteTo.Logger(l => l
        .Filter.ByIncludingOnly(isService)
        .WriteTo.MSSqlServer(connectionString: ""))
    .WriteTo.Logger(l => l
        .Filter.ByExcluding(e => isController(e) || iService(e))
        .WriteTo.RollingFile("d:/logs/recon-api-other-{Date}.log"))
    .CreateLogger();

You can find a similar post here你可以在这里找到类似的帖子

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 将 Serilog 作为 Microsoft.Extentions.Logging.ILogger 正确注入 .net 核心类 - 不是 ASP .Net Core - Correctly Injecting Serilog into .net core classes as Microsoft.Extentions.Logging.ILogger - Not ASP .Net Core 将 Serilog 与 Microsoft.Extensions.Logging.ILogger 结合使用 - Use Serilog with Microsoft.Extensions.Logging.ILogger 在ASP.NET Core 2日志更新后将ILogger映射到Serilog的Logger - Map ILogger to Serilog's Logger after ASP.NET Core 2 logging update 使用Serilog .NET Core进行日志记录不会输出 - Logging with Serilog .NET Core not outputting 运行Asp.Net Core 2的Webapi 2上带有Seri​​log的DI ILogger - DI ILogger with Serilog on Webapi 2 running Asp.Net Core 2 ASP.NET Core 中的 Serilog DI,要注入哪个 ILogger 接口? - Serilog DI in ASP.NET Core, which ILogger interface to inject? 使用 serilog 从 ASP.Net 核心身份记录事件 - Logging events from ASP.Net core identity with serilog 在 .NET Core MVC 中使用 Serilog 使用 Azure 表存储进行日志记录 - Using Serilog for Logging with Azure Table Storage in .NET Core MVC .Net Core 3.1 将 Serilog 与 Microsoft.Extensions.Logger 一起使用 - .Net Core 3.1 Using Serilog with Microsoft.Extensions.Logger Net Core 3.0 和 Serilog 产生 output 像 Microsoft.Extensions.Logging - Net Core 3.0 and Serilog producing output like Microsoft.Extensions.Logging
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM