1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
|
// ----------------------------------------
//
// BuglyAgent.cs
//
// Author:
// Yeelik, <bugly@tencent.com>
//
// Copyright (c) 2015 Bugly, Tencent. All rights reserved.
//
// ----------------------------------------
//
using UnityEngine;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Reflection;
using System.Text;
using System.Text.RegularExpressions;
using System.Runtime.InteropServices;
// We dont use the LogType enum in Unity as the numerical order doesnt suit our purposes
/// <summary>
/// Log severity.
/// { Log, LogDebug, LogInfo, LogWarning, LogAssert, LogError, LogException }
/// </summary>
public enum LogSeverity
{
Log,
LogDebug,
LogInfo,
LogWarning,
LogAssert,
LogError,
LogException
}
/// <summary>
/// Bugly agent.
/// </summary>
public sealed class BuglyAgent
{
/// <summary>
/// The SDK package name, default is 'com.tencent.bugly'
/// </summary>
private const string SDK_PACKAGE = "com.tencent.bugly.msdk";
private const int SDK_TYPE = 2; // Default=0,Bugly=1,MSDK=2
private const int SDK_LOG_LEVEL = 2; // Off=0,Error=1,Warn=2,Info=3,Debug=4
// Define delegate support multicasting to replace the 'Application.LogCallback'
public delegate void LogCallbackDelegate (string condition,string stackTrace,LogType type);
/// <summary>
/// Init sdk with the specified appId.
/// <para>This will initialize sdk to report native exception such as obj-c, c/c++, java exceptions, and also enable c# exception handler to report c# exception logs</para>
/// </summary>
/// <param name="appId">App identifier.</param>
public static void InitWithAppId (string appId)
{
if (IsInitialized) {
DebugLog (null, "BuglyAgent has already been initialized.");
return;
}
if (string.IsNullOrEmpty (appId)) {
return;
}
// init the sdk with app id
InitBuglyAgent (appId);
DebugLog (null, "Initialized with app id: {0}", appId);
// Register the LogCallbackHandler by Application.RegisterLogCallback(Application.LogCallback)
_RegisterExceptionHandler ();
}
/// <summary>
/// Only Enable the C# exception handler.
///
/// <para>
/// You can call it when you do not call the 'InitWithAppId(string)', but you must make sure initialized the sdk in elsewhere,
/// such as the native code in associated Android or iOS project.
/// </para>
///
/// <para>
/// Default Level is <c>LogError</c>, so the LogError, LogException will auto report.
/// </para>
///
/// <para>
/// You can call the method <code>BuglyAgent.ConfigAutoReportLogLevel(LogSeverity)</code>
/// to change the level to auto report if you known what are you doing.
/// </para>
///
/// </summary>
public static void EnableExceptionHandler ()
{
if (IsInitialized) {
DebugLog (null, "BuglyAgent has already been initialized.");
return;
}
DebugLog (null, "Only enable the exception handler, please make sure you has initialized the sdk in the native code in associated Android or iOS project.");
// Register the LogCallbackHandler by Application.RegisterLogCallback(Application.LogCallback)
_RegisterExceptionHandler ();
}
/// <summary>
/// Registers the log callback handler.
///
/// If you need register logcallback using Application.RegisterLogCallback(LogCallback),
/// you can call this method to replace it.
///
/// <para></para>
/// </summary>
/// <param name="handler">Handler.</param>
public static void RegisterLogCallback (LogCallbackDelegate handler)
{
if (handler != null) {
DebugLog (null, "Add log callback handler: {0}", handler);
_LogCallbackEventHandler += handler;
}
}
/// <summary>
/// Sets the log callback extras handler.
/// </summary>
/// <param name="handler">Handler.</param>
public static void SetLogCallbackExtrasHandler(Func<Dictionary<string, string>> handler){
if (handler != null) {
_LogCallbackExtrasHandler = handler;
DebugLog(null, "Add log callback extra data handler : {0}", handler);
}
}
/// <summary>
/// Reports the exception.
/// </summary>
/// <param name="e">E.</param>
/// <param name="message">Message.</param>
public static void ReportException (System.Exception e, string message)
{
if (!IsInitialized) {
return;
}
DebugLog (null, "Report exception: {0}\n------------\n{1}\n------------", message, e);
_HandleException (e, message, false);
}
/// <summary>
/// Reports the exception.
/// </summary>
/// <param name="name">Name.</param>
/// <param name="message">Message.</param>
/// <param name="stackTrace">Stack trace.</param>
public static void ReportException (string name, string message, string stackTrace)
{
if (!IsInitialized) {
return;
}
DebugLog (null, "Report exception: {0} {1} \n{2}", name, message, stackTrace);
_HandleException (LogSeverity.LogException, name, message, stackTrace, false);
}
/// <summary>
/// Unregisters the log callback.
/// </summary>
/// <param name="handler">Handler.</param>
public static void UnregisterLogCallback (LogCallbackDelegate handler)
{
if (handler != null) {
DebugLog (null, "Remove log callback handler");
_LogCallbackEventHandler -= handler;
}
}
/// <summary>
/// Sets the user identifier.
/// </summary>
/// <param name="userId">User identifier.</param>
public static void SetUserId (string userId)
{
if (!IsInitialized) {
return;
}
DebugLog (null, "Set user id: {0}", userId);
SetUserInfo (userId);
}
/// <summary>
/// Sets the scene.
/// </summary>
/// <param name="sceneId">Scene identifier.</param>
public static void SetScene (int sceneId)
{
if (!IsInitialized) {
return;
}
DebugLog (null, "Set scene: {0}", sceneId);
SetCurrentScene (sceneId);
}
/// <summary>
/// Adds the scene data.
/// </summary>
/// <param name="key">Key.</param>
/// <param name="value">Value.</param>
public static void AddSceneData (string key, string value)
{
if (!IsInitialized) {
return;
}
DebugLog (null, "Add scene data: [{0}, {1}]", key, value);
AddKeyAndValueInScene (key, value);
}
/// <summary>
/// Configs the debug mode.
/// </summary>
/// <param name="enable">If set to <c>true</c> debug mode.</param>
public static void ConfigDebugMode (bool enable)
{
EnableDebugMode (enable);
DebugLog (null, "{0} the log message print to console", enable ? "Enable" : "Disable");
}
/// <summary>
/// Configs the auto quit application.
/// </summary>
/// <param name="autoQuit">If set to <c>true</c> auto quit.</param>
public static void ConfigAutoQuitApplication (bool autoQuit)
{
_autoQuitApplicationAfterReport = autoQuit;
}
/// <summary>
/// Configs the auto report log level. Default is LogSeverity.LogError.
/// <example>
/// LogSeverity { Log, LogDebug, LogInfo, LogWarning, LogAssert, LogError, LogException }
/// </example>
/// </summary>
///
/// <param name="level">Level.</param>
public static void ConfigAutoReportLogLevel (LogSeverity level)
{
_autoReportLogLevel = level;
}
/// <summary>
/// Configs the default.
/// </summary>
/// <param name="channel">Channel.</param>
/// <param name="version">Version.</param>
/// <param name="user">User.</param>
/// <param name="delay">Delay.</param>
public static void ConfigDefault (string channel, string version, string user, long delay)
{
DebugLog (null, "Config default channel:{0}, version:{1}, user:{2}, delay:{3}", channel, version, user, delay);
ConfigDefaultBeforeInit (channel, version, user, delay);
}
/// <summary>
/// Logs the debug.
/// </summary>
/// <param name="tag">Tag.</param>
/// <param name="format">Format.</param>
/// <param name="args">Arguments.</param>
public static void DebugLog (string tag, string format, params object[] args)
{
if (string.IsNullOrEmpty (format)) {
return;
}
if(!_debugMode) {
return;
}
Console.WriteLine ("[BuglyAgent] <Debug> - {0} : {1}", tag, string.Format (format, args));
}
/// <summary>
/// Prints the log.
/// </summary>
/// <param name="level">Level.</param>
/// <param name="format">Format.</param>
/// <param name="args">Arguments.</param>
public static void PrintLog (LogSeverity level, string format, params object[] args)
{
if (string.IsNullOrEmpty (format)) {
return;
}
LogToConsole (level, string.Format (format, args));
}
#if UNITY_EDITOR || UNITY_STANDALONE
#region Interface(Empty) in Editor
private static void InitBuglyAgent (string appId)
{
}
private static void ConfigDefaultBeforeInit(string channel, string version, string user, long delay){
}
private static void EnableDebugMode(bool enable){
}
private static void SetUserInfo(string userInfo){
}
private static void ReportException (int type,string name, string message, string stackTrace, bool quitProgram)
{
}
private static void SetCurrentScene(int sceneId) {
}
private static void AddKeyAndValueInScene(string key, string value){
}
private static void AddExtraDataWithException(string key, string value) {
// only impl for iOS
}
private static void LogToConsole(LogSeverity level, string message){
}
private static void SetUnityVersion(){
}
#endregion
#elif UNITY_ANDROID
// #if UNITY_ANDROID
#region Interface for Android
private static readonly string CLASS_UNITYAGENT = "com.tencent.bugly.unity.UnityAgent";
private static AndroidJavaObject _unityAgent;
public static AndroidJavaObject UnityAgent {
get {
if (_unityAgent == null) {
using (AndroidJavaClass clazz = new AndroidJavaClass(CLASS_UNITYAGENT)) {
_unityAgent = clazz.CallStatic<AndroidJavaObject> ("getInstance");
}
}
return _unityAgent;
}
}
private static string _configChannel;
private static string _configVersion;
private static string _configUser;
private static long _configDelayTime;
private static void ConfigDefaultBeforeInit(string channel, string version, string user, long delay){
_configChannel = channel;
_configVersion = version;
_configUser = user;
_configDelayTime = delay;
}
private static void InitBuglyAgent(string appId)
{
if (IsInitialized) {
return;
}
try {
UnityAgent.Call("setSDKPackagePrefixName", SDK_PACKAGE);
} catch {
}
try {
UnityAgent.Call("initWithConfiguration", appId, _configChannel, _configVersion, _configUser, _configDelayTime);
_isInitialized = true;
} catch {
}
}
private static void EnableDebugMode(bool enable){
_debugMode = enable;
try {
UnityAgent.Call ("setLogEnable", enable);
} catch {
}
}
private static void SetUserInfo(string userInfo){
try {
UnityAgent.Call ("setUserId", userInfo);
} catch {
}
}
private static void ReportException (int type, string name, string reason, string stackTrace, bool quitProgram)
{
try {
UnityAgent.Call ("traceException", name, reason, stackTrace, quitProgram);
} catch {
}
}
private static void SetCurrentScene(int sceneId) {
try {
UnityAgent.Call ("setScene", sceneId);
} catch {
}
}
private static void SetUnityVersion(){
try {
UnityAgent.Call ("setSdkConfig","UnityVersion", Application.unityVersion);
} catch {
}
}
private static void AddKeyAndValueInScene(string key, string value){
try {
UnityAgent.Call ("addSceneValue", key, value);
} catch {
}
}
private static void AddExtraDataWithException(string key, string value) {
// no impl
}
private static void LogToConsole(LogSeverity level, string message){
if (!_debugMode && LogSeverity.Log != level) {
if (level < LogSeverity.LogWarning) {
return;
}
}
try {
// UnityAgent.Call ("printLog", string.Format ("<{0}> - {1}", level.ToString (), message));
} catch {
}
}
#endregion
#elif UNITY_IPHONE || UNITY_IOS
#region Interface for iOS
private static bool _crashReporterTypeConfiged = false;
private static void ConfigCrashReporterType(){
if (!_crashReporterTypeConfiged) {
try {
_BuglyConfigCrashReporterType(SDK_TYPE); // MSDK
} catch {
}
}
}
private static void ConfigDefaultBeforeInit(string channel, string version, string user, long delay){
try {
ConfigCrashReporterType();
_BuglyDefaultConfig(channel, version, user, null);
} catch {
}
}
private static void EnableDebugMode(bool enable){
_debugMode = enable;
}
private static void InitBuglyAgent (string appId)
{
if(!string.IsNullOrEmpty(appId)) {
_BuglyConfigCrashReporterType(SDK_TYPE); // MSDK
_BuglyInit(appId, _debugMode, SDK_LOG_LEVEL); // Log level
}
}
private static void SetUnityVersion(){
ConfigCrashReporterType();
// _BuglySetExtraConfig("UnityVersion", Application.unityVersion);
_BuglySetKeyValue("UnityVersion", Application.unityVersion);
}
private static void SetUserInfo(string userInfo){
if(!string.IsNullOrEmpty(userInfo)) {
ConfigCrashReporterType();
_BuglySetUserId(userInfo);
}
}
private static void ReportException (int type, string name, string reason, string stackTrace, bool quitProgram)
{
string extraInfo = "";
Dictionary<string, string> extras = null;
if (_LogCallbackExtrasHandler != null) {
extras = _LogCallbackExtrasHandler();
}
if (extras == null || extras.Count == 0) {
extras = new Dictionary<string, string> ();
extras.Add ("UnityVersion", Application.unityVersion);
}
if (extras != null && extras.Count > 0) {
if (!extras.ContainsKey("UnityVersion")) {
extras.Add ("UnityVersion", Application.unityVersion);
}
StringBuilder builder = new StringBuilder();
foreach(KeyValuePair<string,string> kvp in extras){
builder.Append(string.Format("\"{0}\" : \"{1}\"", kvp.Key, kvp.Value)).Append(" , ");
}
extraInfo = string.Format("{{ {0} }}", builder.ToString().TrimEnd(" , ".ToCharArray()));
}
ConfigCrashReporterType();
// 4 is C# exception
_BuglyReportException(4, name, reason, stackTrace, extraInfo, quitProgram);
}
private static void SetCurrentScene(int sceneId) {
ConfigCrashReporterType();
_BuglySetTag(sceneId);
}
private static void AddKeyAndValueInScene(string key, string value){
ConfigCrashReporterType();
_BuglySetKeyValue(key, value);
}
private static void AddExtraDataWithException(string key, string value) {
}
private static void LogToConsole(LogSeverity level, string message){
if (!_debugMode && LogSeverity.Log != level) {
if (level < LogSeverity.LogWarning) {
return;
}
}
if (_debugMode ) {
Console.WriteLine("[BuglyAgent] <{0}> - {1}", level.ToString(), message);
}
ConfigCrashReporterType();
// _BuglyLogMessage(LogSeverityToInt(level), null, message);
}
private static int LogSeverityToInt(LogSeverity logLevel){
int level = 5;
switch(logLevel) {
case LogSeverity.Log:
level = 5;
break;
case LogSeverity.LogDebug:
level = 4;
break;
case LogSeverity.LogInfo:
level = 3;
break;
case LogSeverity.LogWarning:
case LogSeverity.LogAssert:
level = 2;
break;
case LogSeverity.LogError:
case LogSeverity.LogException:
level = 1;
break;
default:
level = 0;
break;
}
return level;
}
// --- dllimport start ---
[DllImport("__Internal")]
private static extern void _BuglyInit(string appId, bool debug, int level);
[DllImport("__Internal")]
private static extern void _BuglySetUserId(string userId);
[DllImport("__Internal")]
private static extern void _BuglySetTag(int tag);
[DllImport("__Internal")]
private static extern void _BuglySetKeyValue(string key, string value);
[DllImport("__Internal")]
private static extern void _BuglyReportException(int type, string name, string reason, string stackTrace, string extras, bool quit);
[DllImport("__Internal")]
private static extern void _BuglyDefaultConfig(string channel, string version, string user, string deviceId);
[DllImport("__Internal")]
private static extern void _BuglyLogMessage(int level, string tag, string log);
[DllImport("__Internal")]
private static extern void _BuglyConfigCrashReporterType(int type);
[DllImport("__Internal")]
private static extern void _BuglySetExtraConfig(string key, string value);
// dllimport end
#endregion
#endif
#region Privated Fields and Methods
private static event LogCallbackDelegate _LogCallbackEventHandler;
private static bool _isInitialized = false;
private static LogSeverity _autoReportLogLevel = LogSeverity.LogError;
#pragma warning disable 414
private static bool _debugMode = false;
private static bool _autoQuitApplicationAfterReport = false;
private static readonly int EXCEPTION_TYPE_UNCAUGHT = 1;
private static readonly int EXCEPTION_TYPE_CAUGHT = 2;
private static readonly string _pluginVersion = "1.4.2";
private static Func<Dictionary<string, string>> _LogCallbackExtrasHandler;
public static string PluginVersion {
get { return _pluginVersion; }
}
public static bool IsInitialized {
get { return _isInitialized; }
}
public static bool AutoQuitApplicationAfterReport {
get { return _autoQuitApplicationAfterReport; }
}
private static void _RegisterExceptionHandler ()
{
try {
// hold only one instance
#if UNITY_5
Application.logMessageReceived += _OnLogCallbackHandler;
#else
Application.RegisterLogCallback (_OnLogCallbackHandler);
#endif
AppDomain.CurrentDomain.UnhandledException += _OnUncaughtExceptionHandler;
_isInitialized = true;
DebugLog (null, "Register the log callback in Unity {0}", Application.unityVersion);
} catch {
}
SetUnityVersion ();
}
private static void _UnregisterExceptionHandler ()
{
try {
#if UNITY_5
Application.logMessageReceived -= _OnLogCallbackHandler;
#else
Application.RegisterLogCallback (null);
#endif
System.AppDomain.CurrentDomain.UnhandledException -= _OnUncaughtExceptionHandler;
DebugLog (null, "Unregister the log callback in unity {0}", Application.unityVersion);
} catch {
}
}
private static void _OnLogCallbackHandler (string condition, string stackTrace, LogType type)
{
if (_LogCallbackEventHandler != null) {
_LogCallbackEventHandler (condition, stackTrace, type);
}
if (!IsInitialized) {
return;
}
if (!string.IsNullOrEmpty (condition) && condition.Contains ("[BuglyAgent] <Log>")) {
return;
}
if (_uncaughtAutoReportOnce) {
return;
}
// convert the log level
LogSeverity logLevel = LogSeverity.Log;
switch (type) {
case LogType.Exception:
logLevel = LogSeverity.LogException;
break;
case LogType.Error:
logLevel = LogSeverity.LogError;
break;
case LogType.Assert:
logLevel = LogSeverity.LogAssert;
break;
case LogType.Warning:
logLevel = LogSeverity.LogWarning;
break;
case LogType.Log:
logLevel = LogSeverity.LogDebug;
break;
default:
break;
}
if (LogSeverity.Log == logLevel) {
return;
}
_HandleException (logLevel, null, condition, stackTrace, true);
}
private static void _OnUncaughtExceptionHandler (object sender, System.UnhandledExceptionEventArgs args)
{
if (args == null || args.ExceptionObject == null) {
return;
}
try {
if (args.ExceptionObject.GetType () != typeof(System.Exception)) {
return;
}
} catch {
if (UnityEngine.Debug.isDebugBuild == true) {
UnityEngine.Debug.Log ("BuglyAgent: Failed to report uncaught exception");
}
return;
}
if (!IsInitialized) {
return;
}
if (_uncaughtAutoReportOnce) {
return;
}
_HandleException ((System.Exception)args.ExceptionObject, null, true);
}
private static void _HandleException (System.Exception e, string message, bool uncaught)
{
if (e == null) {
return;
}
if (!IsInitialized) {
return;
}
string name = e.GetType ().Name;
string reason = e.Message;
if (!string.IsNullOrEmpty (message)) {
reason = string.Format ("{0}{1}***{2}", reason, Environment.NewLine, message);
}
StringBuilder stackTraceBuilder = new StringBuilder ("");
StackTrace stackTrace = new StackTrace (e, true);
int count = stackTrace.FrameCount;
for (int i = 0; i < count; i++) {
StackFrame frame = stackTrace.GetFrame (i);
stackTraceBuilder.AppendFormat ("{0}.{1}", frame.GetMethod ().DeclaringType.Name, frame.GetMethod ().Name);
ParameterInfo[] parameters = frame.GetMethod ().GetParameters ();
if (parameters == null || parameters.Length == 0) {
stackTraceBuilder.Append (" () ");
} else {
stackTraceBuilder.Append (" (");
int pcount = parameters.Length;
ParameterInfo param = null;
for (int p = 0; p < pcount; p++) {
param = parameters [p];
stackTraceBuilder.AppendFormat ("{0} {1}", param.ParameterType.Name, param.Name);
if (p != pcount - 1) {
stackTraceBuilder.Append (", ");
}
}
param = null;
stackTraceBuilder.Append (") ");
}
string fileName = frame.GetFileName ();
if (!string.IsNullOrEmpty (fileName) && !fileName.ToLower ().Equals ("unknown")) {
fileName = fileName.Replace ("\\", "/");
int loc = fileName.ToLower ().IndexOf ("/assets/");
if (loc < 0) {
loc = fileName.ToLower ().IndexOf ("assets/");
}
if (loc > 0) {
fileName = fileName.Substring (loc);
}
stackTraceBuilder.AppendFormat ("(at {0}:{1})", fileName, frame.GetFileLineNumber ());
}
stackTraceBuilder.AppendLine ();
}
// report
_reportException (uncaught, name, reason, stackTraceBuilder.ToString ());
}
private static void _reportException (bool uncaught, string name, string reason, string stackTrace)
{
if (string.IsNullOrEmpty (name)) {
return;
}
if (string.IsNullOrEmpty (stackTrace)) {
stackTrace = StackTraceUtility.ExtractStackTrace ();
}
if (string.IsNullOrEmpty (stackTrace)) {
stackTrace = "Empty";
} else {
try {
string[] frames = stackTrace.Split ('\n');
if (frames != null && frames.Length > 0) {
StringBuilder trimFrameBuilder = new StringBuilder ();
string frame = null;
int count = frames.Length;
for (int i = 0; i < count; i++) {
frame = frames [i];
if (string.IsNullOrEmpty (frame) || string.IsNullOrEmpty (frame.Trim ())) {
continue;
}
frame = frame.Trim ();
// System.Collections.Generic
if (frame.StartsWith ("System.Collections.Generic.") || frame.StartsWith ("ShimEnumerator")) {
continue;
}
if (frame.StartsWith ("Bugly")) {
continue;
}
if (frame.Contains ("= new Vector3")) {
continue;
}
int start = frame.ToLower ().IndexOf ("(at");
int end = frame.ToLower ().IndexOf ("/assets/");
if (start > 0 && end > 0) {
trimFrameBuilder.AppendFormat ("{0}(at {1}", frame.Substring (0, start).Replace (":", "."), frame.Substring (end));
} else {
trimFrameBuilder.Append (frame.Replace (":", "."));
}
trimFrameBuilder.AppendLine ();
}
stackTrace = trimFrameBuilder.ToString ();
}
} catch {
PrintLog(LogSeverity.LogWarning,"{0}", "Error ");
}
}
PrintLog (LogSeverity.LogError, "ReportException: {0} {1}\n*********\n{2}\n*********", name, reason, stackTrace);
_uncaughtAutoReportOnce = uncaught && _autoQuitApplicationAfterReport;
ReportException (uncaught ? EXCEPTION_TYPE_UNCAUGHT : EXCEPTION_TYPE_CAUGHT, name, reason, stackTrace, uncaught && _autoQuitApplicationAfterReport);
}
private static void _HandleException (LogSeverity logLevel, string name, string message, string stackTrace, bool uncaught)
{
if (!IsInitialized) {
DebugLog (null, "It has not been initialized.");
return;
}
if (logLevel == LogSeverity.Log) {
return;
}
if ((uncaught && logLevel < _autoReportLogLevel)) {
DebugLog (null, "Not report exception for level {0}", logLevel.ToString ());
return;
}
string type = null;
string reason = null;
if (!string.IsNullOrEmpty (message)) {
try {
if ((LogSeverity.LogException == logLevel) && message.Contains ("Exception")) {
Match match = new Regex (@"^(?<errorType>\S+):\s*(?<errorMessage>.*)", RegexOptions.Singleline).Match (message);
if (match.Success) {
type = match.Groups ["errorType"].Value.Trim();
reason = match.Groups ["errorMessage"].Value.Trim ();
}
} else if ((LogSeverity.LogError == logLevel) && message.StartsWith ("Unhandled Exception:")) {
Match match = new Regex (@"^Unhandled\s+Exception:\s*(?<exceptionName>\S+):\s*(?<exceptionDetail>.*)", RegexOptions.Singleline).Match(message);
if (match.Success) {
string exceptionName = match.Groups ["exceptionName"].Value.Trim();
string exceptionDetail = match.Groups ["exceptionDetail"].Value.Trim ();
//
int dotLocation = exceptionName.LastIndexOf(".");
if (dotLocation > 0 && dotLocation != exceptionName.Length) {
type = exceptionName.Substring(dotLocation + 1);
} else {
type = exceptionName;
}
int stackLocation = exceptionDetail.IndexOf(" at ");
if (stackLocation > 0) {
//
reason = exceptionDetail.Substring(0, stackLocation);
// substring after " at "
string callStacks = exceptionDetail.Substring(stackLocation + 3).Replace(" at ", "\n").Replace("in <filename unknown>:0","").Replace("[0x00000]","");
//
stackTrace = string.Format("{0}\n{1}", stackTrace, callStacks.Trim());
} else {
reason = exceptionDetail;
}
// for LuaScriptException
if(type.Equals("LuaScriptException") && exceptionDetail.Contains(".lua") && exceptionDetail.Contains("stack traceback:")) {
stackLocation = exceptionDetail.IndexOf("stack traceback:");
if(stackLocation > 0) {
reason = exceptionDetail.Substring(0, stackLocation);
// substring after "stack traceback:"
string callStacks = exceptionDetail.Substring(stackLocation + 16).Replace(" [", " \n[");
//
stackTrace = string.Format("{0}\n{1}", stackTrace, callStacks.Trim());
}
}
}
}
} catch {
}
if (string.IsNullOrEmpty (reason)) {
reason = message;
}
}
if (string.IsNullOrEmpty (name)) {
if (string.IsNullOrEmpty (type)) {
type = string.Format ("Unity{0}", logLevel.ToString ());
}
} else {
type = name;
}
_reportException (uncaught, type, reason, stackTrace);
}
private static bool _uncaughtAutoReportOnce = false;
#endregion
}
|