mercredi 7 août 2019

Using Reflection to log the Properties of a type

I want a clear and efficient way to log the values of all properties of any type.

The use case is that I have a number of APIs where there may be any type of model that is being passed.

So my code is quickly becoming cluttered with logging statements.

I'm thinking of utilizing Reflection to help with this, but I've never used Reflection in production code before. and I'm concerned of any performance issues that may arise by doing this.

I've created this extension method to my custom logger where I pass the object that I want to log as a generic type T.


    public static class MyLoggerExtensions
    {
        public static void AddObject<T>(this IMyLogger logger, T obj)
        {
            PropertyInfo[] properties = typeof(T).GetProperties();
            properties
                .Where(p => p.CanRead)
                .ToList()
                .ForEach(p =>
                    logger.AddProperty(p.Name, p.GetValue(obj).ToString()));
        }
    }


Please tell me if this use of reflection has the potential to degrade performance of my APIs?





Aucun commentaire:

Enregistrer un commentaire