Upgrading and publishing ILogger Data Extensions

Posted by

I previously wrote about Using Extension Methods for Easy Improved Logging, where I was leveraging extension methods to take an object and log it’s JSON representation with log4net. In .NET Core, we now have ILogger provided by Microsoft.Extensions.Logging, so I figured it would be good to revisit those extension methods.

The source code changes were pretty minimal, in that not much needed to be changed except I now wanted to be targeting an ILogger instead of the log4net logger. I also went through to adjust the method names to be prefixed with “Log” and extend the level text (so, for example, “_log.Warn()” is now “_log.LogWarning()”). Lastly, Microsoft’s ILogger takes an exception as the first argument if one exists, where log4net doesn’t. For my data extensions, I took the naming of methods from the ILogger and appended “Data” at the end. An example log data extension is below:

public static void LogErrorData(this ILogger log, object obj, 
    Exception ex = null, string note = "", 
    [CallerMemberName] string memberName = "") 
    StringBuilder builder = new StringBuilder();
    if (memberName != "")
         builder.Append($"Error in function {memberName}. ");
    if (note != "")
        builder.Append($"Note: {note}. ");     
    if (ex != null)
        builder.Append($"Exception: {ex.Message}, ");
    var json = JsonConvert.SerializeObject(obj,
         new JsonSerializerSettings()
             ReferenceLoopHandling = ReferenceLoopHandling.Ignore
     var objName = obj.GetType().Name;
     builder.Append($"Object name: {objName}, Data: {json}");
     if (ex != null)
         log.LogError(ex, builder.ToString());

So, now that I have an up to date ILogger data extensions project, I wanted to go ahead and open source it. Open sourcing is a piece of cake, as you can just throw up some code publicly accessable to GitHub.com. The GitHub repository that I created for it is located here: https://github.com/mvalenta/ILoggerDataExtensions. While open sourcing the code makes it easy to be used, it’s nice to just have a nuget package where you can simply add it in as a dependency to a .NET Core project. Thus, I went ahead and created a package on nuget.org and published it out for anyone to use, located here: https://www.nuget.org/packages/ILoggerDataExtensions/.

I do still have some work to do around signing the packages, setting up a continuous delivery setup, and ensuring version compatibility, along with adding documentation on the GitHub repository via the readme.md. However, it’s nice to not only create reusable extension methods to assist with improving logging, but also share that capability with the developer community.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.