I have a fairly large program (C#) that needs its functionality expanded by adding an option to turn off logging. The program takes a directory location as an argument, where it stores the log. I want it to not log anything if args[0] is empty. Right now the program has lines like this nested all over it:
DiagnosticLog.WriteLine("\t\t----Verifying Plugins were installed correctly----");
My first idea was to 开发者_StackOverflow中文版just create and do a check for a global flag within that function and run that line if it wasn't set. That way I could avoid using the same if statement around each of these lines all over the code. Is there a more clever way of just "turning off" these lines during run-time?
You could implement a version of DiagnosticLog
that doesn't actually log anything, and use it in stead of your logging version if you don't want to log. That's assuming you know whether or not you want to log when you create the instance of DiagnosticLog
(which I gather from the way you ask, you do).
How about modifying your DiagnosticLog.WriteLine
function to take a second parameter doActualLog
(bool
) which has as default value true
? Make some very minor modifications to DiagnoticLog
to take this value into account. You can then decide at instantiation of DiagnosticLog
if you want actual logging to happen or not.
You could just add an enabled
flag to DiagnosticLog
that is true
by default. If args[0] is empty, call DiagnosticLog.Disable()
to set it to false
. Then in WriteLine
and any other logging functions, check enabled
before doing the actual logging.
Why don't you just call a log function that checks to see if the arg is empty?
public void WriteLine(string log) {
if (!firstArgIsEmpty) {
// Print to file.
}
}
How about using a System.Diagnostics.TraceListener class in conjunction with a System.Diagnostics.TraceSwitch? The functionality you seem to be after is already baked in.
You could create a property
public bool Log { get; set; }
string logFilePath;
public string LogFilePath
{
get { return logFilePath; }
set
{
logFilePath = ValidateLogFilePath(value);
Log = logFilePath.Length > 0;
}
}
public void WriteLine(string line)
{
if (!Log)
return;
//...
}
If you make a boolean property to indicate whether logging is occuring, then you could also use it to skip other sections of code that are not necessary if logging is not occuring. This could be useful if you are building any long strings just for logging purposes.
if (DiagnosticLog.Log)
{
DiagnosticLog.WriteLine("The following plugins were not installed:\r\n\t" +
string.Join("\r\n\t", GetMissingPluginNames()));
}
精彩评论