比方说,我的工作在VB.Net一个小批量处理控制台应用程序。我希望能够构建这样的应用程序:
子WorkerMethod()
做了一些工作
Trace.WriteLine(工作进度)
做更多的工作
Trace.WriteLine(另一个最新进展)
'...
结束小组
副主()
做任何设置,如确认用户希望继续或什么
WorkerMethod()
结束小组
请注意,我使用跟踪
,而不是控制台
我的输出。这是因为工人的方法可以从其他地方调用,甚至生活在一个不同的装配,而我希望能够附加不同的跟踪监听到它。那么,如何连接控制台的痕迹?
我已经可以做到这一点通过定义一个简单的类(如下图所示),并添加一个实例来跟踪的监听器集合,但我不知道是否有一个比较公认的或内置的方法来做到这一点:
公共类ConsoleTrace
继承Diagnostics.TraceListener
公共重载覆盖子写(BYVAL消息作为字符串)
Console.Write(消息)
结束小组
公共重载覆盖子的WriteLine(BYVAL消息作为字符串)
Console.WriteLine(消息)
结束小组
末级
解决方案
您可以按照您的exe文件的config文件中添加。
< XML版本=1.0&GT?;
<结构>
< System.Diagnostics程序>
<跟踪自动冲洗=真正的>
<听众>
<添加名称=的LogListenerTYPE =System.Diagnostics.TextWriterTraceListenerinitializeData =cat.log/>
<添加名称=consoleListenerTYPE =System.Diagnostics.ConsoleTraceListener/>
< /听众>
< /跟踪>
< /system.diagnostics>
< /结构>
我包括TextWriter的为好,如果你是到一个文件感兴趣的记录。
Let's say I'm working on a little batch-processing console app in VB.Net. I want to be able to structure the app like this:
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
Note that I'm using Trace
rather than Console
for my output. This is because the worker method may be called from elsewhere, or even live in a different assembly, and I want to be able to attach different trace listeners to it. So how can I connect the console to the trace?
I can already do it by defining a simple class (shown below) and adding an instance to the Trace's listeners collection, but I'm wondering if there's a more accepted or built in way to accomplish this:
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
解决方案
You can add the following to your exe's .config file.
<?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>
I included the TextWriter as well, in case you're interested in logging to a file.