[2005] Stringbuilder & level declaration
Hi all,
I was wondering something. Is it a good idea to declare a StringBuilder object as a class level variable?
For instance, I have a variable called CLogText that is declared at the class level. I use this object to build error messages each time an exception is thrown, and write it to a log.
I know I can keep appending text to it, but I want each exception entry to be separate.
The way I was thinking of doing it would be to keep the class level declaration, but just clear the buffer each time I write an exception like so:
Code:
ClogText.Replace(ClogText.ToString, " ")
I'd really like to avoid declaring a new StringBuilder in each procedure. Just trying to make as many reuseable objects as I can.
Mods, I didn't know exactly what forum this fit into. I just put it in here because it's a web application.
Re: [2005] Stringbuilder & level declaration
Re-use is something to be kept in mind & encouraged, although I think re-using to this degree may be more counter-productive than expected. As an example, hard to track issues may be introduced should the builder not be cleared (or cleared) in the expected order.
Also, I'm confident .NET (garbage collection, string interning) would handle this very efficiently, so introducing "as many" reusable objects may be a little OTT. As it's a web app, unless the logging procedures are statically hosted or state is maintained across requests, the object lifetimes will be tied to the request anyway.
To the specific question of logging: would a framework, e.g. log4net, be a little friendlier on the eyes, feasible (as some companies are somewhat difficult about third party libraries), or are you trying to implement a logging system for learning purposes?
Re: [2005] Stringbuilder & level declaration
We already have a class that actually writes the text to a file on the server. No third party tools are allowed unless they are available for download on the company download page.
Re: [2005] Stringbuilder & level declaration
What would be the point of that, really? You're only setting yourself up for more points of failure in case someone writes methods there and forgets to clean up after himself (or before).
Let the GC handle it, encapsulate your StringBuilder in the method it's required in.