Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

log4net complex type logging

Tags:

c#

log4net

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);
like image 812
Bilgehan Avatar asked Oct 22 '25 19:10

Bilgehan


1 Answers

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.

like image 138
Barr J Avatar answered Oct 25 '25 08:10

Barr J