• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 205
  • Last Modified:

Problem with LINQ XML logging

Hello Experts

I'm using LINQ to XML I have a bit of a problem with writing to a XML file. It seems that instead of inserting XML nods the framework is writing to the XML file as a streamer, line by line.

I'm using a XML file to record my program events aka logging. If the program is closed before all  processes are finished the XML logging file ends up being unfinished.

Example:
Initial log file:

<root>
<processInfo>
<\processInfo>
 <events>
  <event>
 //Logging event info
  <\event>
 <\events>
<root>

I would expect, as the process runs, for the program to keep the tags and just keep on adding <event> nods with log entries ( and it works fine if I let it run ) but if the process is interrupted I end up with something like this:

<root>
<processInfo>
<\processInfo>
 <events>
  <event>
  This is my logging event info. It was cut off in the mid
 
How can I avoid this problem and make sure that even if my program process is interrupted the XML Logging file closing tags are still there ?

Thank you.
<root>
<processInfo>
<\processInfo>
 <events>
  <event>
 //Logging event info
  <\event>
 <\events>
<root>

Open in new window

<root>
<processInfo>
<\processInfo>
 <events>
  <event>
  This is my logging event info. It was cut off in the mid

Open in new window

0
techsuppoprt
Asked:
techsuppoprt
  • 2
1 Solution
 
wdosanjosCommented:
Your logging class should implement IDisposable and have the necessary code in the Dispose method to properly finalize the file.

IDisposable Interface (System)
http://msdn.microsoft.com/en-us/library/system.idisposable.aspx
0
 
dimajCommented:
I've written a small blog article on how to manipulate XML files using LINQ. You can find it here: http://blog.dimaj.net/2011/02/howto-update-xml-file-using-linq/
0
 
techsuppoprtAuthor Commented:
The blog doesn't help much. It just has basic info how to use XDocument.Save().

Wdosanjos, I thought about collecting process log entries in a collection and then recording them to the XML file only at the using when Dispose() gets called. But what if the process freezes or user desires to end task it.. there will be no log file created correct ?
0
 
wdosanjosCommented:
Correct.  I meant the code in the Dispose method should complete the xml file (closing  <\events> and </root> tags) and closing the file.  As you pointed out buffering all the entries in memory and only writing at the very end won't work consistently.
0

Featured Post

Veeam Disaster Recovery in Microsoft Azure

Veeam PN for Microsoft Azure is a FREE solution designed to simplify and automate the setup of a DR site in Microsoft Azure using lightweight software-defined networking. It reduces the complexity of VPN deployments and is designed for businesses of ALL sizes.

  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now