phuongnd
phuongnd

Reputation: 1289

How to ignore log property base on class type with Serilog

I'm implement AOP using Serilog to log all method call and parameters value
Here is my code:

_logger.ForContext(targetType).Information("INVOKE {@guid} {@MethodName} with parameters {@arg}", guid, invocation.Method.Name, invocation.Arguments);

However, some parameter type cannot to be log as DataTable, DataSet, Image, byte[] ...
How can I ignore these type in Serilog?

Upvotes: 1

Views: 2715

Answers (1)

C. Augusto Proiete
C. Augusto Proiete

Reputation: 27868

An easy solution is to tell Serilog upfront that types such as DataSet, DataTable, etc. should be destructured as scalar values. E.g.

Log.Logger = new LoggerConfiguration()
    .Destructure.AsScalar(typeof(DataSet))
    .Destructure.AsScalar(typeof(DataTable))
    // ...
    .CreateLogger();

You can also use .Destructure.ByTransforming or .Destructure.ByTransformingWhere.

Another solution is to create a custom destructuring policy where you decide how to destructure different types:

Log.Logger = new LoggerConfiguration()
    .Destructure.With<IgnoreSomeTypesDestructuringPolicy>()
    // ...
    .CreateLogger();

public class IgnoreSomeTypesDestructuringPolicy : IDestructuringPolicy
{
    public bool TryDestructure(object value, ILogEventPropertyValueFactory propertyValueFactory, out LogEventPropertyValue result)
    {
        if (value is DataTable || value is DataSet /* ... */)
        {
            result = new ScalarValue(value.ToString());
            return true;
        }

        result = null;
        return false;
    }
}

Upvotes: 4

Related Questions