gpt4 book ai didi

c# - 使用当前的 Serilog ILogger 实例将消息格式化为字符串(但不打印)

转载 作者:行者123 更新时间:2023-12-04 10:56:26 27 4
gpt4 key购买 nike

我有一个自定义 LogEntry专为轻松序列化而设计的类。在对要发送给用户的对象执行操作时,会出现一些日志条目。我还想将这些相同的条目发送到控制台/配置的任何 serilog 接收器。我目前的方法是这样的:

public static void Info(this Case c, ILogger log, string message, params object[] values)
{
log.Information(message, values);
var formattedMessage = string.Empty; // TODO: use serilog to get the string.
// This is what I'm asking for help on!
var entry = new LogEntry
{
LogLevel = LogLevel.Info,
Message = formattedMessage,
PhaseType = c.CurrentPhase // <- it would be convenient if I could enrich
// the current serilog log with this info,
// but I don't know how to do that either.
};

c.Log.Add(entry);
}

我在哪里 Case class 是一个准备发送到 newtonsoft 进行序列化的 POCO。为了完整起见, Case类包含此定义:
public class Case
{
// ...

public List<LogEntry> Log { get; set; } = new List<LogEntry>();
}

也许我的方法是完全错误的。希望我已经给出了足够的上下文来解释我想要完成的任务。如果这个问题让我走上了一条更快乐的道路:如何为 ILogger 创建自定义临时接收器实例?

最佳答案

一种选择是收集 Serilog LogEvent s 由记录器调用创建并使用它们来构造呈现的消息。

这是总体思路的可执行草图。

using System;
using System.Collections.Generic;
using Serilog;
using Serilog.Core;
using Serilog.Events;

// dotnet add package Serilog.Sinks.Console

class LogEventCollection : ILogEventEnricher
{
// Note, this is not threadsafe
public List<LogEvent> Events { get; } = new List<LogEvent>();

public void Enrich(LogEvent logEvent, ILogEventPropertyFactory _)
{
Events.Add(logEvent);
}
}

class Program
{
static void Main(string[] args)
{
Log.Logger = new LoggerConfiguration()
.WriteTo.Console()
.CreateLogger();

var collection = new LogEventCollection();

// Create an `ILogger` with the collector wired in. This
// also works with `LogContext.Push()`.
var collected = Log.ForContext(collection);

collected.Information("Hello");
collected.Information("World");

// One entry for each call above
foreach (var evt in collection.Events)
{
Console.WriteLine(evt.RenderMessage(null));
}
}
}

输出:
[14:23:34 INF] Hello
[14:23:34 INF] World
Hello
World

关于c# - 使用当前的 Serilog ILogger 实例将消息格式化为字符串(但不打印),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59147565/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com