Change how System.Type is serialized in Serilog

Viewed 60

I using Serilog and have several log methods that log a type. Currently when it is converted to a string the result is the full name including the namespace. How do I change that to remove the Namespace (to shorten the log messages somewhat)?

Log.Information("Type is {type}", typeof(System.Int32));
//Renders as 'Type is System.Int32'.  I would prefer 'Type is Int32'.
1 Answers

Maybe:

  1. Custom wrapper around the original Serilog-interface

  2. Simple helper

      internal static class Helper
      {
          public static string GetName(this Type type)
          {
             if (type == typeof(int))
                 return "Type is Int32";
    
             // other cases here...
    
             return string.Empty;
          }
       }
    
     internal static class Program
     { 
         public static void Main()
         {
             Console.WriteLine($"Type: {typeof(int).GetName()}");
         }
     }
    

You can also use a hash table to lookup types with their corresponding descriptions, so you'd save all these if..else.

Regards

Related