Last active
September 13, 2024 20:47
-
-
Save Nesh108/22b3f6e350fe2fd6a483e014210d5215 to your computer and use it in GitHub Desktop.
Unity Logger for posting Errors to Discord channel
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System.Collections.Generic; | |
using System.Linq; | |
using UnityEngine; | |
using UnityEngine.Networking; | |
// License: MIT | |
// Created by: Aceria_ | |
// Edited by: Nesh108 | |
// To use, add these to any MonoBehaviour: | |
// OnEnable: `Application.logMessageReceived += DiscordLogger.HandleLog;` | |
// OnDisable: `Application.logMessageReceived -= DiscordLogger.HandleLog;` | |
public static class DiscordLogger | |
{ | |
private static readonly string DISCORD_WEBHOOK = "<DISCORD_WEBHOOK_URL>"; | |
private static List<string> lastErrors = new List<string>(); | |
private static readonly LogType[] allowedLogTypes = { | |
LogType.Assert, | |
LogType.Error, | |
LogType.Exception | |
}; | |
private static readonly string[] filteredMessages = | |
{ | |
"Failed to read inpurt report", | |
"FMOD failed to initialize the output", | |
"Failed to create device file", | |
}; | |
public static void HandleLog(string msg, string stack, LogType type) | |
{ | |
if (!Application.isEditor) | |
{ | |
if (allowedLogTypes.Contains(type)) | |
{ | |
// Don't spam duplicate messages, ignore some useless ones | |
if (!lastErrors.Contains(stack) && !filteredMessages.Any(msg.Contains)) | |
{ | |
lastErrors.Add(stack); | |
StartCoroutine(_PrepareRequest(msg, stack, type)); | |
} | |
} | |
} | |
} | |
private static IEnumerator _PrepareRequest(string msg, string stack, LogType type) | |
{ | |
yield return new WaitForEndOfFrame(); | |
UnityWebRequest www = UnityWebRequest.Post(DISCORD_WEBHOOK, GetFormData(msg, stack, type, ScreenCapture.CaptureScreenshotAsTexture().EncodeToPNG())); | |
www.SendWebRequest(); | |
} | |
private static WWWForm GetFormData(string msg, string stack, LogType type, byte[] screenshot) | |
{ | |
string content = ""; | |
WWWForm formData = new WWWForm(); | |
// Add build version | |
content = $"**{Application.version}** ({(Debug.isDebugBuild ? "Debug" : "Release")} on __{Application.platform}__\n\n"; | |
// Set up the report | |
content += $"**Type**: {type}\n\n"; | |
content += $"**Message**: {msg}\n\n"; | |
content += $"**Callstack**: {stack}"; | |
formData.AddField("content", content); | |
//optional, but very useful for seeing UI errors | |
if (screenshot != null) | |
{ | |
formData.AddBinaryData("screenshot", screenshot, "discord_error_screenshot.png"); | |
} | |
return formData; | |
} | |
} |
@brunocoimbar thanks! I edited the gist with the license :)
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thanks for sharing that! Under which license is it?