如何对枚举强制执行 Serilog 标记
How to enforce Serilog tagging to an enum
我正在将我们的 log4net 记录器替换为使用 Serilog 的结构化日志记录。
我想使用枚举在代码中强制执行标记,但我在执行此操作时遇到了一些困难。
现在我的日志是这样的:
logger.ErrorFormat("Proxy Logic for the Item {Item} failed. Swallow exception", Item);
当 ErrorFormat
签名为
void ErrorFormat(string format, params object[] args);
但我不知道如何将 Item
替换为 LogTags.TagA
之类的东西。当 TagA 是一个枚举时,它会为我提供为我的标记执行统一标准的方法。
所以它看起来像:
public enum LogTags
{
TagA,
...
}
public class Foo
{
public void DoError()
{
logger.ErrorFormat("Proxy Logic for the Item {@LogTags.TagA} failed. Swallow exception", Item);
}
}
实现这种目标的最佳做法是什么?
属性 Serilog 中的名称需要是简单的非点标识符,因此 Enum.LogTags.Item
这样的名称不能直接使用。
如果简单的名称不合适,您可以使用类似下面的模式来强制嵌套:
logger.ErrorFormat(
"Proxy Logic for the Item {@Enum} failed. Swallow exception",
new { LogTags = new { Item }});
我正在将我们的 log4net 记录器替换为使用 Serilog 的结构化日志记录。 我想使用枚举在代码中强制执行标记,但我在执行此操作时遇到了一些困难。
现在我的日志是这样的:
logger.ErrorFormat("Proxy Logic for the Item {Item} failed. Swallow exception", Item);
当 ErrorFormat
签名为
void ErrorFormat(string format, params object[] args);
但我不知道如何将 Item
替换为 LogTags.TagA
之类的东西。当 TagA 是一个枚举时,它会为我提供为我的标记执行统一标准的方法。
所以它看起来像:
public enum LogTags
{
TagA,
...
}
public class Foo
{
public void DoError()
{
logger.ErrorFormat("Proxy Logic for the Item {@LogTags.TagA} failed. Swallow exception", Item);
}
}
实现这种目标的最佳做法是什么?
属性 Serilog 中的名称需要是简单的非点标识符,因此 Enum.LogTags.Item
这样的名称不能直接使用。
如果简单的名称不合适,您可以使用类似下面的模式来强制嵌套:
logger.ErrorFormat(
"Proxy Logic for the Item {@Enum} failed. Swallow exception",
new { LogTags = new { Item }});