Skip to content

Instantly share code, notes, and snippets.

@nekomimi-daimao
Last active April 24, 2019 10:44
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nekomimi-daimao/48938c1de1e91550a34984cdfc03b702 to your computer and use it in GitHub Desktop.
Save nekomimi-daimao/48938c1de1e91550a34984cdfc03b702 to your computer and use it in GitHub Desktop.
Unity, XR, LogViewer. referencing https://www.urablog.xyz/entry/2017/04/25/195351
using System.Collections.Generic;
using System.Text;
using UnityEngine;
using UnityEngine.UI;
namespace NekomimiDaimao
{
/// https://gist.github.com/nekomimi-daimao/48938c1de1e91550a34984cdfc03b702
public class XRLogger : MonoBehaviour
{
[SerializeField] private Text OutPutText = null;
[SerializeField] private int LineLength = 10;
[SerializeField] private string Keyword = null;
[HeaderAttribute("LogLevel")]
[SerializeField] private bool Error = true;
[SerializeField] private bool Assert = true;
[SerializeField] private bool Warning = true;
[SerializeField] private bool Log = true;
[SerializeField] private bool Exception = true;
private Queue<string> _logQueue;
private StringBuilder _stringBuilder;
private HashSet<LogType> _logSet;
private void Awake()
{
#if !DEVELOPMENT_BUILD && !UNITY_EDITOR
GameObject.Destroy(this.gameObject);
return;
#endif
_logQueue = new Queue<string>(LineLength);
_stringBuilder = new StringBuilder(LineLength);
_logSet = new HashSet<LogType>();
if (Error)
{
_logSet.Add(LogType.Error);
}
if (Assert)
{
_logSet.Add(LogType.Assert);
}
if (Warning)
{
_logSet.Add(LogType.Warning);
}
if (Log)
{
_logSet.Add(LogType.Log);
}
if (Exception)
{
_logSet.Add(LogType.Exception);
}
Application.logMessageReceived += OnLogMessage;
}
private void OnDestroy()
{
Application.logMessageReceived -= OnLogMessage;
}
private void OnLogMessage(string logText, string stackTrace, LogType type)
{
if (!_logSet.Contains(type))
{
return;
}
if (!string.IsNullOrEmpty(Keyword) && !logText.Contains(Keyword))
{
return;
}
switch (type)
{
case LogType.Error:
case LogType.Assert:
case LogType.Exception:
case LogType.Warning:
logText = $"<color=red>{logText}</color>";
break;
case LogType.Log:
default:
break;
}
if (_logQueue.Count >= LineLength)
{
_logQueue.Dequeue();
}
_logQueue.Enqueue(logText);
_stringBuilder.Clear();
foreach (var s in _logQueue)
{
_stringBuilder.AppendLine(s);
}
OutPutText.text = _stringBuilder.ToString();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment