开发者

write xml format log file

Our customized logging sysem saves info into a xml file, like this:

<?xml version="1.0" standalone="yes"?>
<log>
<entry> msg </entry>
<entry> msg </entry>
.
.
.
</log>

Right now we are using StreamWriter to write. If the system crashes (we are in the middle of the development), the end tag/element, </log>, will not be written to the file so the xml file cannot be opened correct with IE. I found there are two possible options to correct this:

Option A: write the end tag at very beginning when file is initialized and then do "insert" for each new entry. right now we are doing "append".

Option B: change to XmlDocument or XmlWriter.

In option A,开发者_运维知识库 change "append" to "insert", we need to keep the current location, which is right before the end tag, </log>,. And write from that current location. I didn't find a good way to do this.

In option B, the XmlWriter is almost the same as other stream/writer. No easy way to "insert". The XmlDocument is easy to "insert", but there is no Flush() method to call. we have to Save() to make it write to file. If the Save() means close the stream/file, I don't want to do Load() and Save() for each entry. that will be too expensive, I think.

do you have any good idea about this?


I would set a global exception handler: that way you could finalize the log, but most important you can collect details relevant to the failure (a stacktrace but also memory state, etc.). In my experience this has always been very effective to understand crashes later on when the system is running "in the wild".


You can use the Enterprise Library that allow you to log to a XML file and much much more. I strongly recomend that you, at least, take a look at that. But if you just want to write a XML log without the other goods from EntLib you can try log4Net for example.


You might want to think about using try ... catch ... finally when writing the log file(s). Then if the main method (for writing the logs) fails, inside of the finally switch to a different method and/or location (if needed) and continue writing the log.


You may want to consider implementing an unhandled exception filter in your application and take care of cleanly flushing your logs there. Take a look at this blog post for information.


Are you sure about using xml for logging? You can try html for you purposes.

<title>Cool log</title>
<pre>Started</pre>
<pre>Finished</pre>
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜