/// <summary>Timer constructor</summary> /// <param name="isAccumulative">Is accumulating the time duration?</param> public Timer(bool isAccumulative) { previous = start; this.isAccumulative = isAccumulative; StackTraceElement[] stack = Sharpen.Thread.CurrentThread().GetStackTrace(); StackTraceElement e = stack[stack.Length - 1]; @out.WriteLine(e + " started at " + Sharpen.Extensions.CreateDate(start)); }
/// <summary> /// Creates threads dump and try to mimic JVM stack trace as much as possible to allow existing analytics tools to be used /// </summary> /// <param name="threadMxBean"> bean to use for thread dump </param> /// <param name="systemProperties"> dumped vm system properties </param> /// <returns> string that contains thread dump </returns> public static string ThreadDump(ThreadMXBean threadMxBean, Properties systemProperties) { ThreadInfo[] threadInfos = threadMxBean.dumpAllThreads(true, true); // Reproduce JVM stack trace as far as possible to allow existing analytics tools to be used string vmName = systemProperties.getProperty("java.vm.name"); string vmVersion = systemProperties.getProperty("java.vm.version"); string vmInfoString = systemProperties.getProperty("java.vm.info"); StringBuilder sb = new StringBuilder(); sb.Append(string.Format("Full thread dump {0} ({1} {2}):\n\n", vmName, vmVersion, vmInfoString)); foreach (ThreadInfo threadInfo in threadInfos) { sb.Append(string.Format("\"{0}\" #{1:D}\n", threadInfo.ThreadName, threadInfo.ThreadId)); sb.Append(" java.lang.Thread.State: ").Append(threadInfo.ThreadState).Append("\n"); StackTraceElement[] stackTrace = threadInfo.StackTrace; for (int i = 0; i < stackTrace.Length; i++) { StackTraceElement e = stackTrace[i]; sb.Append("\tat ").Append(e.ToString()).Append('\n'); // First stack element info can be found in the thread state if (i == 0 && threadInfo.LockInfo != null) { Thread.State ts = threadInfo.ThreadState; switch (ts) { case BLOCKED: sb.Append("\t- blocked on ").Append(threadInfo.LockInfo).Append('\n'); break; case WAITING: sb.Append("\t- waiting on ").Append(threadInfo.LockInfo).Append('\n'); break; case TIMED_WAITING: sb.Append("\t- waiting on ").Append(threadInfo.LockInfo).Append('\n'); break; default: break; } } foreach (MonitorInfo mi in threadInfo.LockedMonitors) { if (mi.LockedStackDepth == i) { sb.Append("\t- locked ").Append(mi).Append('\n'); } } } } return(sb.ToString()); }
public void Constructor() { var e = new StackTraceElement("className", "methodName", "fileName", 42); Assert.That(e.ClassName, Is.EqualTo("className")); Assert.That(e.MethodName, Is.EqualTo("methodName")); Assert.That(e.FileName, Is.EqualTo("fileName")); Assert.That(e.LineNumber, Is.EqualTo(42)); }
private static string generateTag(StackTraceElement caller) { string TAG = "%s.%s(L:%d)"; string callerClazzName = caller.ClassName; callerClazzName = callerClazzName.Substring(callerClazzName.LastIndexOf(".") + 1); TAG = string.Format(TAG, callerClazzName, caller.MethodName, caller.LineNumber); TAG = TextUtils.IsEmpty(customTagPrefix) ? TAG : customTagPrefix + ":" + TAG; return(TAG); }
} // MIssue /// <summary> /// Log Record Constructor /// </summary> /// <param name="record">record</param> public MIssue(LogRecord record) : this(Env.GetCtx(), 0, null) { String summary = record.message; SetSourceClassName(record.sourceClassName); SetSourceMethodName(record.sourceMethodName); SetLoggerName(record.GetLoggerName()); //Throwable t = record.getThrown(); //if (t != null) //{ //if (summary != null && summary.length() > 0) //summary = t.toString() + " " + summary; //if (summary == null || summary.length() == 0) //summary = t.toString(); // String e = record.message.ToString();// = record.message.ToString();// (Object)record.message; StringBuilder error = new StringBuilder(); StackTraceElement[] tes = null;// =(StackTraceElement[])e.StackTrace;// t.getStackTrace(); int count = 0; for (int i = 0; i < e.Length; i++) { StackTraceElement element = tes[i]; String s = element.ToString(); if (s.IndexOf("vienna") != -1) { error.Append(s).Append("\n"); if (count == 0) { String source = element.GetClassName() + "." + element.GetMethodName(); SetSourceClassName(source); SetLineNo(element.GetLineNumber()); } count++; } if (count > 5 || error.Length > 2000) { break; } } SetErrorTrace(error.ToString()); // Stack //CharArrayWriter cWriter = new CharArrayWriter(); //PrintWriter pWriter = new PrintWriter(cWriter); //t.printStackTrace(pWriter); //setStackTrace(cWriter.toString()); //if (summary == null || summary.length() == 0) //summary = "??"; //setIssueSummary(summary); SetRecord_ID(1); } // MIssue
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in .NET: //ORIGINAL LINE: private static StackTraceElement[] decodeStackTrace(DataInput input) throws IOException private static StackTraceElement[] decodeStackTrace(DataInput input) { StackTraceElement[] trace = new StackTraceElement[input.readInt()]; for (int i = 0; i < trace.Length; i++) { trace[i] = new StackTraceElement(input.readUTF(), input.readUTF(), input.readBoolean() ? input.readUTF() : null, input.readInt()); } return(trace); }
/// <summary> /// Check whether a stack trace line is part of the Android source code, or generated by Android /// source code. </summary> /// <param name="line"> stack trace line. </param> /// <returns> true if part of Android source code, false otherwise. </returns> private static bool isAndroidLine(StackTraceElement line) { foreach (string prefix in STACK_TRACE_PACKAGE_SKIP_LIST) { if (line.ClassName.startsWith(prefix + ".")) { return(true); } } return(false); }
/// <summary> /// Get crash identifier from the specified throwable. </summary> /// <param name="ex"> throwable. </param> /// <returns> crash identifier. </returns> public static EngagementCrashId from(Context context, Exception ex) { /* * Loop on causes to determine exception type to use and class/method to use for crashid * computation. The class.method used as the location of a crash (the origin of the crash) is * never considered to be an Android method, try to find an application method as being the * origin of the crash. If we don't find one, use the first method as origin. OutOfMemoryError * is special: it can happen pretty much everywhere, use no origin for this one: aggregate all * OutOfMemoryError into one crash identifier (whatever its position in the causal chain). */ //JAVA TO C# CONVERTER TODO TASK: Java wildcard generics are not converted to .NET: //ORIGINAL LINE: Class<? extends Throwable> topClassName = ex.getClass(); Type <?> topClassName = ex.GetType(); for (Exception cause = ex; cause != null; cause = cause.InnerException) { if (cause.GetType().Equals(typeof(System.OutOfMemoryException))) { return(new EngagementCrashId(typeof(System.OutOfMemoryException), null, null)); } else { foreach (StackTraceElement line in cause.StackTrace) { if (!isAndroidLine(line)) { return(new EngagementCrashId(topClassName, line)); } } } } /* * Very specific case: RuntimeException thrown by ActivityThread. There is no hint of * application code in the stack trace lines, only the message can be parsed. Keep original * method name but change ActivityThread by the application class name found in the message. */ StackTraceElement firstLine = ex.StackTrace[0]; if (ex is Exception && "android.app.ActivityThread".Equals(firstLine.ClassName)) { /* Try parsing message for class name */ Pattern pattern = Pattern.compile("\\{" + context.PackageName + "/([^\\}]+)"); Matcher matcher = pattern.matcher(ex.Message); if (matcher.find()) { return(new EngagementCrashId(topClassName, matcher.group(1), firstLine.MethodName)); } } /* Fail over first type and line if no smart origin could be found */ return(new EngagementCrashId(topClassName, firstLine)); }
/// <summary> /// Construct a <tt>MonitorInfo</tt> object. /// </summary> /// <param name="className"> the fully qualified name of the class of the lock object. </param> /// <param name="identityHashCode"> the {@link System#identityHashCode /// identity hash code} of the lock object. </param> /// <param name="stackDepth"> the depth in the stack trace where the object monitor /// was locked. </param> /// <param name="stackFrame"> the stack frame that locked the object monitor. </param> /// <exception cref="IllegalArgumentException"> if /// <tt>stackDepth</tt> ≥ 0 but <tt>stackFrame</tt> is <tt>null</tt>, /// or <tt>stackDepth</tt> < 0 but <tt>stackFrame</tt> is not /// <tt>null</tt>. </exception> public MonitorInfo(String className, int identityHashCode, int stackDepth, StackTraceElement stackFrame) : base(className, identityHashCode) { if (stackDepth >= 0 && stackFrame == null) { throw new IllegalArgumentException("Parameter stackDepth is " + stackDepth + " but stackFrame is null"); } if (stackDepth < 0 && stackFrame != null) { throw new IllegalArgumentException("Parameter stackDepth is " + stackDepth + " but stackFrame is not null"); } this.StackDepth = stackDepth; this.StackFrame = stackFrame; }
private static string ThreadRootClass() { StackTraceElement[] trace = Thread.CurrentThread().GetStackTrace(); int i = trace.Length - 1; while (i > 0 && (trace[i].GetClassName().StartsWith("com.intellij") || trace[i].GetClassName().StartsWith("java.") || trace[i].GetClassName().StartsWith("sun."))) { i -= 1; } StackTraceElement elem = trace[i]; return(elem.GetClassName()); }
/// <summary> /// Parse an incoming STKL. /// </summary> private void handleSTKL(Client client, ByteBuffer data) { StackTraceElement[] trace; int i, threadId, stackDepth; //JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes: //ORIGINAL LINE: @SuppressWarnings("unused") int future; int future; future = data.getInt(); threadId = data.getInt(); Log.v("ddms", "STKL: " + threadId); /* un-serialize the StackTraceElement[] */ stackDepth = data.getInt(); trace = new StackTraceElement[stackDepth]; for (i = 0; i < stackDepth; i++) { string className, methodName, fileName; int len, lineNumber; len = data.getInt(); className = getString(data, len); len = data.getInt(); methodName = getString(data, len); len = data.getInt(); if (len == 0) { fileName = null; } else { fileName = getString(data, len); } lineNumber = data.getInt(); trace[i] = new StackTraceElement(className, methodName, fileName, lineNumber); } ThreadInfo threadInfo = client.clientData.getThread(threadId); if (threadInfo != null) { threadInfo.stackCall = trace; client.update(Client.CHANGE_THREAD_STACKTRACE); } else { Log.d("STKL", string.Format("Got stackcall for thread {0:D}, which does not exists (anymore?).", threadId)); //$NON-NLS-1$ } }
public static void Encode(StackTraceElement stackTraceElement, ClientMessage clientMessage) { clientMessage.Set(stackTraceElement.ClassName); clientMessage.Set(stackTraceElement.MethodName); string fileName = stackTraceElement.FileName; var fileName_NotNull = fileName != null; clientMessage.Set(fileName_NotNull); if (fileName_NotNull) { clientMessage.Set(fileName); } clientMessage.Set(stackTraceElement.LineNumber); }
private void Record(Sample root, StackTraceElement[] frames) { root.AndIncrement; IDictionary <StackTraceElement, Sample> level = root.Children; // Iterate sample in reverse, since index 0 is top of the stack (most recent method invocation) and we record bottom-to-top. for (int i = frames.Length - 1; i >= 0; i--) { StackTraceElement frame = frames[i]; //JAVA TO C# CONVERTER TODO TASK: Method reference constructor syntax is not converted by Java to C# Converter: Sample sample = level.computeIfAbsent(frame, Sample::new); sample.AndIncrement; level = sample.Children; } }
public static int CalculateDataSize(StackTraceElement stackTraceElement) { var dataSize = Bits.IntSizeInBytes; dataSize += ParameterUtil.CalculateDataSize(stackTraceElement.ClassName); dataSize += ParameterUtil.CalculateDataSize(stackTraceElement.MethodName); dataSize += Bits.BooleanSizeInBytes; string fileName = stackTraceElement.FileName; var fileName_NotNull = fileName != null; if (fileName_NotNull) { dataSize += ParameterUtil.CalculateDataSize(fileName); } return(dataSize); }
/// <summary> /// Constructor of ThreadInfo created by the JVM /// for <seealso cref="ThreadMXBean#getThreadInfo(long[],boolean,boolean)"/> /// and <seealso cref="ThreadMXBean#dumpAllThreads"/> /// </summary> /// <param name="t"> Thread </param> /// <param name="state"> Thread state </param> /// <param name="lockObj"> Object on which the thread is blocked </param> /// <param name="lockOwner"> the thread holding the lock </param> /// <param name="blockedCount"> Number of times blocked to enter a lock </param> /// <param name="blockedTime"> Approx time blocked to enter a lock </param> /// <param name="waitedCount"> Number of times waited on a lock </param> /// <param name="waitedTime"> Approx time waited on a lock </param> /// <param name="stackTrace"> Thread stack trace </param> /// <param name="monitors"> List of locked monitors </param> /// <param name="stackDepths"> List of stack depths </param> /// <param name="synchronizers"> List of locked synchronizers </param> private ThreadInfo(Thread t, int state, Object lockObj, Thread lockOwner, long blockedCount, long blockedTime, long waitedCount, long waitedTime, StackTraceElement[] stackTrace, Object[] monitors, int[] stackDepths, Object[] synchronizers) { int numMonitors = (monitors == null ? 0 : monitors.Length); MonitorInfo[] lockedMonitors; if (numMonitors == 0) { lockedMonitors = EMPTY_MONITORS; } else { lockedMonitors = new MonitorInfo[numMonitors]; for (int i = 0; i < numMonitors; i++) { Object @lock = monitors[i]; //JAVA TO C# CONVERTER WARNING: The .NET Type.FullName property will not always yield results identical to the Java Class.getName method: String className = @lock.GetType().FullName; int identityHashCode = System.identityHashCode(@lock); int depth = stackDepths[i]; StackTraceElement ste = (depth >= 0 ? stackTrace[depth] : null); lockedMonitors[i] = new MonitorInfo(className, identityHashCode, depth, ste); } } int numSyncs = (synchronizers == null ? 0 : synchronizers.Length); LockInfo[] lockedSynchronizers; if (numSyncs == 0) { lockedSynchronizers = EMPTY_SYNCS; } else { lockedSynchronizers = new LockInfo[numSyncs]; for (int i = 0; i < numSyncs; i++) { Object @lock = synchronizers[i]; //JAVA TO C# CONVERTER WARNING: The .NET Type.FullName property will not always yield results identical to the Java Class.getName method: String className = @lock.GetType().FullName; int identityHashCode = System.identityHashCode(@lock); lockedSynchronizers[i] = new LockInfo(className, identityHashCode); } } Initialize(t, state, lockObj, lockOwner, blockedCount, blockedTime, waitedCount, waitedTime, stackTrace, lockedMonitors, lockedSynchronizers); }
private static bool AwaitParked(ThreadRepository.ThreadInfo thread, long timeout, TimeUnit unit) { bool parked = false; for (long end = DateTimeHelper.CurrentUnixTimeMillis() + unit.toMillis(timeout); DateTimeHelper.CurrentUnixTimeMillis() < end;) { StackTraceElement frame = thread.StackTrace[0]; if ("park".Equals(frame.MethodName) && frame.ClassName.EndsWith("Unsafe")) { if (thread.State.name().EndsWith("WAITING")) { parked = true; break; } } } return(parked); }
// Private method to infer the caller's class and method names private void InferCaller() { NeedToInferCaller = false; JavaLangAccess access = SharedSecrets.JavaLangAccess; Throwable throwable = new Throwable(); int depth = access.getStackTraceDepth(throwable); bool lookingForLogger = true; for (int ix = 0; ix < depth; ix++) { // Calling getStackTraceElement directly prevents the VM // from paying the cost of building the entire stack frame. StackTraceElement frame = access.getStackTraceElement(throwable, ix); String cname = frame.ClassName; bool isLoggerImpl = IsLoggerImplFrame(cname); if (lookingForLogger) { // Skip all frames until we have found the first logger frame. if (isLoggerImpl) { lookingForLogger = false; } } else { if (!isLoggerImpl) { // skip reflection call if (!cname.StartsWith("java.lang.reflect.") && !cname.StartsWith("sun.reflect.")) { // We've found the relevant frame. SourceClassName = cname; SourceMethodName = frame.MethodName; return; } } } } // We haven't found a suitable frame, so just punt. This is // OK as we are only committed to making a "best effort" here. }
private void logTrace(string dbkey, StackTraceElement[] elements) { if (elements == null || elements.Length == 0) { return; } foreach (StackTraceElement ste in elements) { if (ste.ClassName.IndexOf("service.impl") > 0) { log.debug("no transaction data source Key[" + dbkey + "," + ste.ClassName + "." + ste.MethodName + ",line number:" + ste.LineNumber + "]"); return; } } foreach (StackTraceElement ste in elements) { log.debug("no transaction data source Key[" + dbkey + "," + ste.ClassName + "." + ste.MethodName + ",line number:" + ste.LineNumber + "]"); } return; }
private static void PrintThreadInfo(ThreadInfo ti, PrintWriter @out) { // print thread information PrintThread(ti, @out); // print stack trace with locks StackTraceElement[] stacktrace = ti.GetStackTrace(); MonitorInfo[] monitors = ti.GetLockedMonitors(); for (int i = 0; i < stacktrace.Length; i++) { StackTraceElement ste = stacktrace[i]; @out.WriteLine(Indent + "at " + ste.ToString()); foreach (MonitorInfo mi in monitors) { if (mi.GetLockedStackDepth() == i) { @out.WriteLine(Indent + " - locked " + mi); } } } @out.WriteLine(); }
/// <summary> /// Returns a <tt>MonitorInfo</tt> object represented by the /// given <tt>CompositeData</tt>. /// The given <tt>CompositeData</tt> must contain the following attributes /// as well as the attributes specified in the /// <a href="LockInfo.html#MappedType"> /// mapped type</a> for the <seealso cref="LockInfo"/> class: /// <blockquote> /// <table border summary="The attributes and their types the given CompositeData contains"> /// <tr> /// <th align=left>Attribute Name</th> /// <th align=left>Type</th> /// </tr> /// <tr> /// <td>lockedStackFrame</td> /// <td><tt>CompositeData as specified in the /// <a href="ThreadInfo.html#StackTrace">stackTrace</a> /// attribute defined in the {@link ThreadInfo#from /// ThreadInfo.from} method. /// </tt></td> /// </tr> /// <tr> /// <td>lockedStackDepth</td> /// <td><tt>java.lang.Integer</tt></td> /// </tr> /// </table> /// </blockquote> /// </summary> /// <param name="cd"> <tt>CompositeData</tt> representing a <tt>MonitorInfo</tt> /// </param> /// <exception cref="IllegalArgumentException"> if <tt>cd</tt> does not /// represent a <tt>MonitorInfo</tt> with the attributes described /// above. /// </exception> /// <returns> a <tt>MonitorInfo</tt> object represented /// by <tt>cd</tt> if <tt>cd</tt> is not <tt>null</tt>; /// <tt>null</tt> otherwise. </returns> public static MonitorInfo From(CompositeData cd) { if (cd == null) { return(null); } if (cd is MonitorInfoCompositeData) { return(((MonitorInfoCompositeData)cd).MonitorInfo); } else { MonitorInfoCompositeData.validateCompositeData(cd); String className = MonitorInfoCompositeData.getClassName(cd); int identityHashCode = MonitorInfoCompositeData.getIdentityHashCode(cd); int stackDepth = MonitorInfoCompositeData.getLockedStackDepth(cd); StackTraceElement stackFrame = MonitorInfoCompositeData.getLockedStackFrame(cd); return(new MonitorInfo(className, identityHashCode, stackDepth, stackFrame)); } }
public async Task ExecuteAsync(string invokedExecutableName, string[] parameters, ExecutionEnvironment env) { Log.Debug("Execute: ", ExecutableName, " ", parameters.ToJson(inline: true)); Output.PipeTo(env.Output); Error.PipeTo(env.Error); env.Input.PipeTo(Input); this.invokedExecutableName = invokedExecutableName; this.parameters = parameters.ToList(); this.state = new ExecutionState(); this.env = env; ResetInternalState(); if (UseOptions) { parseOptions(); } // need help ? if (printHelp) { printOptions(); return; } // execute the command else { await ExecuteInternalAsync(); } StackTraceElement element = new StackTraceElement { Executable = ExecutableName, Parameters = parameters, State = state }; env.StackTrace.Add(element); }
public void Equality() { var e = new StackTraceElement("className", "methodName", "fileName", 42); #pragma warning disable CS1718 // Comparison made to same variable // ReSharper disable EqualExpressionComparison // ReSharper disable ConditionIsAlwaysTrueOrFalse Assert.That(e.Equals(null), Is.False); Assert.That(e.Equals(e), Is.True); Assert.That(e.Equals(new StackTraceElement("className", "methodName", "fileName", 42)), Is.True); Assert.That(e == e, Is.True); Assert.That(e == null, Is.False); Assert.That(e == new StackTraceElement("className", "methodName", "fileName", 42), Is.True); Assert.That(e != new StackTraceElement("classNamX", "methodName", "fileName", 42), Is.True); Assert.That(e.GetHashCode(), Is.Not.Zero); // ReSharper restore EqualExpressionComparison // ReSharper restore ConditionIsAlwaysTrueOrFalse #pragma warning restore CS1718 // Comparison made to same variable }
public MonitorInfo(String arg0, int arg1, int arg2, StackTraceElement arg3) : base(ProxyCtor.I) { Instance.CallConstructor("(Ljava/lang/String;IILjava/lang/StackTraceElement;)V", arg0, arg1, arg2, arg3); }
/// <summary> /// Format the given message to XML. /// <para> /// This method can be overridden in a subclass. /// It is recommended to use the <seealso cref="Formatter#formatMessage"/> /// convenience method to localize and format the message field. /// /// </para> /// </summary> /// <param name="record"> the log record to be formatted. </param> /// <returns> a formatted log record </returns> public override String Format(LogRecord record) { StringBuilder sb = new StringBuilder(500); sb.Append("<record>\n"); sb.Append(" <date>"); AppendISO8601(sb, record.Millis); sb.Append("</date>\n"); sb.Append(" <millis>"); sb.Append(record.Millis); sb.Append("</millis>\n"); sb.Append(" <sequence>"); sb.Append(record.SequenceNumber); sb.Append("</sequence>\n"); String name = record.LoggerName; if (name != null) { sb.Append(" <logger>"); Escape(sb, name); sb.Append("</logger>\n"); } sb.Append(" <level>"); Escape(sb, record.Level.ToString()); sb.Append("</level>\n"); if (record.SourceClassName != null) { sb.Append(" <class>"); Escape(sb, record.SourceClassName); sb.Append("</class>\n"); } if (record.SourceMethodName != null) { sb.Append(" <method>"); Escape(sb, record.SourceMethodName); sb.Append("</method>\n"); } sb.Append(" <thread>"); sb.Append(record.ThreadID); sb.Append("</thread>\n"); if (record.Message != null) { // Format the message string and its accompanying parameters. String message = formatMessage(record); sb.Append(" <message>"); Escape(sb, message); sb.Append("</message>"); sb.Append("\n"); } // If the message is being localized, output the key, resource // bundle name, and params. ResourceBundle bundle = record.ResourceBundle; try { if (bundle != null && bundle.GetString(record.Message) != null) { sb.Append(" <key>"); Escape(sb, record.Message); sb.Append("</key>\n"); sb.Append(" <catalog>"); Escape(sb, record.ResourceBundleName); sb.Append("</catalog>\n"); } } catch (Exception) { // The message is not in the catalog. Drop through. } Object[] parameters = record.Parameters; // Check to see if the parameter was not a messagetext format // or was not null or empty if (parameters != null && parameters.Length != 0 && record.Message.IndexOf("{") == -1) { for (int i = 0; i < parameters.Length; i++) { sb.Append(" <param>"); try { Escape(sb, parameters[i].ToString()); } catch (Exception) { sb.Append("???"); } sb.Append("</param>\n"); } } if (record.Thrown != null) { // Report on the state of the throwable. Throwable th = record.Thrown; sb.Append(" <exception>\n"); sb.Append(" <message>"); Escape(sb, th.ToString()); sb.Append("</message>\n"); StackTraceElement[] trace = th.StackTrace; for (int i = 0; i < trace.Length; i++) { StackTraceElement frame = trace[i]; sb.Append(" <frame>\n"); sb.Append(" <class>"); Escape(sb, frame.ClassName); sb.Append("</class>\n"); sb.Append(" <method>"); Escape(sb, frame.MethodName); sb.Append("</method>\n"); // Check for a line number. if (frame.LineNumber >= 0) { sb.Append(" <line>"); sb.Append(frame.LineNumber); sb.Append("</line>\n"); } sb.Append(" </frame>\n"); } sb.Append(" </exception>\n"); } sb.Append("</record>\n"); return(sb.ToString()); }
protected bool Equals(StackTraceElement other) { return(string.Equals(ClassName, other.ClassName) && string.Equals(MethodName, other.MethodName) && string.Equals(FileName, other.FileName) && LineNumber == other.LineNumber); }
/// <summary> /// <inheritDoc/> /// /// </summary> public override IList <Redwood.Record> Handle(Redwood.Record record) { StringBuilder b = new StringBuilder(1024); //--Special case for Exceptions string[] content; if (record.content is Exception) { //(vars) IList <string> lines = new List <string>(); //(root message) Exception exception = (Exception)record.content; lines.Add(record.content.ToString()); StackTraceElement[] trace = exception.GetStackTrace(); StackTraceElement topTraceElement = trace.Length > 0 ? trace[0] : null; foreach (StackTraceElement e in exception.GetStackTrace()) { lines.Add(tab + e.ToString()); } //(causes) while (exception.InnerException != null) { System.Console.Out.WriteLine("TOP ELEMENT: " + topTraceElement); //((variables)) exception = exception.InnerException; trace = exception.GetStackTrace(); lines.Add("Caused by: " + exception.GetType() + ": " + exception.Message); for (int i = 0; i < trace.Length; i++) { //((add trace element)) StackTraceElement e_1 = trace[i]; lines.Add(tab + e_1.ToString()); //((don't print redundant elements)) if (topTraceElement != null && e_1.GetClassName().Equals(topTraceElement.GetClassName()) && e_1.GetMethodName().Equals(topTraceElement.GetMethodName())) { lines.Add(tab + "..." + (trace.Length - i - 1) + " more"); break; } } //((update top element)) topTraceElement = trace.Length > 0 ? trace[0] : null; } //(set content array) content = new string[lines.Count]; content = Sharpen.Collections.ToArray(lines, content); } else { if (record.content == null) { content = new string[] { "null" }; } else { string toStr; if (record.content is ISupplier) { //noinspection unchecked toStr = ((ISupplier <object>)record.content).Get().ToString(); } else { toStr = record.content.ToString(); } if (toStr == null) { content = new string[] { "<null toString()>" }; } else { content = toStr.Split("\n"); } } } //would be nice to get rid of this 'split()' call at some point //--Handle Tracks UpdateTracks(record.depth); if (this.missingOpenBracket) { this.Style(b, "{\n", trackColor, trackStyle); this.missingOpenBracket = false; } //--Process Record //(variables) int cursorPos = 0; int contentLinesPrinted = 0; //(loop) Color color = Color.None; Edu.Stanford.Nlp.Util.Logging.Style style = Edu.Stanford.Nlp.Util.Logging.Style.None; //(get channels) List <object> printableChannels = new List <object>(); foreach (object chan in record.Channels()) { if (chan is Color) { color = (Color)chan; } else { if (chan is Edu.Stanford.Nlp.Util.Logging.Style) { style = (Edu.Stanford.Nlp.Util.Logging.Style)chan; } else { if (chan != Redwood.Force) { printableChannels.Add(chan); } } } } //--Write Channels if (leftMargin > 2) { //don't print if not enough space //((print channels) b.Append("["); cursorPos += 1; object lastChan = null; bool wasAnyChannelPrinted = false; for (int i = 0; i < printableChannels.Count; i++) { object chan_1 = printableChannels[i]; if (chan_1.Equals(lastChan)) { continue; } //skip duplicate channels lastChan = chan_1; //(get channel) string toPrint = chan_1.ToString(); if (toPrint.Length > leftMargin - 1) { toPrint = Sharpen.Runtime.Substring(toPrint, 0, leftMargin - 2); } if (cursorPos + toPrint.Length >= leftMargin) { //(case: doesn't fit) while (cursorPos < leftMargin) { b.Append(" "); cursorPos += 1; } if (contentLinesPrinted < content.Length) { WriteContent(record.depth, Style(new StringBuilder(), content[contentLinesPrinted], color, style).ToString(), b); contentLinesPrinted += 1; } b.Append("\n "); cursorPos = 1; } //(print flag) bool wasChannelPrinted = FormatChannel(b, toPrint, chan_1); wasAnyChannelPrinted = wasAnyChannelPrinted || wasChannelPrinted; if (wasChannelPrinted && i < printableChannels.Count - 1) { b.Append(channelSeparatorChar); cursorPos += 1; } cursorPos += toPrint.Length; } if (wasAnyChannelPrinted) { b.Append("]"); cursorPos += 1; } else { b.Length = b.Length - 1; // remove leading "[" cursorPos -= 1; } } //--Content //(write content) while (contentLinesPrinted < content.Length) { while (cursorPos < leftMargin) { b.Append(" "); cursorPos += 1; } WriteContent(record.depth, Style(new StringBuilder(), content[contentLinesPrinted], color, style).ToString(), b); contentLinesPrinted += 1; if (contentLinesPrinted < content.Length) { b.Append("\n"); cursorPos = 0; } } //(print) if (b.Length == 0 || b[b.Length - 1] != '\n') { b.Append("\n"); } Print(record.Channels(), b.ToString()); //--Continue if (info != null) { info.numElementsPrinted += 1; } List <Redwood.Record> rtn = new List <Redwood.Record>(); rtn.Add(record); return(rtn); }
protected bool Equals(StackTraceElement other) { return string.Equals(ClassName, other.ClassName) && string.Equals(MethodName, other.MethodName) && string.Equals(FileName, other.FileName) && LineNumber == other.LineNumber; }
public void ToStringOverride() { var e = new StackTraceElement("className", "methodName", "fileName", 42); Assert.That(e.ToString(), Is.EqualTo("at className.methodName(...) in fileName:42")); }
internal Sample(StackTraceElement stackTraceElement) { this.StackTraceElement = stackTraceElement; Children = new ConcurrentDictionary <StackTraceElement, Sample>(); }
/* * Handle a REcent ALlocation response. * * Message header (all values big-endian): * (1b) message header len (to allow future expansion); includes itself * (1b) entry header len * (1b) stack frame len * (2b) number of entries * (4b) offset to string table from start of message * (2b) number of class name strings * (2b) number of method name strings * (2b) number of source file name strings * For each entry: * (4b) total allocation size * (2b) threadId * (2b) allocated object's class name index * (1b) stack depth * For each stack frame: * (2b) method's class name * (2b) method name * (2b) method source file * (2b) line number, clipped to 32767; -2 if native; -1 if no source * (xb) class name strings * (xb) method name strings * (xb) source file strings * * As with other DDM traffic, strings are sent as a 4-byte length * followed by UTF-16 data. */ private void handleREAL(Client client, ByteBuffer data) { Log.e("ddm-heap", "*** Received " + name(CHUNK_REAL)); int messageHdrLen, entryHdrLen, stackFrameLen; int numEntries, offsetToStrings; int numClassNames, numMethodNames, numFileNames; /* * Read the header. */ messageHdrLen = (data.get() & 0xff); entryHdrLen = (data.get() & 0xff); stackFrameLen = (data.get() & 0xff); numEntries = (data.getShort() & 0xffff); offsetToStrings = data.getInt(); numClassNames = (data.getShort() & 0xffff); numMethodNames = (data.getShort() & 0xffff); numFileNames = (data.getShort() & 0xffff); /* * Skip forward to the strings and read them. */ data.position = offsetToStrings; string[] classNames = new string[numClassNames]; string[] methodNames = new string[numMethodNames]; string[] fileNames = new string[numFileNames]; readStringTable(data, classNames); readStringTable(data, methodNames); //System.out.println("METHODS: " // + java.util.Arrays.deepToString(methodNames)); readStringTable(data, fileNames); /* * Skip back to a point just past the header and start reading * entries. */ data.position = messageHdrLen; List <AllocationInfo> list = new List <AllocationInfo>(numEntries); int allocNumber = numEntries; // order value for the entry. This is sent in reverse order. for (int i = 0; i < numEntries; i++) { int totalSize; int threadId, classNameIndex, stackDepth; totalSize = data.getInt(); threadId = (data.getShort() & 0xffff); classNameIndex = (data.getShort() & 0xffff); stackDepth = (data.get() & 0xff); /* we've consumed 9 bytes; gobble up any extra */ for (int skip = 9; skip < entryHdrLen; skip++) { data.get(); } StackTraceElement[] steArray = new StackTraceElement[stackDepth]; /* * Pull out the stack trace. */ for (int sti = 0; sti < stackDepth; sti++) { int methodClassNameIndex, methodNameIndex; int methodSourceFileIndex; short lineNumber; string methodClassName, methodName, methodSourceFile; methodClassNameIndex = (data.getShort() & 0xffff); methodNameIndex = (data.getShort() & 0xffff); methodSourceFileIndex = (data.getShort() & 0xffff); lineNumber = data.getShort(); methodClassName = classNames[methodClassNameIndex]; methodName = methodNames[methodNameIndex]; methodSourceFile = fileNames[methodSourceFileIndex]; steArray[sti] = new StackTraceElement(methodClassName, methodName, methodSourceFile, lineNumber); /* we've consumed 8 bytes; gobble up any extra */ for (int skip = 9; skip < stackFrameLen; skip++) { data.get(); } } list.Add(new AllocationInfo(allocNumber--, classNames[classNameIndex], totalSize, (short)threadId, steArray)); } client.clientData.allocations = list.ToArray(); client.update(Client.CHANGE_HEAP_ALLOCATIONS); }
/// <summary> /// Check whether a stack trace line is part of the Android source code, or generated by Android /// source code. </summary> /// <param name="line"> stack trace line. </param> /// <returns> true if part of Android source code, false otherwise. </returns> private static bool isAndroidLine(StackTraceElement line) { foreach (string prefix in STACK_TRACE_PACKAGE_SKIP_LIST) { if (line.ClassName.startsWith(prefix + ".")) { return true; } } return false; }
/// <summary> /// Init crash identifier. </summary> /// <param name="type"> crash type. </param> /// <param name="location"> crash location (origin of the crash in the stack trace). </param> private EngagementCrashId(Type type, StackTraceElement location) : this(type, location.ClassName, location.MethodName) { }
/// <summary> /// Record an application exception, along with a message. /// </summary> /// <param name="message">The message to record along with the exception.</param> /// <param name="exception">The exception to record.</param> public static void LogError(string message, System.Exception exception) { #if __IOS__ NativeFlurry.LogError( string.Format(exception.GetType().FullName, message), exception.ToString(), new NSException (exception.GetType().FullName, exception.Message, null)); #elif __ANDROID__ Java.Lang.Exception javaEx = new Java.Lang.Exception(exception.Message); StackTrace stackTrace = new StackTrace(exception, true); StackTraceElement[] trace = new StackTraceElement[stackTrace.FrameCount]; for (int index = 0; index < stackTrace.FrameCount; ++index) { StackFrame frame = stackTrace.GetFrame(index); trace[index] = new StackTraceElement(frame.GetMethod().DeclaringType.Name, frame.GetMethod().Name, frame.GetFileName(), frame.GetFileLineNumber()); } javaEx.SetStackTrace(trace); NativeFlurry.OnError( string.Format(exception.GetType().FullName, message), exception.ToString(), javaEx); #elif WINDOWS_PHONE NativeFlurry.LogError(message, exception); #endif }
/// <summary> /// Init crash identifier. </summary> /// <param name="type"> crash type. </param> /// <param name="location"> crash location (origin of the crash in the stack trace). </param> private EngagementCrashId(Type type, StackTraceElement location) : this(type, location.ClassName, location.MethodName) { }
/// <summary> /// Returns a string representation of this thread info. /// The format of this string depends on the implementation. /// The returned string will typically include /// the <seealso cref="#getThreadName thread name"/>, /// the <seealso cref="#getThreadId thread ID"/>, /// its <seealso cref="#getThreadState state"/>, /// and a <seealso cref="#getStackTrace stack trace"/> if any. /// </summary> /// <returns> a string representation of this thread info. </returns> public override String ToString() { StringBuilder sb = new StringBuilder("\"" + ThreadName + "\"" + " Id=" + ThreadId + " " + ThreadState); if (LockName != null) { sb.Append(" on " + LockName); } if (LockOwnerName != null) { sb.Append(" owned by \"" + LockOwnerName + "\" Id=" + LockOwnerId); } if (Suspended) { sb.Append(" (suspended)"); } if (InNative) { sb.Append(" (in native)"); } sb.Append('\n'); int i = 0; for (; i < StackTrace_Renamed.Length && i < MAX_FRAMES; i++) { StackTraceElement ste = StackTrace_Renamed[i]; sb.Append("\tat " + ste.ToString()); sb.Append('\n'); if (i == 0 && LockInfo != null) { Thread.State ts = ThreadState; switch (ts.InnerEnumValue()) { case Thread.State.InnerEnum.BLOCKED: sb.Append("\t- blocked on " + LockInfo); sb.Append('\n'); break; case Thread.State.InnerEnum.WAITING: sb.Append("\t- waiting on " + LockInfo); sb.Append('\n'); break; case Thread.State.InnerEnum.TIMED_WAITING: sb.Append("\t- waiting on " + LockInfo); sb.Append('\n'); break; default: break; } } foreach (MonitorInfo mi in LockedMonitors_Renamed) { if (mi.LockedStackDepth == i) { sb.Append("\t- locked " + mi); sb.Append('\n'); } } } if (i < StackTrace_Renamed.Length) { sb.Append("\t..."); sb.Append('\n'); } LockInfo[] locks = LockedSynchronizers; if (locks.Length > 0) { sb.Append("\n\tNumber of locked synchronizers = " + locks.Length); sb.Append('\n'); foreach (LockInfo li in locks) { sb.Append("\t- " + li); sb.Append('\n'); } } sb.Append('\n'); return(sb.ToString()); }