これが、私の Winforms アプリケーションの構成ファイルです。現在、MyTraceSource はコメントアウトされています。コメントを外してプログラムを実行すると、期待どおりに動作します。参照ライブラリからコンソールに出力を取得します。MyTraceSource は、インスタンス化され、MyOposServiceObject と呼ぶ参照ライブラリで使用される Trace ソースです。Logger.cs ファイルに TestApplication という名前の別の TraceSource をセットアップしていることに気付くでしょう。そのトレース ソースは、テスト アプリケーションで使用するログです (なんて論理的な名前でしょう...) 2 つのトレース ソースがインスタンス化され、2 つの異なるプロジェクトで使用されていることを明確にするためです。1 つはクラス ライブラリで、もう 1 つは winforms アプリケーションです。winforms アプリケーションをコンソール プログラムとしてコンパイルし、アプリで TraceSource のコメントを外します。config ファイル 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から何も得ません。私は何を間違っていますか?