Logging Serializable Objects

Here’s a handy method to log your object serialized as XML

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
//
public void LogObject(object obj)
{
	var msg = "";
	try
	{
		using (var w = new StringWriter())
		{
			var s = new XmlSerializer(obj.GetType());
			s.Serialize(w, obj);
			w.Flush();
			msg = w.ToString();
		}
	}
	catch (Exception e)
	{
		msg = e.Message.ToString();
	}
 
	msg = string.Format("{0}\n{1}", obj.GetType(), msg);
	Log.Debug(msg);
}
 
LogObject(msgHeader);
//

This is what my logger spit out

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
OTA_TravelItineraryReadNS2_2_0.MessageHeader
<?xml version="1.0" encoding="utf-16"?>
<MessageHeader xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns="http://www.ebxml.org/namespaces/messageHeader">
  <From>
    <PartyId>55555</PartyId>
  </From>
  <To>
    <PartyId>789789789</PartyId>
  </To>
  <CPAId>2WE2</CPAId>
  <ConversationId>130615-120130.2844</ConversationId>
  <Action>TravelItineraryReadLLSRQ</Action>
  <MessageData>
    <MessageId>mid:200051209-18808-23933@clientofsabre.com</MessageId>
  </MessageData>
</MessageHeader>

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.