我们使用 serilog 从 .nrt 核心应用程序输出。我们使用紧凑的 json 来缩小尺寸。在紧凑中,它似乎将错误键与 @ 符号放在一起;
“@l”:“警告”
我似乎无法让过滤器工作,它要么不返回结果,要么显示错误。我尝试了很多方法,但我确信这应该有效;
{ $.@l = "警告" }
任何人都建议我哪里出错了。
我认为您不能在选择器中使用
@
。来自文档:
属性选择器是字母数字字符串,也支持“-”和“_”字符。
解决这个问题的一种方法是匹配该行,就好像它不是 json 的一部分一样。
例如,如果您的日志行如下所示:
"@l": "Warning"
你可以用以下方法过滤掉它:
[key="@l", colon, value=Warning]
我也有同样的问题。您很可能像我一样使用 Serilog.Formatting.Compact.CompactJsonFormatter。
实现自己的 ITextFormatter 是一种解决方法,因为像 @ 或 $ 这样的前缀是硬编码在 CompactJsonFormatter 中的。
我使用 CompactJsonFormatter 作为基础,将 @、$ 的用法替换为 s_,它就可以工作了。
不幸的是,这仍然是 AWS CloudWatch 中的一个问题。我想出了以下基于普遍存在的 CompactJsonFormatter 的类,并将其作为默认包装器。 (可选)您可以提供另一个 ITextFormatter(如 RenderedCompactJsonFormatter),并提供备用 ITextFormatter 使用的新的 ReifiedPropertyNames 列表。
public class CloudWatchCompactJsonFormatter : ITextFormatter {
public string DefaultReifiedPropsPrefixSigil { get; init; } = "@";
public string ReplacementReifiedPropsPrefixSigil { get; init; } = "_";
public ITextFormatter TextFormatter { get; init; } = new CompactJsonFormatter();
public List<string> ReifiedProperties { get; init; } = ["t", "mt", "r", "l", "x", "tr", "sp"];
public void Format(LogEvent logEvent, TextWriter output)
{
using var sw = new StringWriter();
TextFormatter.Format(logEvent, sw);
var log = sw.ToString();
foreach (var p in ReifiedProperties)
{
log = log.Replace($"\"{DefaultReifiedPropsPrefixSigil}{p}\":", $"\"{ReplacementReifiedPropsPrefixSigil}{p}\":");
}
output.Write(log);
} }
像往常一样在您的 Program.cs 中实现它:
builder.Host.UseSerilog((context, configuration) => { configuration.WriteTo.Console(new CloudWatchCompactJsonFormatter());});
现在您可以使用如下过滤器搜索 CloudWatch 日志流:
{ $._l = "Warning" }
希望有帮助!