Skip to content

Instantly share code, notes, and snippets.

@AldeRoberge
Last active November 15, 2024 20:53
Show Gist options
  • Save AldeRoberge/69554c24ac7c4080af34c2330a1f99ee to your computer and use it in GitHub Desktop.
Save AldeRoberge/69554c24ac7c4080af34c2330a1f99ee to your computer and use it in GitHub Desktop.
Redirects console output (Console.WriteLine) to Unity (Debug.Log). Keep in mind that this will probably add some internal logging of Unity to your Editor console.
using System;
using System.IO;
using System.Text;
using UnityEngine;
namespace Generator.Scripts.Runtime.Utilities.Logging
{
/// <summary>
/// Redirects console output (Console.WriteLine) to Unity (Debug.Log)
/// </summary>
public class UnityConsoleRedirect : MonoBehaviour
{
public void Start()
{
Console.SetOut(new UnityTextWriter(false));
Console.SetError(new UnityTextWriter(true));
}
private class UnityTextWriter : TextWriter
{
private readonly StringBuilder _buffer = new();
private readonly bool _isError;
public UnityTextWriter(bool isError)
{
_isError = isError;
}
public override void Flush()
{
if (_buffer.Length <= 0) return;
if (_isError)
Debug.LogError(_buffer.ToString());
else
Debug.Log(_buffer.ToString());
_buffer.Length = 0;
}
public override void Write(string value)
{
if (string.IsNullOrEmpty(value))
return;
_buffer.Append(value);
var len = value.Length;
if (len <= 0) return;
var lastChar = value[len - 1];
if (lastChar == '\n')
Flush();
}
public override void Write(char value)
{
_buffer.Append(value);
if (value == '\n')
Flush();
}
public override void Write(char[] value, int index, int count)
{
Write(new string(value, index, count));
}
public override Encoding Encoding => Encoding.Default;
}
}
}
@AldeRoberge
Copy link
Author

Suggestion of Rich Wepner : I guess you probably want to do the same thing with Console.SetErr as well? 💡

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment