Skip to content

Instantly share code, notes, and snippets.

@akeit0
Created August 10, 2024 08:30
Show Gist options
  • Select an option

  • Save akeit0/be22ecb6bb1c9bb78ef8051a3fb0588f to your computer and use it in GitHub Desktop.

Select an option

Save akeit0/be22ecb6bb1c9bb78ef8051a3fb0588f to your computer and use it in GitHub Desktop.
ConsoleRedirect
//License
//These codes are licensed under CC0.
using System.IO;
using System.Text;
using UnityEngine;
static class ConsoleRedirect
{
[RuntimeInitializeOnLoadMethod(RuntimeInitializeLoadType.AfterAssembliesLoaded)]
static void ConsoleInit()
{
var defaultOut = System.Console.Out;
var defaultError = System.Console.Error;
System.Console.SetOut(new ConsoleWriter(defaultOut));
System.Console.SetError(new ErrorWriter(defaultError));
}
class ConsoleWriter : TextWriter
{
TextWriter Default { get; }
public ConsoleWriter(TextWriter defaultOut)
{
Default = defaultOut;
}
public override void Write(char value)
{
Default.Write(value);
}
public override void Write(string value)
{
Default.Write(value);
switch (value)
{
case "\r\n":
case "\n":
return;
default:
Debug.Log(value);
break;
}
}
public override Encoding Encoding => Encoding.ASCII;
}
class ErrorWriter : TextWriter
{
TextWriter Default { get; }
public ErrorWriter(TextWriter defaultError)
{
Default = defaultError;
}
public override void Write(char value)
{
Default.Write(value);
}
public override void Write(string value)
{
Default.Write(value);
Debug.LogError(value);
}
public override Encoding Encoding => Encoding.ASCII;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment