Nlog: [Question] : How to Ignore a property?

Created on 2 Feb 2019  路  5Comments  路  Source: NLog/NLog

Hi,
When using structured logging like :
_logger.Log('Data: {@data}', data);
This logs every property of data with extremely high depth, so I want to ignore a property from being serialized by attribute or something or limit the Max Depth of logger.
I tried [JsonIgnore] and [IgnoreDataMember] and excludeProperties on Target but they didn't work.

question

Most helpful comment

Sounds like a good idea to support IgnoreDataMember-attribute for properties. PR are welcome.

You can inject your own IJsonConverter at NLog.Config.ConfigurationItemFactory.Default.JsonConverter and do special handling for your special object:

See also: https://github.com/NLog/NLog/wiki/How-to-use-structured-logging#i-like-to-use-jsonnet-for-creating-json

This way you can inject your own special converter that handles wanted types, or else just forwards the call to the defaultConverter:

var defaultConverter = NLog.Config.ConfigurationItemFactory.Default.JsonConverter;
var newConverter = new MyConverter(defaultConverter);
NLog.Config.ConfigurationItemFactory.Default.JsonConverter = newConverter;

All 5 comments

Sounds like a good idea to support IgnoreDataMember-attribute for properties. PR are welcome.

You can inject your own IJsonConverter at NLog.Config.ConfigurationItemFactory.Default.JsonConverter and do special handling for your special object:

See also: https://github.com/NLog/NLog/wiki/How-to-use-structured-logging#i-like-to-use-jsonnet-for-creating-json

This way you can inject your own special converter that handles wanted types, or else just forwards the call to the defaultConverter:

var defaultConverter = NLog.Config.ConfigurationItemFactory.Default.JsonConverter;
var newConverter = new MyConverter(defaultConverter);
NLog.Config.ConfigurationItemFactory.Default.JsonConverter = newConverter;

Another quick option is to:

  • Write the ToString on your type and do a data.ToString()
  • Convert the instance before logging

I assume your question has been answered, if not, please let us know!

What about doing this when using DI such as Autofac?

NLog 5.0 will make it easier to override the IJsonConverter by hooking up a dependency-injection-container. See also: #3666

NLog 4.7 will includes #3610 that will allow one to transform objects into anonymous-objects with only the wanted properties.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

imanushin picture imanushin  路  3Comments

MaximRouiller picture MaximRouiller  路  3Comments

npandrei picture npandrei  路  3Comments

ErcinDedeoglu picture ErcinDedeoglu  路  3Comments

imanushin picture imanushin  路  3Comments