将跟踪输出重定向到控制台 [英] Redirect Trace output to Console

查看:41
本文介绍了将跟踪输出重定向到控制台的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我正在 VB.Net 中开发一个小的批处理控制台应用程序.我希望能够像这样构建应用程序:

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

请注意,我的输出使用的是 Trace 而不是 Console.这是因为 worker 方法可能会从其他地方调用,甚至可能存在于不同的程序集中,我希望能够将不同的跟踪侦听器附加到它.那么如何将控制台连接到跟踪?

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?

我已经可以通过定义一个简单的类(如下所示)并将一个实例添加到 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

推荐答案

您可以将以下内容添加到您的 exe 的 .config 文件中.

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>

我也包含了 TextWriter,以防您有兴趣登录到文件.

I included the TextWriter as well, in case you're interested in logging to a file.

这篇关于将跟踪输出重定向到控制台的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆