Skip to content

Instantly share code, notes, and snippets.

@Pizzaandy
Created April 24, 2023 06:24
Show Gist options
  • Select an option

  • Save Pizzaandy/48ed0202bfca0016bd0103626289cf36 to your computer and use it in GitHub Desktop.

Select an option

Save Pizzaandy/48ed0202bfca0016bd0103626289cf36 to your computer and use it in GitHub Desktop.
Simple Unity stack frame logging
using UnityEngine;
using System;
using System.Text;
using System.Diagnostics;
using Debug = UnityEngine.Debug;
public static class StackFrameUtility
{
public static void Log(this StackFrame frame, object message = null)
{
var method = frame.GetMethod();
string fileName = frame.GetFileName();
int lineNumber = frame.GetFileLineNumber();
string methodName = method.Name;
string declaringType = method.DeclaringType.FullName;
var methodParams = method.GetParameters();
var parameters = new StringBuilder(32);
for (int i = 0; i < methodParams.Length; i++)
{
parameters.Append($"{methodParams[i].ParameterType} {methodParams[i].Name}");
if (i+1 < methodParams.Length)
{
parameters.Append(", ");
}
}
string formattedMethodName = $"{declaringType}.{methodName}({parameters})";
if (!string.IsNullOrEmpty(fileName))
{
int startSubName = fileName.IndexOf("Assets", StringComparison.OrdinalIgnoreCase);
if (startSubName > 0)
{
fileName = fileName.Substring(startSubName);
}
}
if (message != null)
{
Debug.Log($"{message}\n{formattedMethodName} (at {fileName}:{lineNumber})");
}
else
{
Debug.Log($"{formattedMethodName} (at {fileName}:{lineNumber})");
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment