将跟踪输出重定向到控制台
假设我正在 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
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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您可以将以下内容添加到 exe 的 .config 文件中。
如果您有兴趣记录到文件,我还包含了 TextWriter。
You can add the following to your exe's .config file.
I included the TextWriter as well, in case you're interested in logging to a file.
Joel,
您可以执行此操作而不是应用程序配置方法:
或者,如果您想在应用程序的生命周期中管理添加或删除侦听器:
Joel,
You could do this instead of the app config method:
or this, if you want to manage adding or removing the listener during the life of the app:
很好的解决方案,但我遇到的情况是同一个调用 exe 运行不同的 dll,所以我不想修改调用 exe 的 .config 文件。 我希望每个 dll 都能处理它自己对跟踪输出的更改。
很简单:
当然,这会将 Trace 输出输出到“output.txt”文件。
Great solution, but I have a situation where I have different dll's being run by the same calling exe, so I don't want to modify the calling exe's .config file. I want each dll to handle it's own alteration of the trace output.
Easy enough:
This will, of course, output Trace output to the "output.txt" file.