- Home /
How to redirect System.Console.Write from dll to Debug.Log
What I am currently doing can be summarized as:
var stdOut = System.Console.Out;
var consoleOut = new StringWriter();
System.Console.SetOut(consoleOut);
//.dll call that calls System.Console.Write/WriteLine
Debug.Log( consoleOut.ToString());
System.Console.SetOut(stdOut);
This works but will only output to the Unity console after all my calls are finished. Is it possible to whenever System.Console.Write is called in the .dll, to output immediately to Unity console?
Answer by Bunny83 · Oct 27, 2014 at 01:56 PM
Well, Debug.Log seems to be one of the few things in unity that actually is thread-safe (as far as i can tell. I've used it a couple of times without problems). So you basically have two options:
If your dll is a managed dll, just use UnityEngine.Debug.Log
Create your own TextWriter that writes to Debug.Log
So you can write a simple class like this:
public class DebugLogWriter : System.IO.TextWriter
{
public override void Write(string value)
{
base.Write(value);
Debug.Log(value);
}
public override System.Text.Encoding Encoding
{
get { return System.Text.Encoding.UTF8; }
}
}
And use it like this:
System.Console.SetOut(new DebugLogWriter());
However there are a few things to keep in mind. The TextWriter class is an abstract class which doesn't write to anything by default. It provides a lot methods to write to your "writer". All methods are actually using void Write(char)
. However it's an inconvenient method to write to Debug.Log as it only receives one character at a time. As long as the code that writes to the console uses Write(string) or writeLine(String) everything should be fine and you'll intercept it. But if someone uses void Write(char[]) or and of the other methods that directly writes to Write(char) you won't get it.
You can of course implement the Write(char) method and handle everything there by accumulating the string there, but you don't know when the logging is completed. You can't rely on a newline character.
Finally keep in mind if your method in the DLL runs on the main thread, you won't see any updates in the Unity console since Unity runs on the same thread and Unity won't redraw itself until your method finished. If you need to get a result because your method might crash Unity, you might want to log to a file instead of the Unity console.