How to identify generic objects in exception logs?

129 views Asked by At

I have a helper method that accepts parameters with generic types. This method can throw exceptions, which I log in order to debug later. Some objects have ids, some have names, etc., that would be useful to know when trying to debug. How can I log this information in a useful way?

2

There are 2 answers

1
bjaksic On BEST ANSWER

Regardles if it is a generic method or not, unless your object is null, you can log the type with myObject.GetType().ToString()

Loger.log("Object type that has thrown an error is" + myObj.GetType().ToString());

EDIT:

If you would like to read more information from the object then you can read object properties like this:

Type type = myObj.GetType();
List<string> info = new List<String>();
info.Add("Object type that has thrown an error is: " + type.ToString() + Environment.NewLine);
foreach (var prop in type.GetProperties())
{
    if (prop.CanRead)
    {
        info.Add("Name: " + prop.Name + " , Value: " + prop.GetValue(myObj) + Environment.NewLine);
    }
}
Logger.log(string.Join("", info));

This should work without any problems for primitives. For Objects it depends on how the ToString method is implemented. Also note that it will not read recursively, just the direct members of the class.

0
Grax32 On

This function returns a C# style type name (something like List<String> or List<Dictionary<Int32,String>>) from a type.

public static string FancyTypeName(Type type)
{
    var typeName = type.Name.Split('`')[0];
    if (type.IsGenericType)
    {
        typeName += string.Format("<{0}>", string.Join(",",
             type.GetGenericArguments().Select(v => FancyTypeName(v)).ToArray())
           );
    }
    return typeName;
}