I have a log tool for my applications. I log to XML in a hierarchical manner (this means that I can nest log items). My Log(string, bool) takes two parameters, one with the string to log and a bool value determining if this comment should be nested below the previous log comment. A PopLog() method is made to go to the parent, and continue logging on the parent level.
This means that when I log like this:
Log("first", false);
...
Log("Second", true);
...
Log("Third", true);
PopLog();
PopLog();
PopLog();
This gives the following result:
<first>
<second>
<third>
</second>
</first>
The problem I have with the current design is it is hard to keep track of my log level, how deep I am in the logging tree, and whether or not I need to pop, log using true, or log using false.
Any good ideas on how to make this simpler, more maintainable and better (changing log provider is not an option)?
A better design would be, IMO, to separate the push/pop behaviour from the logging itself. Here’s a solution in C#, using
IDisposable:This way, you can do something like: