假设我正在 VB.Net 中开发一个小型批处理控制台应用程序。我希望能够像这样构建应用程序:
Sub WorkerMethod()
'Do some work
Trace.WriteLine("Work progress")
'Do more work
Trace.WriteLine("Another progress update")
'...
End Sub
Sub Main()
'Do any setup, like confirm the user wants to continue or whatever
WorkerMethod()
End Sub
请注意,我使用 Trace
而不是 Console
进行输出。这是因为工作方法可能从其他地方调用,甚至位于不同的程序集中,并且我希望能够向其附加不同的跟踪监听器。那么如何将控制台连接到跟踪呢?
我已经可以通过定义一个简单的类(如下所示)并向 Trace 的监听器集合添加一个实例来做到这一点,但我想知道是否有更容易接受或内置的方法来完成此操作:
Public Class ConsoleTrace
Inherits Diagnostics.TraceListener
Public Overloads Overrides Sub Write(ByVal message As String)
Console.Write(message)
End Sub
Public Overloads Overrides Sub WriteLine(ByVal message As String)
Console.WriteLine(message)
End Sub
End Class
最佳答案
您可以将以下内容添加到 exe 的 .config 文件中。
<?xml version="1.0"?>
<configuration>
<system.diagnostics>
<trace autoflush="true">
<listeners>
<add name="logListener" type="System.Diagnostics.TextWriterTraceListener" initializeData="cat.log" />
<add name="consoleListener" type="System.Diagnostics.ConsoleTraceListener"/>
</listeners>
</trace>
</system.diagnostics>
</configuration>
我还包含了 TextWriter,以防您有兴趣记录到文件。
关于.net - 将跟踪输出重定向到控制台,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/198322/