Redirect Trace output to Console

a 夏天 提交于 2019-11-27 17:29:16

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.

Joel,

You could do this instead of the app config method:

Trace.Listeners.Add(new ConsoleTraceListener());

or this, if you want to manage adding or removing the listener during the life of the app:

ConsoleTraceListener listener = new ConsoleTraceListener();
Trace.Listeners.Add(listener);

Trace.WriteLine("Howdy");

Trace.Listeners.Remove(listener);

Trace.Close();

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:

Stream outResultsFile = File.Create ("output.txt");
var textListener = new TextWriterTraceListener (outResultsFile);
Trace.Listeners.Add (textListener);

This will, of course, output Trace output to the "output.txt" file.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!