为特定的 NLog 实例设置 ValueFormatter? [英] Set ValueFormatter for specific NLog instance?
问题描述
我有 2 个 NLog 实例,其中一个需要特殊的 ValueFormatter 来序列化参数.ValueFormatter 使用以下代码设置:
I have 2 NLog instances where one needs a special ValueFormatter to serialize parameters. The ValueFormatter is set with this code :
NLog.Config.ConfigurationItemFactory.Default.ValueFormatter = new NLogValueFormatter();
如您所见,它将应用于所有记录器.我在 NLogger 本身上找不到任何可能需要 ValueFormatter 的属性.
So as you can see it will be applied to all loggers. I can´t find any property on the NLogger itself that might take a ValueFormatter.
有没有办法将这个 ValueFormatter 绑定到一个记录器?
Is there any way to bind this ValueFormatter just to one of the loggers?
编辑 1:
private CommunicationFormatProvider provider = new CommunicationFormatProvider();
public void LogCommunication(string message, params object[] args)
{
_comLogger.Log(LogLevel.Info, provider, message, args);
}
public class CommunicationFormatProvider : IFormatProvider, ICustomFormatter
{
public string Format(string format, object arg, IFormatProvider formatProvider)
{
StringBuilder strBuilder = new StringBuilder();
strBuilder.Append(format);
var myTarget = LogManager.Configuration.FindTargetByName("communicationTarget");
myTarget = ((myTarget as NLog.Targets.Wrappers.WrapperTargetBase)?.WrappedTarget) ?? myTarget;
var jsonLayout = (myTarget as NLog.Targets.TargetWithLayout)?.Layout as NLog.Layouts.JsonLayout;
if (jsonLayout?.MaxRecursionLimit > 0)
strBuilder.Append(JsonConvert.SerializeObject(arg, new JsonSerializerSettings() { MaxDepth = jsonLayout?.MaxRecursionLimit }));
return strBuilder.ToString();
}
object IFormatProvider.GetFormat(Type formatType)
{
return (formatType == typeof(ICustomFormatter)) ? this : null;
}
}
编辑 2:
public bool FormatValue(object value, string format, CaptureType captureType, IFormatProvider formatProvider, StringBuilder builder)
{
if (value.GetType() == typeof(LogData))
return false;
builder.Append(format);
try
{
var myTarget = LogManager.Configuration.FindTargetByName("communicationTarget");
myTarget = ((myTarget as NLog.Targets.Wrappers.WrapperTargetBase)?.WrappedTarget) ?? myTarget;
var jsonLayout = (myTarget as NLog.Targets.TargetWithLayout)?.Layout as NLog.Layouts.JsonLayout;
if (jsonLayout?.MaxRecursionLimit > 0)
{
var jsonSettings = new JsonSerializerSettings() { MaxDepth = jsonLayout?.MaxRecursionLimit };
using (var stringWriter = new StringWriter())
{
using (var jsonWriter = new JsonTextWriterMaxDepth(stringWriter, jsonSettings))
JsonSerializer.Create(jsonSettings).Serialize(jsonWriter, value);
builder.Append(stringWriter.ToString());
}
}
else
value = null;
}
catch(Exception ex)
{
builder.Append($"Failed to serlize {value.GetType()} : {ex.ToString()}");
}
return true;
}
JSON Serializer from here:json.net 序列化时限制 maxdepth
JSON Serializer from here : json.net limit maxdepth when serializing
推荐答案
NLog JsonLayout 有两个对 LogEvent 属性序列化很重要的选项:
NLog JsonLayout has two options that are important for serialization of LogEvent Properties:
- 包括所有属性
- MaxRecursionLimit
默认参数是这样的:
<layout type="JsonLayout" includeAllProperties="false" maxRecursionLimit="0">
<attribute name="time" layout="${longdate}" />
<attribute name="level" layout="${level}"/>
<attribute name="message" layout="${message}" />
</layout>
但是您也可以像这样激活包含 LogEvent 属性:
But you can also activate inclusion of LogEvent properties like this:
<layout type="JsonLayout" includeAllProperties="true" maxRecursionLimit="10">
<attribute name="time" layout="${longdate}" />
<attribute name="level" layout="${level}"/>
<attribute name="message" layout="${message}" />
</layout>
如果您有这样的自定义对象:
If you have a custom object like this:
public class Planet
{
public string Name { get; set; }
public string PlanetType { get; set; }
public override string ToString()
{
return Name; // Will be called in normal message-formatting
}
}
然后你可以像这样记录对象:
Then you can log the object like this:
logger.Info("Hello {World}", new Planet() { Name = "Earth", PlanetType = "Water Planet" });
默认的 JsonLayout 将只包含默认属性,其中 message
-attribute 表示 Hello Earth
.
The default JsonLayout will just include the default attributes, where message
-attribute says Hello Earth
.
但是带有 includeAllProperties="true"
的 JsonLayout 将包含任何额外的 LogEvent 属性.并将包含已完全序列化的 World
-propety.
But the JsonLayout with includeAllProperties="true"
will include any additional LogEvent-properties. And will include World
-propety that has been serialized fully.
这个想法是人们不应该关心日志记录时 NLog 目标是如何配置的.Logging-Rules + Target-Configuration + Layout-Configuration 决定了最终应该如何编写.
The idea is that one should not care about how NLog Targets are configured when logging. It is the Logging-Rules + Target-Configuration + Layout-Configuration that decides how things should be finally written.
如果你真的想把对象序列化成${message}
,那么你也可以这样做:
If you really want the object to be serialized into ${message}
, then you can also do this:
logger.Info("Hello {@World}", new Planet() { Name = "Earth", PlanetType = "Water Planet" });
如果您不希望 LogEvent 属性与默认属性混合在一起,那么您可以这样做:
If you don't want the LogEvent-properties mixed together with your default properties, then you can do this:
<layout type="JsonLayout" maxRecursionLimit="10">
<attribute name="time" layout="${longdate}" />
<attribute name="level" layout="${level}"/>
<attribute name="message" layout="${message}" />
<attribute name="properties" encode="false">
<layout type="JsonLayout" includeAllProperties="true" maxRecursionLimit="10" />
</attribute>
</layout>
如果您有一个将字段与属性混合的对象,那么您可以告诉 NLog 为该类型执行自定义反射:
If you have an object that mixes fields with properties, then you can tell NLog to perform custom reflection for that type:
LogManager.Setup().SetupSerialization(s =>
s.RegisterObjectTransformation<GetEntityViewRequest>(obj =>
return Newtonsoft.Json.Linq.JToken.FromObject(obj) // Lazy and slow
)
);
这篇关于为特定的 NLog 实例设置 ValueFormatter?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!