public void OnException(ExceptionContext context) { this._logger.LogError("MatterCenterExceptionFilter", context.Exception); var stackTrace = new StackTrace(context.Exception, true); StackFrame stackFrameInstance = null; if(stackTrace.GetFrames().Length>0) { for(int i=0; i< stackTrace.GetFrames().Length; i++) { if(stackTrace.GetFrames()[i].ToString().Contains("Microsoft.Legal.Matter")) { stackFrameInstance = stackTrace.GetFrames()[i]; break; } } } var response = new ErrorResponse() { Message = context.Exception.Message, StackTrace = context.Exception.ToString(), Description = "Error occured in the system. Please contact the administrator", //Exception = context.Exception.ToString(), LineNumber = stackFrameInstance?.GetFileLineNumber(), MethodName = stackFrameInstance?.GetMethod().Name, ClassName = stackFrameInstance?.GetMethod().DeclaringType.Name, ErrorCode = ((int)HttpStatusCode.InternalServerError).ToString() }; context.Result = new ObjectResult(response) { StatusCode = (int)HttpStatusCode.InternalServerError, DeclaredType = typeof(ErrorResponse) }; }
/// <summary> /// This method will generate error response that will be sent to the client /// </summary> /// <param name="ex">Exception object that occured </param> /// <returns></returns> public ErrorResponse GenerateErrorResponse(Exception ex) { var stackTrace = new StackTrace(ex, true); StackFrame stackFrameInstance = null; if (stackTrace.GetFrames().Length > 0) { for (int i = 0; i < stackTrace.GetFrames().Length; i++) { if (stackTrace.GetFrames()[i].ToString().Contains("Microsoft.Legal.Matter")) { stackFrameInstance = stackTrace.GetFrames()[i]; break; } } } //Create custom exception response that needs to be send to client var response = new ErrorResponse() { Message = ex.Message, StackTrace = ex.StackTrace.ToString(), Description = "Error occured in the system. Please contact the administrator", Exception = ex, LineNumber = stackFrameInstance?.GetFileLineNumber(), MethodName = stackFrameInstance?.GetMethod().Name, ClassName = stackFrameInstance?.GetMethod().DeclaringType.Name, ErrorCode = ((int)HttpStatusCode.InternalServerError).ToString(), IsErrror = true }; return response; }
public static void TraceCall() { #if TRACE var st = new StackTrace(); var caller_sf = st.GetFrames()[1]; var caller_method = caller_sf.GetMethod(); //if (caller_sf.ToString() == lastCall) // return; //else // lastCall = caller_sf.ToString(); var caller_method_from_compiler_non_tainted = st.GetFrames().Skip(2).SkipWhile(x => x.GetMethod().DeclaringType.FullName.Contains("Microsoft.FSharp.Compiler.Tainted")).FirstOrDefault(); // var caller_params = caller_method.GetParameters(); Console.WriteLine("Called {0}.{1}.{2} [from {3}]", caller_method.DeclaringType.Namespace, caller_method.DeclaringType.Name, caller_method.Name, caller_method_from_compiler_non_tainted.GetMethod().Name); #else #endif }
/// <summary> /// Implement OnException method of IExceptionFilter which will be invoked /// for all unhandled exceptions /// </summary> /// <param name="context"></param> public void OnException(ExceptionContext context) { this._logger.LogError("MatterCenterExceptionFilter", context.Exception); var stackTrace = new StackTrace(context.Exception, true); StackFrame stackFrameInstance = null; if(stackTrace.GetFrames().Length>0) { for(int i=0; i< stackTrace.GetFrames().Length; i++) { if(stackTrace.GetFrames()[i].ToString().Contains("Microsoft.Legal.Matter")) { stackFrameInstance = stackTrace.GetFrames()[i]; break; } } } //Create custom exception response that needs to be send to client var response = new ErrorResponse() { Message = context.Exception.Message, StackTrace = context.Exception.ToString(), Description = "Error occured in the system. Please contact the administrator", //Exception = context.Exception.ToString(), LineNumber = stackFrameInstance?.GetFileLineNumber(), MethodName = stackFrameInstance?.GetMethod().Name, ClassName = stackFrameInstance?.GetMethod().DeclaringType.Name, ErrorCode = ((int)HttpStatusCode.InternalServerError).ToString() }; //Create properties that need to be added to application insights var properties = new Dictionary<string, string>(); properties.Add("StackTrace", response.StackTrace); properties.Add("LineNumber", response.LineNumber.ToString()); properties.Add("MethodName", response.MethodName.ToString()); properties.Add("ClassName", response.ClassName.ToString()); properties.Add("ErrorCode", response.ErrorCode.ToString()); //Create Telemetry object to add exception to the application insights var ai = new TelemetryClient(); ai.InstrumentationKey = instrumentationKey; if(ai.IsEnabled()) { //add exception to the Application Insights ai.TrackException(context.Exception, properties); } //Send the exceptin object to the client context.Result = new ObjectResult(response) { StatusCode = (int)HttpStatusCode.InternalServerError, DeclaredType = typeof(ErrorResponse) }; }
// avoid replication of tests on all constructors (this is no // problem because the stack is already set correctly). The // goal is to call every property and methods to see if they // have any* security requirements (*except for LinkDemand and // InheritanceDemand). private void Check (StackTrace st) { if (st.FrameCount > 0) Assert.IsNotNull (st.GetFrame (0), "GetFrame"); else Assert.IsNull (st.GetFrame (0), "GetFrame"); if (st.FrameCount > 0) Assert.IsNotNull (st.GetFrames (), "GetFrames"); else Assert.IsNull (st.GetFrames (), "GetFrames"); Assert.IsNotNull (st.ToString (), "ToString"); }
public SentryStacktrace(Exception e) { StackTrace trace = new StackTrace(e, true); if (trace.GetFrames() != null) { int length = trace.GetFrames().Length; this.Frames = new ExceptionFrame[length]; for (int i=0; i<length; i++) { StackFrame frame = trace.GetFrame(length - i - 1); this.Frames[i] = BuildExceptionFrame(frame); } } }
/// <summary> /// スタックトレースを取得します。 /// </summary> public static IEnumerable<string> ToStackTraceString(StackTrace stackTrace) { var omitted = false; return stackTrace.GetFrames() .Where(frame => { if (string.IsNullOrEmpty(frame.GetFileName())) { var oldOmitted = omitted; omitted = true; return !oldOmitted; } else { omitted = false; return true; } }) .Select(frame => { if (string.IsNullOrEmpty(frame.GetFileName())) { return " 場所: 省略されますた"; } else { return string.Format(" 場所: {0}({1}): {2}", frame.GetFileName(), frame.GetFileLineNumber(), GetMethodString(frame.GetMethod())); } }); }
public static void LogError(string msg , LogType lt , Exception ex) { writeMutex.WaitOne(); System.IO.StreamWriter file = new System.IO.StreamWriter(Env.ErrorFolderPath, true); file.WriteLine(lt.ToString() + ":"); string[] lines = msg.Split('\n'); foreach (var l in lines) { file.WriteLine(l); } file.WriteLine("_Time :"+ DateTime.Now.ToString(CultureInfo.InvariantCulture)); if(ex != null) { var st = new StackTrace(ex, true); var stackFrames = st.GetFrames(); if (stackFrames != null) foreach (var frame in stackFrames) { file.WriteLine("_Frame : " + frame.ToString()); // Get the line number from the stack frame var line = frame.GetFileLineNumber(); file.WriteLine("_Line : " + line.ToString()); } } file.WriteLine("---------------------------------------------------------END----------------------------------------------------------"); file.Close(); writeMutex.ReleaseMutex(); }
public static void ER(Exception e, params string[] extras) { StackTrace st = new StackTrace(); StackFrame[] frames = st.GetFrames(); string methodName = "UnknownMethod"; for(int i=0;i< frames.Length;i++) { if (frames[i].GetMethod().Name == System.Reflection.MethodInfo.GetCurrentMethod().Name) { if (i + 1 < frames.Length) { methodName = frames[i + 1].GetMethod().Name; break; } } } Console.WriteLine(String.Format("{1}[{4}:{5}][ERROR({2})]{0}:{3}", methodName, tab, Thread.CurrentThread.ManagedThreadId, e.Message, DateTime.Now.ToShortDateString(), DateTime.Now.ToShortTimeString())); Console.WriteLine("==========StackTrace=========="); if (e.StackTrace != null) Console.WriteLine(e.StackTrace.ToString()); else Console.WriteLine(st.ToString()); Console.WriteLine("=============END=============="); foreach (string s in extras) Console.WriteLine(s); }
private bool Check_PopedomTypeAttaible() { //System.Web.HttpResponse rp = System.Web.HttpContext.Current.Response; //rp.Write("执行方法名称!"); //rp.Write(System.Reflection.MethodBase.GetCurrentMethod().Name); //rp.Write("<br>"); StackTrace stack = new StackTrace(); foreach (StackFrame sframe in stack.GetFrames()) { //rp.Write(sframe.GetMethod().Name); //rp.Write("<br>"); foreach (PopedomTypeAttaible var in sframe.GetMethod().GetCustomAttributes(typeof(PopedomTypeAttaible), true)) { //rp.Write(var.PType.ToString()); //rp.Write("<br>"); //rp.Write("无权限!"); //rp.End(); //return false; FrameWorkPermission.CheckPermissionVoid(var.PType); } //rp.Write("------"); //rp.Write("<br>"); } //rp.End(); return true; }
public override void Eval(MockDirectoryWrapper dir) { if (DoFail && TestThread()) { bool isDoFlush = false; bool isClose = false; var trace = new StackTrace(); foreach (var frame in trace.GetFrames()) { var method = frame.GetMethod(); if (isDoFlush && isClose) { break; } if ("flush".Equals(method.Name)) { isDoFlush = true; } if ("close".Equals(method.Name)) { isClose = true; } } if (isDoFlush && !isClose && Random().NextBoolean()) { HitExc = true; throw new IOException(Thread.CurrentThread.Name + ": now failing during flush"); } } }
private static string GetSource() { // skip 2 frames: GetSource and its caller var trace = new StackTrace(2); var frames = trace.GetFrames(); // might not need a foreach, but doing to to be sure foreach (var frame in frames) { var method = frame.GetMethod(); var type = method.DeclaringType; var assembly = type.Assembly; // only remove System? if (assembly.GetName().Name == "System") { continue; } // in case there are > 2 frames if (type.Name == "Log") { continue; } // that sounds just about nice return string.Format("{0}::{1}", type.Name, method.Name); } return ""; }
/// <summary> /// Log event /// </summary> public static void Log( params String[] messages ) { log.Info(messages); // TODO: replace this with log4net but figure out how to reuse current processes configuration/logger lock ( logfile ) { FileStream fs = new FileStream( Tracer.logfile , FileMode.Append , FileAccess.Write ); StreamWriter sw = new StreamWriter( fs ); sw.WriteLine( DateTime.Now ); StackTrace stackTrace = new StackTrace( true ); StackFrame[] sts = stackTrace.GetFrames(); sw.WriteLine( "Content:" ); foreach ( String msg in messages ) sw.WriteLine( msg ); String stackMsg = Environment.StackTrace; sw.WriteLine( Environment.StackTrace ); sw.WriteLine( "==============================" ); sw.Flush(); sw.Close(); } }
void LoadDebugging(object sender, AssemblyLoadEventArgs args, string name) { // can skip the first 2 frames, // they just have the event handlers for assem load StackTrace stackTrace = new StackTrace(2); StackFrame[] frames = stackTrace.GetFrames(); // dump the stack foreach (StackFrame frame in frames) { MethodBase method = frame.GetMethod(); ParameterInfo[] parameters = method.GetParameters(); StringBuilder parString = new StringBuilder(); for (int i = 0; i < parameters.Length; i++) { ParameterInfo par = parameters[i]; if (i > 0) parString.Append(", "); parString.Append(par.ParameterType.ToString()); } //LoggerFactory.Default.Log(AssemblyLoadMonitorLogID, " at " + method.DeclaringType.Name + "." + method.Name + "(" + parString.ToString() + ")"); } }
public void OnGUI() { ICollection<MethodReport> failedTests = Suite.FailedTests; if (failedTests.Count != 0) { int i = 0; foreach (MethodReport failedTest in failedTests) { string filePath = null; int lineNumber = -1; StackTrace trace = new StackTrace(failedTest.RaisedException, true); foreach (StackFrame frame in trace.GetFrames()) { if (frame.GetMethod().DeclaringType.GetCustomAttribute<JUUTTestClassAttribute>() != null) { string fullPath = frame.GetFileName(); if (fullPath != null) { filePath = fullPath.Substring(fullPath.IndexOf("Assets", System.StringComparison.Ordinal)); lineNumber = frame.GetFileLineNumber(); } break; } } if (filePath != null) { if (GUI.Button(new Rect(10, 10 + i * 25, 600, 20), failedTest.ShortText)) { JUUTUnityUtil.OpenTestFile(filePath, lineNumber); } } i++; } } }
protected String GetCallingFilePath() { var trace = new StackTrace(true); var frames = trace.GetFrames(); var filename = frames[3].GetFileName(); return filename; }
void LoadDebugging(object sender, AssemblyLoadEventArgs args, string name) { // we'll output the full assemblyName Console.WriteLine("{0} was loaded:", args.LoadedAssembly.FullName); // can skip the first 2 frames, // they just have the event handlers for assem load StackTrace stackTrace = new StackTrace(2); StackFrame[] frames = stackTrace.GetFrames(); // dump the stack foreach (StackFrame frame in frames) { MethodBase method = frame.GetMethod(); ParameterInfo[] parameters = method.GetParameters(); StringBuilder parString = new StringBuilder(); for (int i = 0; i < parameters.Length; i++) { ParameterInfo par = parameters[i]; if (i > 0) parString.Append(", "); parString.Append(par.ParameterType.ToString()); } Console.WriteLine(" at {0}.{1}({2})", method.DeclaringType.Name, method.Name, parString.ToString()); } }
public SentryStacktrace(Exception e) { StackTrace trace = new StackTrace(e, true); Frames = (trace.GetFrames() ?? new StackFrame[0]).Reverse().Select(frame => { int lineNo = frame.GetFileLineNumber(); if (lineNo == 0) { //The pdb files aren't currently available lineNo = frame.GetILOffset(); } var method = frame.GetMethod(); return new ExceptionFrame() { Filename = frame.GetFileName(), Module = (method.DeclaringType != null) ? method.DeclaringType.FullName : null, Function = method.Name, Source = method.ToString(), LineNumber = lineNo, ColumnNumber = frame.GetFileColumnNumber() }; }).ToList(); }
/// <summary> /// Collects the call stack at a given moment in time. /// </summary> /// <returns>A string representing the call stack in the form Function1,Class1,FileInfo1\nFunction2,Class2,FileInfo2\n...</returns> protected string GetCallStack() { StackTrace stackTrace = new StackTrace(true); StackFrame[] stackFrames = stackTrace.GetFrames(); string stack = string.Empty; foreach (StackFrame stackFrame in stackFrames) { MethodBase method = stackFrame.GetMethod(); if (method != null && method.ReflectedType != null) { string function = method.Name; string className = method.ReflectedType.FullName; string fileName = stackFrame.GetFileName(); string fileInfo = (fileName != null) ? string.Format(CultureInfo.InvariantCulture, "{0}:{1}", fileName.Split('\\').Last(), stackFrame.GetFileLineNumber()) : string.Empty; bool isOwnCode = !(className.StartsWith("Microsoft.", StringComparison.Ordinal) || className.StartsWith("System.", StringComparison.Ordinal)); // This data gets stored in a custom property. The length of data stored in a custom property is limited. // We save space by only sending the last part of the namespace (the class name). className = className.Split('.').Last(); // We save even more space by only sending the "Just My Code" version of the call stack. if (isOwnCode) { stack += string.Format(CultureInfo.InvariantCulture, "{0},{1},{2}\n", function, className, fileInfo); } } } return stack; }
// Because Assembly.GetEntryAssembly() doesn't work in UnitTests... public static Assembly Go() { var specAidAssembly = Assembly.GetExecutingAssembly(); StackTrace stackTrace = new StackTrace(); // get call stack StackFrame[] stackFrames = stackTrace.GetFrames(); // get method calls (frames) Assembly assembly = null; foreach (var stackFrame in stackFrames) { try { var dType = stackFrame.GetMethod().DeclaringType; if (dType == null) continue; assembly = dType.Assembly; if (specAidAssembly.FullName != assembly.FullName) { return assembly; } } // ReSharper disable EmptyGeneralCatchClause catch // ReSharper restore EmptyGeneralCatchClause { // Throw away the exception... // Either we have the assembly in the Stack or we don't... } } return assembly; }
private Logger Log(Level Level, object Format, params object[] Params) { if (Enabled || OnGlobalLog != null) { StackTrace stackTrace = new StackTrace(); StackFrame StackFrame = null; foreach (var Frame in stackTrace.GetFrames()) { if (Frame.GetMethod().DeclaringType != typeof(Logger)) { StackFrame = Frame; break; } } if (Enabled) { if (OnLog != null) OnLog(Level, String.Format(Format.ToString(), Params), StackFrame); } if (OnGlobalLog != null) { OnGlobalLog(Name, Level, String.Format(Format.ToString(), Params), StackFrame); } } return this; }
public bool Perform() { Reset(); StackTrace trace = new StackTrace(false); StackFrame[] frames= trace.GetFrames(); for (int i=frames.Length-1; i>=0; i--) { StackFrame frame = frames[i]; string typeName = frame.GetMethod().DeclaringType.FullName; mTrace.Append(Common.NewLine + typeName + " : " + frame.GetMethod()); List<StackFrameBase> tests; if (mTests.TryGetValue("", out tests)) { if (Test(frame, trace, tests)) return true; } if (mTests.TryGetValue(typeName, out tests)) { if (Test(frame, trace, tests)) return true; } } return false; }
public static void BeginLog(string message) { if (LoggerData._logging.Equals(true)) { string callingmethod = string.Empty; int managedthreadid = Thread.CurrentThread.ManagedThreadId; StackTrace stackTrace = new StackTrace(); if (stackTrace != null) { StackFrame[] stackFrames = stackTrace.GetFrames(); if (stackFrames != null && (stackFrames.Count() >= 1)) { callingmethod = ((System.Type)stackFrames[1].GetMethod().ReflectedType).Name + "." + stackFrames[1].GetMethod().Name; // System.Diagnostics.Debug.WriteLine(callingmethod); } } LoggerData loggerdata = new LoggerData(message, System.Environment.TickCount, callingmethod); if (_threadtotickcountqueue.ContainsKey(managedthreadid)) ((Stack<LoggerData>)_threadtotickcountqueue[managedthreadid]).Push(loggerdata); else { Stack<LoggerData> queue = new Stack<LoggerData>(); queue.Push(loggerdata); _threadtotickcountqueue[managedthreadid] = queue; } } }
/// <summary> /// Converts an exception stack to a sarif code location list. /// </summary> public static IList<AnnotatedCodeLocation> ToCodeLocations(this Exception exception) { List<AnnotatedCodeLocation> codeLocations = new List<AnnotatedCodeLocation>(); StackTrace stack = new StackTrace(exception); foreach (StackFrame frame in stack.GetFrames()) { AnnotatedCodeLocation codeLocation = new AnnotatedCodeLocation(); MemberInfo member = frame.GetMethod(); if (member != null) { codeLocation.Message = member.ReflectedType.FullName + "." + member.Name; } PhysicalLocationComponent physicalLocation = new PhysicalLocationComponent(); string filename = frame.GetFileName(); if (!String.IsNullOrWhiteSpace(filename)) { physicalLocation.Uri = new Uri(filename); } physicalLocation.Region = new Region(); physicalLocation.Region.StartLine = frame.GetFileLineNumber(); physicalLocation.Region.EndLine = frame.GetFileLineNumber(); physicalLocation.Region.StartColumn = frame.GetFileColumnNumber(); physicalLocation.Region.EndColumn = frame.GetFileColumnNumber(); codeLocation.PhysicalLocation = new List<PhysicalLocationComponent>() { physicalLocation }; codeLocations.Add(codeLocation); } return codeLocations; }
protected String GetCallingMethod() { var trace = new StackTrace(true); var frames = trace.GetFrames(); var method = frames[3].GetMethod(); return method.ToString(); }
public Boolean UsePrefix() { StackTrace stackTrace = new StackTrace(); List<StackFrame> stackFramesNow = stackTrace.GetFrames().ToList(); stackFramesNow.Reverse(); Boolean foundAll = true; foreach (var stackFrame in stackFrames) { Boolean foundNow = false; foreach (var frameNow in stackFramesNow) { string stackCompare = stackFrame.GetMethod().Module + "#" + stackFrame.GetMethod().Name; string nowCompare = frameNow.GetMethod().Module + "#" + frameNow.GetMethod().Name; if (stackCompare == nowCompare) { foundNow = true; break; } } foundAll = foundAll & foundNow; } return foundAll; }
/// <summary> /// Traceログを出力 /// </summary> /// <param name="ex"></param> public static void TraceLog(Exception ex) { int threadID = Thread.CurrentThread.ManagedThreadId; StackTrace st = new StackTrace(ex); string methodName = string.Empty; string className = string.Empty; foreach (StackFrame sf in st.GetFrames()) { methodName = sf.GetMethod().Name; if (sf.GetMethod().ReflectedType == null) continue; className = sf.GetMethod().ReflectedType.FullName; if (className != st.GetFrame(0).GetMethod().ReflectedType.FullName && methodName != "OnExceptionOccured") { break; } } StringBuilder sb = new StringBuilder(); sb.Append(threadID); sb.Append(Const_DelimiterTab); sb.Append(className); sb.Append(Const_DelimiterTab); sb.Append(methodName); sb.Append(Const_DelimiterTab); sb.Append(ex.Message); sb.Append(Const_DelimiterTab); sb.Append(ex.StackTrace); WriteLog(sb.ToString()); }
/// <summary> /// Logwriters the specified source. /// </summary> /// <param name="source">object that wrote the logentry.</param> /// <param name="prio">Importance of the log message</param> /// <param name="message">The message.</param> public void Write(object source, LogPrio prio, string message) { StringBuilder sb = new StringBuilder(); sb.Append(DateTime.Now.ToString()); sb.Append(" "); sb.Append(prio.ToString().PadRight(10)); sb.Append(" | "); #if DEBUG StackTrace trace = new StackTrace(); StackFrame[] frames = trace.GetFrames(); int endFrame = frames.Length > 4 ? 4 : frames.Length; int startFrame = frames.Length > 0 ? 1 : 0; for (int i = startFrame; i < endFrame; ++i) { sb.Append(frames[i].GetMethod().Name); sb.Append(" -> "); } #else sb.Append(System.Reflection.MethodBase.GetCurrentMethod().Name); sb.Append(" | "); #endif sb.Append(message); Console.ForegroundColor = GetColor(prio); Console.WriteLine(sb.ToString()); Console.ForegroundColor = ConsoleColor.Gray; }
private static void Run(Byte[] code, Boolean raiseException = false) { Console.WriteLine(); var stackTrace = new StackTrace(); var stackFrame = stackTrace.GetFrames()[1]; var methodName = stackFrame.GetMethod().Name; Console.WriteLine("*** Start: " + methodName); Exception e = null; try { RunTest(code, ADDRESS, Common.UC_MODE_32); } catch (UnicornEngineException ex) { e = ex; } if (!raiseException && e != null) { Console.Error.WriteLine("Emulation FAILED! " + e.Message); } Console.WriteLine("*** End: " + methodName); Console.WriteLine(); }
private static string GetPreviousMethod(int back = 2) { StackTrace st = new StackTrace(); StackFrame[] frames = st.GetFrames(); string methodName = "UnknownMethod"; if (frames != null && frames.Length > (back + 1)) methodName = frames[back].GetMethod().Name; return methodName; }
/// <summary> /// 打印堆栈信息 /// </summary> /// <returns></returns> public static string PrintStackTrace() { string stackStr = null; //设置为true,这样才能捕获到文件路径名和当前行数,当前行数为GetFrames代码的函数,也可以设置其他参数 System.Diagnostics.StackTrace st = new System.Diagnostics.StackTrace(true); //得到当前的所以堆栈 System.Diagnostics.StackFrame[] sf = st.GetFrames(); for (int i = 0; i < sf.Length; ++i) { stackStr = stackStr + "\r\n" + " FileName=" + sf[i].GetFileName() + " fullname=" + sf[i].GetMethod().DeclaringType.FullName + " function=" + sf[i].GetMethod().Name + " FileLineNumber=" + sf[i].GetFileLineNumber(); } return(stackStr); }
private static string GetLoggerStackTrace(bool isInfo = false) { System.Diagnostics.StackTrace st = new System.Diagnostics.StackTrace(true); System.Diagnostics.StackFrame[] sfs = st.GetFrames(); System.Text.StringBuilder sb = new System.Text.StringBuilder(); int tempIndex = 0; foreach (var item in sfs) { tempIndex++; if (item.GetMethod().DeclaringType.FullName == "Sugar.Logger") { continue; } sb.Append(" "); sb.Append($"{item.GetMethod().DeclaringType.FullName}:{item.GetMethod().Name}"); sb.Append("("); System.Reflection.ParameterInfo tempParameterInfo; System.Reflection.ParameterInfo[] parameters = item.GetMethod().GetParameters(); for (int i = 0; i < parameters.Length; i++) { tempParameterInfo = parameters[i]; sb.Append($"{tempParameterInfo.ParameterType} {tempParameterInfo.Name}"); if (i < parameters.Length - 1) { sb.Append(','); } } sb.Append(')'); sb.Append($" at ({item.GetFileName()}:{item.GetFileLineNumber()})"); if (tempIndex != sfs.Length) { sb.AppendLine(); } //if (isInfo) //{ // if (tempIndex == 1) // { // break; // } //} } return(sb.ToString()); }
public static void Print(object log, LogLevel level) { if (!verboseMode) { return; } System.Text.StringBuilder builder = new System.Text.StringBuilder(); System.Diagnostics.StackTrace trace = new System.Diagnostics.StackTrace(); System.Diagnostics.StackFrame[] stackFrames = trace.GetFrames(); string caller = stackFrames[1].GetMethod().Name; for (int i = 0; i < stackFrames.Length; i++) { System.Type reflectedType = stackFrames[i].GetMethod().ReflectedType; if (builder.ToString().IndexOf(reflectedType.FullName) == -1 && reflectedType.FullName.Length < 32) { builder.Append($"{reflectedType.FullName}{(i == stackFrames.Length - 1 ? "" : ">>")}"); } } if (builder.ToString().EndsWith(">>")) { builder = builder.Remove(builder.Length - 2, 2); } switch (level) { case LogLevel.Warning: Debug.LogWarning($"[{builder}:{caller}] -> {log}"); break; case LogLevel.Assert: Debug.LogAssertion($"[{builder}:{caller}] -> {log}"); break; case LogLevel.Error: Debug.LogError($"[{builder}:{caller}] -> {log}"); break; default: Debug.Log($"[{builder}:{caller}] -> {log}"); break; } }
internal static object CallMethodEx(Type type, object instance, string class_name, string method_name, params object[] args) { type = null; if (type == null) { if (instance != null) { type = instance.GetType(); } if (class_name != null) { type = Type.GetType(class_name, throwOnError: false); } if (type == null) { System.Diagnostics.StackTrace stackTrace = new System.Diagnostics.StackTrace(); System.Diagnostics.StackFrame frame = stackTrace.GetFrames()[1]; var method = frame.GetMethod(); string methodName = method.Name; Type methodsClass = method.DeclaringType; type = methodsClass; if (type == null) { return(null); } } } var m = type.GetMethod(method_name, (instance == null ? System.Reflection.BindingFlags.Static : System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.Static) | System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.NonPublic); if (m == null) { return(null); } return(m.Invoke(m.IsStatic ? null : instance, args)); }
internal static bool SetFieldEx(Type type, object instance, string class_name, string field_name, object value) { type = null; if (type == null) { if (instance != null) { type = instance.GetType(); } if (class_name != null) { type = Type.GetType(class_name, throwOnError: false); } if (type == null) { System.Diagnostics.StackTrace stackTrace = new System.Diagnostics.StackTrace(); System.Diagnostics.StackFrame frame = stackTrace.GetFrames()[1]; var method = frame.GetMethod(); string methodName = method.Name; Type methodsClass = method.DeclaringType; type = methodsClass; if (type == null) { return(false); } } } var m = type.GetField(field_name, (instance == null ? System.Reflection.BindingFlags.Static : System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.Static) | System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.NonPublic); if (m == null) { return(false); } m.SetValue(m.IsStatic ? null : instance, value); return(true); }
static string GetStackTrace(Exception e) { string stackTrace = ""; try { StackTrace st = new System.Diagnostics.StackTrace(e); foreach (StackFrame frame in st.GetFrames()) { stackTrace = "at " + frame.GetMethod().Module.Name + "." + frame.GetMethod().ReflectedType.Name + "." + frame.GetMethod().Name + " (IL offset: 0x" + frame.GetILOffset().ToString("x") + ")\n" + stackTrace; } Console.Write(stackTrace); Console.WriteLine("Message: " + e.Message); } catch { } return(stackTrace); }
public VulcanMessage(Severity severity, Exception innerException, string message, params object[] formatParmeters) { _innerException = innerException; _severity = severity; System.Diagnostics.StackTrace st = new System.Diagnostics.StackTrace(); System.Diagnostics.StackFrame[] stackFrames = st.GetFrames(); MethodBase method = null; foreach (System.Diagnostics.StackFrame sf in stackFrames) { method = sf.GetMethod(); if (method.ReflectedType.Equals(typeof(VulcanEngine.Common.MessageEngine)) || method.ReflectedType.Equals(typeof(VulcanEngine.Common.VulcanMessage))) { continue; } else { break; } } this._message = String.Format("{0}: {1}: {2}", severity, method.ReflectedType.Name, String.Format(message, formatParmeters)); }
/// <summary> /// Gets the stack trace with IL offsets /// </summary> public static string StackTraceIL(this Exception ex) { // Need to use IL offsets as proxy for line numbers in stack trace in Silverlight. Taken from // http://liviutrifoi.wordpress.com/2011/04/21/silverlight-stack-trace-line-numbers/ string stackTrace = null; try { StackTrace st = new System.Diagnostics.StackTrace(ex); if (st != null) { foreach (StackFrame frame in st.GetFrames()) { stackTrace = "at " + frame.GetMethod().Module.Name + "." + frame.GetMethod().ReflectedType.Name + "." + frame.GetMethod().Name + " (IL offset: 0x" + frame.GetILOffset().ToString("x") + ")\n" + stackTrace; } } } catch { } return(stackTrace); }
/// <summary> /// Produces an async-friendly readable representation of the stack trace. /// </summary> /// <remarks> /// The async-friendly formatting is achieved by: /// * Skipping all awaiter frames (all methods in types implementing <see cref="IAsyncStateMachine" />). /// * Inferring the original method name from the async state machine class (<see cref="IAsyncStateMachine" />) /// and removing the "MoveNext" - currently only for C#. /// * Adding the "async" prefix after "at" on each line for async invocations. /// * Appending "(?)" to the method signature to indicate that parameter information is missing. /// * Removing the "End of stack trace from previous location..." text. /// </remarks> /// <param name="stackTrace">The stack trace.</param> /// <returns>An async-friendly readable representation of the stack trace.</returns> public static string ToAsyncString(this StackTrace stackTrace) { if (stackTrace == null) { throw new ArgumentNullException(nameof(stackTrace)); } var stackFrames = stackTrace.GetFrames(); if (stackFrames == null) { return(string.Empty); } var displayFilenames = true; var firstFrame = true; var stringBuilder = new StringBuilder(255); foreach (var frame in stackFrames) { var method = frame.GetMethod(); if (method == null) { continue; } var declaringType = method.DeclaringType?.GetTypeInfo(); // skip awaiters if (declaringType != null && (typeof(INotifyCompletion).GetTypeInfo().IsAssignableFrom(declaringType) || method.DeclaringType == typeof(ExceptionDispatchInfo))) { continue; } if (firstFrame) { firstFrame = false; } else { stringBuilder.Append(Environment.NewLine); } stringBuilder.AppendFormat(CultureInfo.InvariantCulture, " {0} ", AtString); var isAsync = FormatMethodName(stringBuilder, declaringType); if (!isAsync) { stringBuilder.Append(method.Name); if (method is MethodInfo methodInfo && methodInfo.IsGenericMethod) { FormatGenericArguments(stringBuilder, methodInfo.GetGenericArguments()); } } else if (declaringType?.IsGenericType == true) { // ReSharper disable once PossibleNullReferenceException FormatGenericArguments(stringBuilder, declaringType.GenericTypeArguments); } stringBuilder.Append("("); if (isAsync) { stringBuilder.Append("?"); } else { FormatParameters(stringBuilder, method); } stringBuilder.Append(")"); displayFilenames = FormatFileName(displayFilenames, frame, stringBuilder); } return(stringBuilder.ToString()); }
public void Main(string[] args) { try { _config = new Config(); AppDomain.CurrentDomain.AssemblyResolve += delegate(object sender, ResolveEventArgs sargs) { var asm = typeof(Terraria.Program).Assembly; var resourceName = new AssemblyName(sargs.Name).Name + ".dll"; var text = Array.Find(asm.GetManifestResourceNames(), (string element) => element.EndsWith(resourceName)); if (text == null) { return(null); } using (Stream manifestResourceStream = asm.GetManifestResourceStream(text)) { var array = new byte[manifestResourceStream.Length]; manifestResourceStream.Read(array, 0, array.Length); return(Assembly.Load(array)); } }; Console.BackgroundColor = ConsoleColor.White; Console.ForegroundColor = ConsoleColor.DarkCyan; Console.Clear(); Console.WriteLine("OTAPI Test Launcher."); var options = new NDesk.Options.OptionSet() .Add("as:|auto-start:", x => _config.AutoStart = true); options.Parse(args); //AttachHooks(); PreStart?.Invoke(this, EventArgs.Empty); if (_config.AutoStart) { StartGame(args); } else { Menu(args); } } catch (Exception ex) { try { StackTrace st = new System.Diagnostics.StackTrace(ex); string stackTrace = ""; foreach (StackFrame frame in st.GetFrames()) { stackTrace = "at " + frame.GetMethod().Module.Name + "." + frame.GetMethod().ReflectedType.Name + "." + frame.GetMethod().Name + " (IL offset: 0x" + frame.GetILOffset().ToString("x") + ")\n" + stackTrace; } Console.Write(stackTrace); Console.WriteLine(ex); } catch { Console.Write(""); Console.WriteLine(ex); } Console.ReadKey(true); } }
public static List <EnhancedStackFrame> GetFrames(StackTrace stackTrace) { var frames = new List <EnhancedStackFrame>(); var stackFrames = stackTrace.GetFrames(); if (stackFrames == null) { return(frames); } EnhancedStackFrame?lastFrame = null; PortablePdbReader? portablePdbReader = null; try { for (var i = 0; i < stackFrames.Length; i++) { var frame = stackFrames[i]; if (frame is null) { continue; } var method = frame.GetMethod(); // Always show last stackFrame if (method != null && !ShowInStackTrace(method) && i < stackFrames.Length - 1) { continue; } var fileName = frame.GetFileName(); var row = frame.GetFileLineNumber(); var column = frame.GetFileColumnNumber(); var ilOffset = frame.GetILOffset(); if (method != null && string.IsNullOrEmpty(fileName) && ilOffset >= 0) { // .NET Framework and older versions of mono don't support portable PDBs // so we read it manually to get file name and line information (portablePdbReader ??= new PortablePdbReader()).PopulateStackFrame(frame, method, frame.GetILOffset(), out fileName, out row, out column); } if (method is null) { // Method can't be null continue; } var resolvedMethod = GetMethodDisplayString(method); if (lastFrame?.IsEquivalent(resolvedMethod, fileName, row, column) ?? false) { lastFrame.IsRecursive = true; } else { var stackFrame = new EnhancedStackFrame(frame, resolvedMethod, fileName, row, column); frames.Add(stackFrame); lastFrame = stackFrame; } } } finally { portablePdbReader?.Dispose(); } return(frames); }
public static void Log(ELogLevel level, ELogTag tag, string content, string stack) { CLogSys logSys = CGameRoot.GetGameSystem <CLogSys>(); if (logSys == null) { return; } if ((int)level < (int)logSys.mSelfLogLevel) { return; } //if (FightScene.mInstance != null && FightScene.mInstance.isBattleStart) //{ // return; //} #region 重复内容保护 string sameStr = content.Substring(0, Mathf.Min(20, content.Length)); if (string.IsNullOrEmpty(mSameLogStr) || mSameLogStr != sameStr) { mSameLogStr = sameStr; mSameLogCnt = 0; } else { mSameLogCnt++; } if (mSameLogCnt > 20) { return; } #endregion #if !UNITY_EDITOR if (string.IsNullOrEmpty(stack)) { System.Diagnostics.StackTrace stackTrace = new System.Diagnostics.StackTrace(true); System.Diagnostics.StackFrame[] stackFrames = stackTrace.GetFrames(); System.Text.StringBuilder sb = new System.Text.StringBuilder(); for (int i = 0; i < stackFrames.Length; ++i) { System.Reflection.MethodBase method = stackFrames[i].GetMethod(); string typeName = method.DeclaringType.FullName; string methodName = method.Name; if (typeName == "CLogSys" || typeName == "UnityEngine.Debug" || methodName == "CallLogCallback") { continue; } sb.AppendFormat("{0}:{1}\n", typeName, methodName); } stack = sb.ToString(); } char[] contentInLine; int contentIdx; TransInLine(content, out contentInLine, out contentIdx); char[] stackInLine; int stackIdx; TransInLine(stack, out stackInLine, out stackIdx); System.DateTime now = System.DateTime.Now; string curTime = string.Format("{0:00}{1:00}{2:00}{3:00}{4:00}", now.Month, now.Day, now.Hour, now.Minute, now.Second); string logStr = string.Format("{0}|{1}|{2}|{3}|{4}|{5}", cLogPrefix, curTime, level.ToString()[0], tag, new string(contentInLine, 0, contentIdx), new string(stackInLine, 0, stackIdx)); //ELogLevel logLevel = (ResourceSys != null && ResourceSys.RootCfg != null) ? ResourceSys.RootCfg.mLogLevel : ELogLevel.Debug; if (mLogPlatform != null) { mLogPlatform.Log(logStr); } if (level >= ELogLevel.Error) { //DCProxy.ReportError(content, logStr); } #else if (level == ELogLevel.Warning) { Debug.LogWarning(content); } else if (level == ELogLevel.Error) { Debug.LogError(content); } else if (level == ELogLevel.Fatal) { Debug.LogError(content); } else if (level == ELogLevel.Debug) { Debug.LogWarning(content); } else if (level == ELogLevel.Verbose) { Debug.Log(content); } #endif }
public static void Check() { StackTrace trace = new System.Diagnostics.StackTrace(); StackFrame[] frames = trace.GetFrames(); //find who is calling me System.Reflection.MethodBase method = frames[1].GetMethod(); DrsrTestAttribute.Site = EnvironmentConfig.TestSite; object[] attrs = method.GetCustomAttributes(false); if (attrs == null) { return; } string level = null; foreach (object o in attrs) { //for out test attribute, invoke "Do" method, for MSTEST attributes, do accordingly Type thisType = o.GetType(); switch (thisType.Name) { case "DescriptionAttribute": { EnvironmentConfig.TestSite.Log.Add(LogEntryKind.Comment, "Test description: " + typeof(DescriptionAttribute).GetProperty("Description").GetValue(o, null).ToString()); } break; case "PriorityAttribute": { EnvironmentConfig.TestSite.Log.Add(LogEntryKind.Comment, "Implementation priority of this scenario is: " + typeof(PriorityAttribute).GetProperty("Priority").GetValue(o, null).ToString()); } break; case "TestCategoryAttribute": { TestCategoryAttribute tca = o as TestCategoryAttribute; foreach (string s in tca.TestCategories) { if (s.StartsWith("Win")) { level = s; continue; } // Check if SDC, RODC exist when TestCategory contain SDC, RODC if (s.Equals("SDC")) { if (!EnvironmentConfig.MachineStore.ContainsKey(EnvironmentConfig.Machine.WritableDC2)) { EnvironmentConfig.TestSite.Assume.Fail("The test requires a Secondary writable DC in the environment. Please set the corresponding field in PTF config, or make sure the machine can be connected."); } continue; } if (s.Equals("RODC")) { if (!EnvironmentConfig.MachineStore.ContainsKey(EnvironmentConfig.Machine.RODC)) { EnvironmentConfig.TestSite.Assume.Fail("The test requires a Read-Only DC in the environment. Please set the corresponding field in PTF config, or make sure the machine can be connected."); } continue; } } } break; default: if (thisType.BaseType == typeof(DrsrTestAttribute)) { try { thisType.GetMethod("Do").Invoke(o, null); } catch (Exception e) { DrsrTestAttribute.Site.Assert.Fail(e.InnerException.Message); } } break; } } if (level == null) { throw new Exception("Test Case not set in any domain functional level category"); } FunctionLevelAttribute fl = null; switch (level) { case "Win2000": fl = new FunctionLevelAttribute(DrsrDomainFunctionLevel.DS_BEHAVIOR_WIN2000); break; case "Win2003": fl = new FunctionLevelAttribute(DrsrDomainFunctionLevel.DS_BEHAVIOR_WIN2003); break; case "Win2008": fl = new FunctionLevelAttribute(DrsrDomainFunctionLevel.DS_BEHAVIOR_WIN2008); break; case "Win2008R2": fl = new FunctionLevelAttribute(DrsrDomainFunctionLevel.DS_BEHAVIOR_WIN2008R2); break; case "Win2012": fl = new FunctionLevelAttribute(DrsrDomainFunctionLevel.DS_BEHAVIOR_WIN2012); break; case "Win2012R2": fl = new FunctionLevelAttribute(DrsrDomainFunctionLevel.DS_BEHAVIOR_WIN2012R2); break; case "WinThreshold": fl = new FunctionLevelAttribute(DrsrDomainFunctionLevel.DS_BEHAVIOR_WINTHRESHOLD); break; case "Winv1803": ADCommonServerAdapter adapter = new ADCommonServerAdapter(); adapter.Initialize(DrsrTestAttribute.Site); ServerVersion curVersion = adapter.PDCOSVersion; if (curVersion < ServerVersion.Winv1803) { DrsrTestAttribute.Site.Assert.Inconclusive("Test case expects PDCOSVersion {0} should be Equal or Greater than Winv1803", curVersion); } fl = new FunctionLevelAttribute(DrsrDomainFunctionLevel.DS_BEHAVIOR_WINTHRESHOLD); break; default: throw new Exception("Unknown domain functional level category: " + level); } fl.Do(); }
public static IList <StackFrameInfo> GetFrames(Exception exception, out AggregateException error) { var frames = new List <StackFrameInfo>(); if (exception == null) { error = default; return(frames); } using (var portablePdbReader = new PortablePdbReader()) { var needFileInfo = true; var stackTrace = new System.Diagnostics.StackTrace(exception, needFileInfo); var stackFrames = stackTrace.GetFrames(); if (stackFrames == null) { error = default; return(frames); } List <Exception> exceptions = null; for (var i = 0; i < stackFrames.Length; i++) { var frame = stackFrames[i]; var method = frame.GetMethod(); // Always show last stackFrame if (!ShowInStackTrace(method) && i < stackFrames.Length - 1) { continue; } var stackFrame = new StackFrameInfo { StackFrame = frame, FilePath = frame.GetFileName(), LineNumber = frame.GetFileLineNumber(), MethodDisplayInfo = GetMethodDisplayString(frame.GetMethod()), }; if (string.IsNullOrEmpty(stackFrame.FilePath)) { try { // .NET Framework and older versions of mono don't support portable PDBs // so we read it manually to get file name and line information portablePdbReader.PopulateStackFrame(stackFrame, method, frame.GetILOffset()); } catch (Exception ex) { if (exceptions is null) { exceptions = new List <Exception>(); } exceptions.Add(ex); } } frames.Add(stackFrame); } if (exceptions != null) { error = new AggregateException(exceptions); return(frames); } error = default; return(frames); } }
public static StackTrace Create(System.Diagnostics.StackTrace trace) => new StackTrace( trace.GetFrames()?.Select(StackFrame.Create)?.ToArray(), trace.GetCapturedTraces()?.Select(StackTrace.Create)?.ToArray());
static public void Assert(bool InCondition, string InFormat, params object[] InParameters) { if (!InCondition) { try { string failedMessage = null; if (!string.IsNullOrEmpty(InFormat)) { try { if (InParameters != null) { failedMessage = string.Format(InFormat, InParameters); } else { failedMessage = InFormat; } } catch (Exception) { } } #if UNITY_ANDROID || UNITY_IPHONE else { failedMessage = string.Format(" no assert detail, stacktrace is :{0}", Environment.StackTrace); } #endif #if UNITY_EDITOR || UNITY_STANDALONE if (failedMessage != null) { LogE("Assert failed! " + failedMessage); } else { LogE("Assert failed!"); } string msg = "Assert failed! "; if (!string.IsNullOrEmpty(failedMessage)) { msg += failedMessage; } var trace = new System.Diagnostics.StackTrace(); var frames = trace.GetFrames(); for (int i = 0; i < frames.Length; ++i) { msg += frames[i].ToString(); } try { LogE(msg); } catch (Exception) { } #else if (failedMessage != null) { var str = "Assert failed! " + failedMessage; LogW(str); } else { LogW("Assert failed!"); } #endif } catch (Exception) { } } }
internal static RenderingCollection CompleteStackTraceForCurrentApplicationPoint(string message = "", string exceptionType = "", bool fileSystemLog = true, bool htmlOut = false) { System.Diagnostics.StackTrace stackTrace = new System.Diagnostics.StackTrace(true); string fileName; string line; string column; string method; StackTraceItem stackTraceItem; StackTraceItem? errorFile = null; List <StackTraceItem> stackTraceItems = new List <StackTraceItem>(); int counter = 0; foreach (StackFrame stackItem in stackTrace.GetFrames()) { fileName = stackItem.GetFileName() ?? ""; fileName = fileName.Replace('\\', '/'); if (fileName.Length > 0) { if (fileName.IndexOf(StackTrace.SELF_FILENAME) > -1 & fileName.IndexOf(StackTrace.SELF_FILENAME) == fileName.Length - StackTrace.SELF_FILENAME.Length) { continue; } if (fileName.IndexOf(Exceptions.SELF_FILENAME) > -1 & fileName.IndexOf(Exceptions.SELF_FILENAME) == fileName.Length - Exceptions.SELF_FILENAME.Length) { continue; } if (fileName.IndexOf(Debug.SELF_FILENAME) > -1 & fileName.IndexOf(Debug.SELF_FILENAME) == fileName.Length - Debug.SELF_FILENAME.Length) { continue; } } line = stackItem.GetFileLineNumber().ToString().Trim(); column = stackItem.GetFileColumnNumber().ToString().Trim(); method = stackItem.GetMethod().ToString().Trim(); if (line.Length == 0) { line = "?"; } stackTraceItem = new StackTraceItem { File = fileName, Line = line, Column = column, Method = method }; if ( !errorFile.HasValue & fileName.Length > 0 & line != "?" ) { errorFile = stackTraceItem; } stackTraceItems.Add(stackTraceItem); counter++; } return(new RenderingCollection { ErrorFileStackTrace = errorFile, AllStackTraces = stackTraceItems, ExceptionMessage = message, ExceptionType = exceptionType.Length > 0 ? exceptionType : "", ExceptionHash = "", CausedByHash = "", CausedByMessage = "", CausedByType = "", }); }