I want to log complex type object in c# and to use log4net for logging. What is the correct approach to do this?I use filelogappender.So I want to see my entity in log.Should I do it to use stringbuilder class and convert my entity to string or serialize it to json or is log4net has a ability to this?
public class Person
{
Name {get;set;}
Surname{get;set;}
}
Person personobject=new Person("MyName","MySurname");
log4net.Log.Warn(personobject);
You cannot log complex types, the reason is very simple:
The logging mechanism perform an hard enough work - you have to open stream and close stream every time you log information.
The data you stream is mostly text, there is no easy way to parse a complex object into text representation so what you see, is the 'shallow' text representation of the type: 'Object object'.
The easy workaround is to serialize the object manually as JSON string, this way:
log4net.Log.Warn(Newtonsoft.Json.JsonConvert.SerializeObject(personobject));
This will serialize your type as string, not as object and so, you will be able to log any complex type you want.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With