这是我的Winforms应用程序中的配置文件。目前已将MyTraceSource注释掉,如果我取消注释并运行我的程序,它将按预期工作。我从引用的库中输出到我的控制台。 MyTraceSource是一个Trace源,它在我引用的库中实例化并使用,我称之为MyOposServiceObject。您会注意到我在名为TestApplication的Logger.cs文件中设置了另一个TraceSource。该跟踪源是我在测试应用程序中使用的日志记录(逻辑名称是什么......)就这样我很清楚有2个跟踪源实例化并在2个不同的项目中使用。一个是类库,另一个是winforms应用程序。如果我将我的winforms应用程序编译为控制台程序并在app.config文件中取消注释我的TraceSource,我将从MyOposServiceObject登录到控制台。清楚如泥?好的一些代码。
的App.config
<system.diagnostics>
<trace autoflush="true"/>
<sharedListeners>
<!-- Outputs to a Log File-->
<add name ="file" type ="System.Diagnostics.TextWriterTraceListener" initializeData="DEMO.log">
<filter type="System.Diagnostics.EventTypeFilter" initializeData="Off"/>
</add>
<!-- Outputs to the console-->
<add name="console" type ="System.Diagnostics.ConsoleTraceListener" >
<filter type="System.Diagnostics.EventTypeFilter" initializeData="All"/>
</add>
</sharedListeners>
<sources>
<!--<source name="MyTraceSource" switchValue="All" >
<listeners>
<remove name="Default"/>
<add name="console"/>
</listeners>
</source>-->
</sources>
</system.diagnostics>
但是,我不希望我的程序成为控制台程序,因此我创建了一个自定义TraceListener。
MyTraceListener.cs
public class MyTraceListener : TraceListener
{
private System.Windows.Forms.TextBox output;
public MyTraceListener(System.Windows.Forms.TextBox output)
{
this.Name = "FancyTrace";
this.output = output;
}
public override void Write(string message)
{
output.SafeSetText(string.Format("{0}\r\n[{1}] {2}",output.Text, DateTime.Now.ToString("F"), message));
}
public override void WriteLine(string message)
{
Write(message + Environment.NewLine);
}
}
我把它连接起来
Logger.cs
internal static void ShowDebugWindow()
{
if (debugWindow != null) return;
debugWindow = new Form();
debugWindow.TopMost = true;
debugWindow.FormBorderStyle = FormBorderStyle.FixedToolWindow;
TextBox tb = new TextBox();
tb.Multiline = true;
tb.Dock = DockStyle.Fill;
debugWindow.Controls.Add(tb);
MyTraceListener myTrace = new MyTraceListener(tb);
trace.Listeners.Add(myTrace);
opos.Listeners.Add(myTrace);
debugWindow.Show();
}
private static TraceSource trace = new TraceSource("TestApplication");
private static TraceSource opos = new TraceSource("MyTraceSource");
现在trace
在此应用程序中使用,并且它的输出确实进入我的小调试窗口。但我从opos得不到任何东西。我做错了什么?
答案 0 :(得分:0)
总而言之,您希望两个项目中的所有TraceSource
都显示在您的小调试窗口,控制台和任何共享侦听器中,是否正确?
我假设您的应用结构如下:
- Solution
- Class Library
- MyTraceListener.cs
- Logger.cs
- OtherCodeThatUsesLogger.cs
- Winforms Project : References Class Library
- app.config
- WinformsCodeThatUsesLogger.cs
如果是这样,我认为这里的问题是你的消费代码没有使用你在Logger.cs中创建的TraceSource的实例。
Logger.cs
public static TraceSource trace = new TraceSource("TestApplication");
public static TraceSource opos = new TraceSource("MyTraceSource");
使用代码
void foo() {
Logger.trace.TraceInformation("hello... ");
Logger.opos.TraceInformation("muggles.");
}