May 1, 2022

Logging Assertions in ASP .Net Core

Sometimes it useful to extend the logging system so that you can log assertions/code contracts. Simple logger add-on so that assertions/code contracts can be logged in ASP.Net:
using System.Runtime.CompilerServices;

public static class ILoggerAssertionExtender
{
  public static bool Assert(this ILogger logger, 
    Func<bool> predicate, 
    Func<string> message)
  {
      bool assertion = predicate();
      if (!assertion)
      {
          logger.LogError("Code contract/assertion failed :" + message());
      }
      // The assertion outcome is returned so the user can react to it (throw an exception, 
      // insert a DebuggerBreak(), ...) after the logging is done.
      return assertion; 
  }
  
  // This one adds Caller attributes to get more details
  public static bool CallerAssert(this ILogger logger, 
    Func<bool> predicate,
    Func<string> message,
    [CallerMemberName] string member = "", 
    [CallerFilePath] string file = "", 
    [CallerLineNumber] int line = -1)
  {
      bool assertion = predicate();
      if (!assertion)
      {
          logger.LogError($"Code contract/assertion failed in Member {member}, File {file}, Line {line}: " + message());
      }
      // The assertion outcome is returned so the user can react to it (throw an exception, 
      // insert a DebuggerBreak(), ...) after the logging is done.
      return assertion; 
  }
}

No comments: