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
        }
    }

}

**

©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 227,156评论 6 529
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 97,866评论 3 413
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 174,880评论 0 373
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 62,398评论 1 308
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 71,202评论 6 405
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 54,743评论 1 320
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 42,822评论 3 438
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 41,962评论 0 285
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 48,476评论 1 331
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 40,444评论 3 354
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 42,579评论 1 365
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 38,129评论 5 355
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 43,840评论 3 344
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 34,231评论 0 25
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 35,487评论 1 281
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 51,177评论 3 388
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 47,568评论 2 370