更新时间:2023-12-05 12:19:46
这可能需要更多的工作,但我会反其道而行之.
This may be some kind of more work, but I would go the other way round.
为控制台实例化一个TraceListener
,为日志文件实例化一个;此后在您的代码中使用 Trace.Write
语句而不是 Console.Write
.之后删除日志或控制台输出或附加其他日志记录机制变得更容易.
Instantiate a TraceListener
for the console and one for the log file; thereafter use Trace.Write
statements in your code instead of Console.Write
. It becomes easier afterwards to remove the log, or the console output, or to attach another logging mechanism.
static void Main(string[] args)
{
Trace.Listeners.Clear();
TextWriterTraceListener twtl = new TextWriterTraceListener(Path.Combine(Path.GetTempPath(), AppDomain.CurrentDomain.FriendlyName));
twtl.Name = "TextLogger";
twtl.TraceOutputOptions = TraceOptions.ThreadId | TraceOptions.DateTime;
ConsoleTraceListener ctl = new ConsoleTraceListener(false);
ctl.TraceOutputOptions = TraceOptions.DateTime;
Trace.Listeners.Add(twtl);
Trace.Listeners.Add(ctl);
Trace.AutoFlush = true;
Trace.WriteLine("The first line to be in the logfile and on the console.");
}
据我所知,您可以在应用程序配置中定义侦听器,从而可以在不接触构建的情况下激活或停用日志记录.
As far as I can recall, you can define the listeners in the application configuration making it possible to activate or deactivate the logging without touching the build.