unity 利用 Conditional 定義條件方法擴展Log工具

利用 Conditional 屬性,程序員可以定義條件方法。Conditional 屬性通過測試條件編譯符號來確定適用的條件。當運行到一個條件方法調用時,是否執行該調用,要根據出現該調用時是否已定義了此符號來確定。如果定義了此符號,則執行該調用;否則省略該調用(包括對調用的參數的計算)。

條件方法要受到以下限制:

  • 條件方法必須是類聲明或結構聲明中的方法。如果在接口聲明中的方法上指定 Conditional 屬性,將出現編譯時錯誤。
  • 條件方法必須具有 void 返回類型。
  • 不能用 override 修飾符標記條件方法。但是,可以用 virtual 修飾符標記條件方法。此類方法的重寫方法隱含為有條件的方法,而且不能用 Conditional 屬性顯式標記。
  • 條件方法不能是接口方法的實現。否則將發生編譯時錯誤。
  • 如果條件方法用在“委托創建表達式”中,也會發生編譯時錯誤

Ps.盡量使用Conditional屬性代替#if和#endif

/*MyConditional.cs*/
 
//#define DEBUG
using System;
using System.Diagnostics;
class Info
{
    //[Conditional("DEBUG")]
    public static void Trace(string strMessage)
    {
        Console.WriteLine(strMessage);
    }
 
    [Conditional("DEBUG")]
    public static void TraceX(string strFormat,params object[] list)
    {
        Console.WriteLine(strFormat, list);
    }
}
 
class TestConditional
{
    public static void Main()
    {
        Info.Trace("Cool!");
        Info.TraceX("{0} {1} {2}","C", "U", 2001);
    }
}
 
/*
編譯方式1:
csc /define:DEBUG /out:1.exe MyConditional.cs
 
運行結果1:
Cool!
C U 2001
*/
 
/*
編譯方式2:
csc /out:1.exe MyConditional.cs
 
運行結果2:
Cool!
*/

unity中的是用,用來進行日志的輸出:

using UnityEngine;
using System.Diagnostics;
using System.Net;
using System;
using Debug = UnityEngine.Debug;
using System.Collections.Generic;
using System.Text;

public class Logger
{
    static protected Stopwatch watch = new Stopwatch();
    private static WebClient m_webClient = new WebClient();
    private static List<string> m_errorList = new List<string>();
    private static bool m_canTakeError = true;
    private static bool m_isInit = false;
    private static int counter = 0;
    private static StringBuilder sb = new StringBuilder();
    public static string clientVerstion = string.Empty;
    public static string loginUid = string.Empty;
    public static string localIP = string.Empty;
    public static string platName = string.Empty;
    public static string sceneName = "Launch";
    public static string DEBUG_BUILD_VER = "HOG_ALPHA_1";
    public static string platChannel = "outnet";

    [Conditional("UNITY_EDITOR")]
    [Conditional("LOGGER_ON")]
    static public void Log(string s, params object[] p)
    {
        Debug.Log(DateTime.Now + " -- " + (p != null && p.Length > 0 ? string.Format(s, p) : s));
    }

    [Conditional("UNITY_EDITOR")]
    [Conditional("LOGGER_ON")]
    static public void Log(object o)
    {
        Debug.Log(o);
    }

    [Conditional("UNITY_EDITOR")]
    [Conditional("LOGGER_ON")]
    public static void LogToMainThread(string s, params object[] p)
    {
        string msg = (p != null && p.Length > 0 ? string.Format(s, p) : s);
        LoggerHelper.Instance.LogToMainThread(LoggerHelper.LOG_TYPE.LOG, msg);
    }

    [Conditional("UNITY_EDITOR")]
    [Conditional("LOGGER_ON")]
    static public void Assert(bool condition, string s, params object[] p)
    {
        if (condition)
        {
            return;
        }

        LogError("Assert failed! Message:\n" + s, p);
    }

    static public void LogError(string s, params object[] p)
    {
#if UNITY_EDITOR || LOGGER_ON
        Debug.LogError((p != null && p.Length > 0 ? string.Format(s, p) : s));
#else
        AddError(string.Format("clientversion:{0} uid: {1} device:{2} ip:{3} platname:{4} platChannel:{5} scenename:{6} debug_build_ver:{7} \n {8} ",
        clientVerstion, loginUid, (SystemInfo.deviceModel + "/" + SystemInfo.deviceUniqueIdentifier), localIP, platName, platChannel, sceneName, DEBUG_BUILD_VER,
        (p != null && p.Length > 0 ? string.Format(s, p) : s)));
#endif
    }

    public static void LogErrorToMainThread(string s, params object[] p)
    {
        string msg = (p != null && p.Length > 0 ? string.Format(s, p) : s);
        LoggerHelper.Instance.LogToMainThread(LoggerHelper.LOG_TYPE.LOG_ERR, msg);
    }


    static public void LogStackTrace(string str)
    {
        StackFrame[] stacks = new StackTrace().GetFrames();
        string result = str + "\r\n";

        if (stacks != null)
        {
            for (int i = 0; i < stacks.Length; i++)
            {
                result += string.Format("{0} {1}\r\n", stacks[i].GetFileName(), stacks[i].GetMethod().ToString());
                //result += stacks[i].ToString() + "\r\n";
            }
        }

        LogError(result);
    }

    private static void AddError(string errorStr)
    {
        if (!string.IsNullOrEmpty(errorStr))
        {
            m_errorList.Add(errorStr);
        }
    }

    private static void SendToHttpSvr(string postData)
    {
        if (!string.IsNullOrEmpty(postData))
        {
            //Logger.Log("error:" + postData);
            if (!m_isInit)
            {
                m_webClient.UploadStringCompleted += new UploadStringCompletedEventHandler(OnUploadStringCompleted);
                m_isInit = true;
            }

            m_webClient.UploadStringAsync(new Uri(URLSetting.REPORT_ERROR_URL), "POST", postData);
        }
    }

    public static void CheckReportError()
    {
        counter++;

        if (counter % 5 == 0 && m_canTakeError)
        {
            DealWithReportError();
            counter = (counter > 1000) ? 0 : counter;
        }
    }

    private static void DealWithReportError()
    {
        int errorCount = m_errorList.Count;
        if (errorCount > 0)
        {
            m_canTakeError = false;
            counter = 0;
            sb.Length = 0;
            for (int i = 0; i < errorCount; i++)
            {
                sb.Append(m_errorList[i] + " | \n");
            }

            m_errorList.Clear();
            SendToHttpSvr(sb.ToString());
        }
    }
    static void OnUploadStringCompleted(object sender, UploadStringCompletedEventArgs e)
    {
        m_canTakeError = true;
    }

    [Conditional("UNITY_EDITOR")]
    static public void Watch()
    {
#if UNITY_EDITOR
        watch.Reset();
        watch.Start();
#endif
    }

    static public long useTime
    {
        get
        {
#if UNITY_EDITOR
            return watch.ElapsedMilliseconds;
#else
            return 0;
#endif
        }
    }

    static public string useMemory
    {
        get
        {
#if UNITY_5_6_OR_NEWER
            return (UnityEngine.Profiling.Profiler.usedHeapSizeLong / 1024 / 1024).ToString() + " mb";
#elif UNITY_5_5_OR_NEWER
            return (UnityEngine.Profiling.Profiler.usedHeapSize / 1024 / 1024).ToString() + " mb";
#else
            return (Profiler.usedHeapSize / 1024 / 1024).ToString() + " mb";
#endif
        }
    }

}

**

?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。