using System; using System.Collections.Generic; using UnityEngine; namespace NoSuchStudio.Common { /// /// Base class for MonoBehaviours that should have a separate logger. Useful for filtering /// logs by class types. /// /// /// This class keeps track of all types that inherit it and creates a /// for each. /// Any messages logged through the helper methods will have the class name prepended to the message. /// /// // will print "[MyClass] Hello World!" /// MonoBehaviourWithLogger.LogLog<MyClass>("Hello World!"); /// /// Using sample code like below, you can filter your logs by class. /// /// MonoBehaviourWithLogger.GetLoggerByType<SubclassOfMonoBehaviourWithLogger>().Item1.filterLogType = LogType.Error; /// /// public abstract class MonoBehaviourWithLogger : MonoBehaviour { public static readonly Dictionary loggers = new Dictionary(); public Logger logger { get { Type thisType = GetType(); return GetLoggerByType(thisType).logger; } } public string logTag { get { Type thisType = GetType(); return GetLoggerByType(thisType).logTag; } } protected void LogLog(string format, params object[] args) { logger.LogFormat(LogType.Log, string.Format("{0} {1}", logTag, format), args); } protected void LogWarn(string format, params object[] args) { logger.LogFormat(LogType.Warning, string.Format("{0} {1}", logTag, format), args); } protected void LogError(string format, params object[] args) { logger.LogFormat(LogType.Error, string.Format("{0} {1}", logTag, format), args); } private static void AddType(Type type) { if (!loggers.ContainsKey(type)) { loggers.Add(type, (new Logger(Debug.unityLogger.logHandler), string.Format("[{0}]", type.Name))); } } public static (Logger logger, string logTag) GetLoggerByType(Type type) { AddType(type); return loggers[type]; } public static (Logger logger, string logTag) GetLoggerByType() { return GetLoggerByType(typeof(T)); } protected static void LogLog(string format, params object[] args) { (Logger logger, string LogTag) = GetLoggerByType(); logger.LogFormat(LogType.Log, string.Format("{0} {1}", LogTag, format), args); } protected static void LogWarn(string format, params object[] args) { (Logger logger, string LogTag) = GetLoggerByType(); logger.LogFormat(LogType.Warning, string.Format("{0} {1}", LogTag, format), args); } protected static void LogError(string format, params object[] args) { (Logger logger, string LogTag) = GetLoggerByType(); logger.LogFormat(LogType.Error, string.Format("{0} {1}", LogTag, format), args); } } }