Okay, I think the title can be quite confusing... :)
My application is using CS-Script as a script interface. In the scripts my application will be running, I want to have some sort of "Debug print" - meaning somewhere in the script the scripter can do "Debug.Print("BLAAAAH!!!");") and that would show up somewhere in my very funky output dialog.
Of course I can create my own debug-ooutput-stuff, but since I'm using C开发者_StackOverflow社区# as a scripting language and people using C# would be used to use System.Diagnostics and use Debug.Print("..."), it would be great if I could reroute System.Diagnostics.Debug.Print("") and System.Diagnostics.Debug.WriteLine("...") to trace their output to my cool output-window.
So.
Does anybody know if it's possible to reroute C#'s System.Diagnostic.Debug print/writeline output to something I have control over ?
For that, you can create a custom TraceListener
.
You should set the compile time DEBUG symbol or run the script with /dbg option
cscs /dbg <yourScript>
You will also need to create a custom TraceListener or simply use a trace viewer like the sysinternals DebugView
I use the TraceListener for this also, but here's my code snippets:
Classes:
using System.Diagnostics;
public class DebugOutputListener : TraceListener
{
public event EventHandler<DebugMessageArgs> DebugMessage;
public override void Write(string message)
{
EventHandler<DebugMessageArgs> h = DebugMessage;
if (h != null)
{
DebugArgs args = new DebugArgs
{
Message = message
};
h(this, args);
}
}
public override void WriteLine(string message)
{
Write(message + "\r\n");
}
}
public class DebugMessageArgs : EventArgs
{
public string Message
{
get;
set;
}
}
To receive debug messages, instantiate an instance of the DebugOutputListener, subscribe to the DebugMessage event handler and register the listener with the Debug.Listeners collection.
e.g.
private void InitialiseDebugListener()
{
DebugListener dl = new DebugListener();
dl.DebugMessage += new EventHandler<DebugArgs>(Console_OnDebugMessage);
Debug.Listeners.Add(dl);
}
private void Console_OnDebugMessage(object sender, DebugMessageArgs e)
{
string debugMessage = e.Message;
// Do what you want with debugMessage.
// Be aware this may not come in on the application/form thread.
}
精彩评论