assume this class:
public class Logger
{
static TextWriter fs = null;
public Logger(string path)
{
fs = File.CreateText(path);
}
public static void Log(Exception ex)
{
///do logging
}
public static void Log(string text)
{
///do logging
}
}
and I have to use this like:
Logger log = new Logger(path);
and then use Logger.Log() to log what I want. I just use one Logger.
the question is: is this a good design? to instantiate a class and then always call it’s static method? any suggestion yield in better design is appreciated.
Edit based on Marc‘s answer:
I flush on the last line of Log and there is no need for me to read the file while it is open, the issue with file not cleanly closed is right. this class simply satisfy my requirements and there is no need to be thread safe for it. I just want to get read of the instantiation part, I should get into the SetPath you said, any suggestion for closing file?
Yes, having a constructor just for this is bad design. A static
SetPathmethod that can only be called once (else throws an exception) would seem better. You would set the path during app-startup, etc.Then you can either make it a
static class, or a singleton if it is required to satisfy some interface-based scenario.Next: you must add synchronisation here! That is not thread safe. If two threads attempt to log at the same time, I would expect this to collapse horribly. It doesn’t need to be complex; at the simplest:
(but note that this may incur some blocking costs; which can be improved with more sophisticated code – see below)
There are existing logging libraries that will think of lots more issues – file partitioning, async (to stop your code being blocked by IO), batching, etc; why not just use one of them? In particular, at te moment your file will not be cleanly closed at app-exit, doesn’t flush regularly, and will keep the file locked most of the time. Not good.