Saturday, August 17, 2019

Another LoggerWrapper

So another logger wrapper ...

In  I was working on project which should also provide library for third party developers.
And there was logging ... So main problem was we had been used an version of Log4Net and another team has been using another version ...
So we recognized that library version lock problem.

First solution was to hide our version by Costura Fody, which was not working very well, and then ... then there was more difficult solution to use reflection.

And here is : AnotherLoggerWrapper

Simple idea is that there is an interface similar to Log4Net, with some implementations, which you can use in your project, and if somebody would like to use  your library then he can provide an object which then will be "investigated" by reflection, if it is compatible with Log4Net common interface, and then will be used. Used means - delegates will be produced, so it is not so slow.

There are examples in unit tests of GitHub project LoggerWrapper.

Example - how to use :

            var logger = LoggerWrapper.CreateFromILogLikeObject(loggerMock.Object);
            logger.Info(
"testMessage");1. How delegate is created:

Example - how delegates are created:

1. MethodInfo
        private static MethodInfo GetWriteMessageMethodInfo(MethodInfo[] methods, String methodName)
        {
           
var specificMethods = from mi in methods
                                  let p = mi.GetParameters()
                                 
where p.Length == 1
                                        && (p[
0].ParameterType == typeof(object) || p[0].ParameterType == typeof(string))
                                        && mi.Name == methodName
                                        && mi.IsStatic ==
false
                                        && mi.IsPublic
                                 
select mi;
           
var specificMethodsArray = specificMethods.ToArray();
           
if (specificMethodsArray.Count() == 1)
            {
               
return specificMethodsArray[0];
            }
           
return null;
        } 2. Delegate from method info         private static LogMethods.WriteObject GetWriteMessageMethod(MethodInfo methodInfo, Object instance)
        {
            LogMethods.WriteObject method =
null;
           
if (methodInfo != null)
            {
                method = (LogMethods.WriteObject) Delegate.CreateDelegate(
typeof (LogMethods.WriteObject), instance, methodInfo);
            }

           
return method;
        } I also enjoyed development of unit tests of this project, so whole project is just fun ... Enjoy !