//Can only be called inside a service public static void PromoteException(Exception error,MessageVersion version,ref Message fault) { StackFrame frame = new StackFrame(1); Type serviceType = frame.GetMethod().ReflectedType; PromoteException(serviceType,error,version,ref fault); }
private static void LogMessage(string tag, int stackIndex, string arguments, string message) { #if DEBUG var frame = new System.Diagnostics.StackFrame(stackIndex, true); var thread = System.Threading.Thread.CurrentThread; var threadInfo = "<" + thread.ManagedThreadId.ToString("000") + (string.IsNullOrEmpty(thread.Name) ? "" : ("=" + thread.Name)) + ">"; #if GG_PLATFORM_IOS var dateInfo = ""; #else var dateInfo = "[" + DateTime.Now.ToString("HH:mm:ss,fff") + "]"; #endif var backrefInfo = new string(' ', 32) + " in " + frame.GetFileName() + ":" + frame.GetFileLineNumber(); var methodInfo = frame.GetMethod().ReflectedType.Name + "." + frame.GetMethod().Name + "(" + arguments + ")"; var msg = threadInfo + " " + dateInfo + " " + methodInfo + " " + message + " " + backrefInfo; #if GG_PLATFORM_ANDROID Android.Util.Log.Debug(tag, msg); #elif GG_PLATFORM_IOS Console.WriteLine(tag + " " + msg); #else Debug.WriteLine(tag + " " + msg); #endif #endif // DEBUG }
// Constructors // Methods public void Trace(string message, bool addStackFrame = true) { try { if (_DebugMode) { string msg = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff") + ": "; if (addStackFrame) { System.Diagnostics.StackFrame stackframe = new System.Diagnostics.StackFrame(1); msg += stackframe.GetMethod().ReflectedType.FullName + "." + stackframe.GetMethod().Name + " - "; } msg += message; if (message == "") { msg = System.Environment.NewLine + msg; } if (string.IsNullOrEmpty(_DebugLocation)) { _DebugLocation = Path.GetTempPath(); } StreamWriter tw = new StreamWriter(_DebugLocation + "\\\\iApplications.log", true); tw.WriteLine(msg); tw.Close(); } } catch (Exception ex) { ErrHandle(ex, false); } }
internal void AppendCall(int index) { SecurityCallFrame call = new SecurityCallFrame(); m_StackFrames.Add(call); StackFrame frame = new StackFrame(index); call.CallerType = frame.GetMethod().DeclaringType.ToString(); call.Operation = frame.GetMethod().Name + "()"; if(Count == 1) { call.Address = Environment.MachineName; call.Authentication = Thread.CurrentPrincipal.Identity.AuthenticationType; call.ActivityId = Guid.NewGuid(); call.IdentityName = Thread.CurrentPrincipal.Identity.Name; if(call.IdentityName == String.Empty) { call.IdentityName =WindowsIdentity.GetCurrent().Name; } call.Operation = frame.GetMethod().Name + "()"; } else //Must be in a service already { //Add local information for this service call.Address = OperationContext.Current.Channel.LocalAddress.Uri.ToString(); call.Authentication = ServiceSecurityContext.Current.PrimaryIdentity.AuthenticationType; call.IdentityName = Thread.CurrentPrincipal.Identity.Name; call.ActivityId = m_StackFrames[Count-2].ActivityId; } }
/// <summary> /// 指定されたクラスのStackFrameを取得する。 /// </summary> /// <returns>StackFrame</returns> public static List<StackFrame> Find(Type type) { List<StackFrame> list = new List<StackFrame>(); string className = type.FullName; for (int i = 0; i < MAX; i++) { StackFrame stackFrame = new StackFrame(i, true); if (stackFrame.GetMethod() == null) { break; } string stackFrameClassName = stackFrame.GetMethod().ReflectedType.FullName; if (stackFrameClassName.Equals(className)) { list.Add(stackFrame); } else if(list.Count > 0) { break; } } if (list.Count == 0) { throw new InvalidOperationException("cannot find a StackFrame of " + type.FullName); } return list; }
public void reflectiontest1() { System.Diagnostics.StackFrame stackFrame = new System.Diagnostics.StackFrame(); System.Reflection.MethodBase methodBase = stackFrame.GetMethod(); Console.WriteLine(methodBase.Name); // Displays "WhatsmyName" try { throw new Exception(); } catch { System.Diagnostics.StackFrame stackFrameex = new System.Diagnostics.StackFrame(); System.Reflection.MethodBase methodBaseex = stackFrame.GetMethod(); Console.WriteLine(methodBaseex.Name); // Displays "WhatsmyName" } try { Program pe = new Program(); pe.reflectiontest2();// } catch { System.Diagnostics.StackFrame stackFrameex = new System.Diagnostics.StackFrame(); System.Reflection.MethodBase methodBaseex = stackFrame.GetMethod(); Console.WriteLine(methodBaseex.Name); // Displays "WhatsmyName" StackTrace stackTracep = new StackTrace(); StackFrame stackFramep = stackTracep.GetFrame(1); MethodBase methodBasep = stackFrame.GetMethod(); // Displays "WhatsmyName" Console.WriteLine(" Parent Method Name {0} ", methodBasep.Name); } }
public static void Registrar(string mensagem) { var fullName = ""; var stackFrame = new StackFrame(1); Type declaringType = stackFrame.GetMethod().DeclaringType; if (declaringType != null) { fullName += declaringType.FullName; } fullName += "." + stackFrame.GetMethod().Name + "()"; var log = new StringBuilder(); log.AppendLine("++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++"); log.AppendLine(DateTime.Now.ToString("dd/MM/yyyy - HH:mm:ss")); log.AppendLine(fullName); log.AppendLine(mensagem); log.AppendLine("++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++"); string dir = ConfigurationManager.AppSettings["logPath"]; string fileName = string.Format("log_" + DateTime.Now.Year + "_" + DateTime.Now.Month.ToString(CultureInfo.InvariantCulture).PadLeft(2, '0') + ".avlog"); string path = Path.Combine(dir, fileName); if (!Directory.Exists(dir)) { Directory.CreateDirectory(dir); } var writer = new StreamWriter(path, true); writer.Write(log); writer.Close(); }
public static int Main () { MethodBase myMethodBase = MethodBase.GetCurrentMethod (); MethodBase inlinedMethodBase = InlinedMethods.GetCurrentMethod (); Assembly myExecutingAssembly = Assembly.GetExecutingAssembly (); Assembly inlinedExecutingAssembly = InlinedMethods.GetExecutingAssembly (); Assembly myCallingAssembly = Assembly.GetCallingAssembly (); Assembly inlinedCallingAssembly = InlinedMethods.CallCallingAssembly (); StackFrame myStackFrame = new StackFrame (); StackFrame inlinedStackFrame = InlinedMethods.GetStackFrame (); string myConstructorCalledFrom = new CallingAssemblyDependant ().CalledFrom; string inlinedConstructorCalledFrom = CallingAssemblyDependant.CalledFromLibrary (); StaticFlag.Flag = true; bool strictFlag = ResourceStrictFieldInit.Single.Flag; bool relaxedFlag = ResourceRelaxedFieldInit.Single.Flag; Console.WriteLine ("[{0}]CurrentMethod: my {1}, inlined {2}, equals {3}", TestFailed (myMethodBase == inlinedMethodBase), myMethodBase.Name, inlinedMethodBase.Name, myMethodBase == inlinedMethodBase); Console.WriteLine ("[{0}]ExecutingAssembly: my {1}, inlined {2}, equals {3}", TestFailed (myExecutingAssembly == inlinedExecutingAssembly), myExecutingAssembly.GetName ().Name, inlinedExecutingAssembly.GetName ().Name, myExecutingAssembly == inlinedExecutingAssembly); Console.WriteLine ("[{0}]CallingAssembly: my {1}, inlined {2}, equals {3}", TestFailed (myCallingAssembly == inlinedCallingAssembly), myCallingAssembly.GetName ().Name, inlinedCallingAssembly.GetName ().Name, myCallingAssembly == inlinedCallingAssembly); Console.WriteLine ("[{0}]StackFrame.GetMethod: my {1}, inlined {2}, equals {3}", TestFailed (myStackFrame.GetMethod ().Name == inlinedStackFrame.GetMethod ().Name), myStackFrame.GetMethod ().Name, inlinedStackFrame.GetMethod ().Name, myStackFrame.GetMethod ().Name == inlinedStackFrame.GetMethod ().Name); Console.WriteLine ("[{0}]ConstructorCalledFrom: my {1}, inlined {2}, equals {3}", TestFailed (myConstructorCalledFrom == inlinedConstructorCalledFrom), myConstructorCalledFrom, inlinedConstructorCalledFrom, myConstructorCalledFrom == inlinedConstructorCalledFrom); Console.WriteLine ("[{0}]strictFlag: {1}, relaxedFlag: {2}", TestFailed ((strictFlag != relaxedFlag)), strictFlag, relaxedFlag); if ((myMethodBase != inlinedMethodBase) && (myExecutingAssembly != inlinedExecutingAssembly) && (myCallingAssembly != inlinedCallingAssembly) && (myStackFrame.GetMethod ().Name != inlinedStackFrame.GetMethod ().Name) && (myConstructorCalledFrom != inlinedConstructorCalledFrom) && (strictFlag == relaxedFlag)) { return 0; } else { return 1; } }
public ILogger GetLogger() { StackFrame frame = new StackFrame(1, false); Type t = frame.GetMethod() == null ? GetType() : frame.GetMethod().DeclaringType; return GetLogger(t); }
/// <summary>Prints a formatted message to the debug console.</summary> /// <param name="obj">The source object.</param> /// <param name="args">Comma separated list of items to print.</param> public static void DebugLog( this object obj, params object[] args) { string str = args.Aggregate<object, string>("", (string a, object b) => {return a + b.ToString(); }); StackFrame sf = new StackFrame(1); string src = sf.GetMethod().DeclaringType.Name + "(" + sf.GetMethod().Name + ")"; Debug.Print(string.Format("{0}: {1}", src, str)); }
// get current method name public static string current() { System.Diagnostics.StackFrame stackframe = new System.Diagnostics.StackFrame(1, true); return stackframe.GetMethod().ReflectedType.Name + "." + stackframe.GetMethod().Name ; }
/// <summary> /// Get the caller identity from the stacktrace /// </summary> /// <param name="skipFrames">The level of stack frame to skip</param> /// <returns>The caller function</returns> private static string GetCallerIdentity(int skipFrames) { var frame = new StackFrame(skipFrames, true); if (null != frame.GetMethod() && null != frame.GetMethod().DeclaringType) { return string.Format("{0}.{1}", frame.GetMethod().DeclaringType.Name, frame.GetMethod().Name); } return string.Empty; }
public void ErrHandle(Exception ex, bool writeTrace = true) { if (writeTrace) { System.Diagnostics.StackFrame stackframe = new System.Diagnostics.StackFrame(1); string msg = stackframe.GetMethod().ReflectedType.FullName + "." + stackframe.GetMethod().Name + " - " + ex.Message; Trace(_Err + msg, false); /// ToDo: Do something else? } }
private static string FormatMessage( System.Diagnostics.StackTrace trace, string text, params object[] args) { System.Diagnostics.StackFrame frame = trace.GetFrame(1); string className = frame.GetMethod().ReflectedType.FullName; string methodName = frame.GetMethod().Name; string message = String.Format( "{0}/{1}: {2}", className, methodName, text); return(String.Format(message, args)); }
public void LogMsg(string message, params object[] args) { StackFrame stackFrame = new StackFrame(1); DateTime timestamp = DateTime.Now.ToUniversalTime(); string csvFormattedMessage = string.Format(message, args).Replace(@"""", @""""""); LogBuilder.AppendFormat(@"""[{0}]"",""[{1}]"",""[{2}]"",""{3}""", timestamp.ToLongTimeString(), stackFrame.GetMethod().DeclaringType.ToString(), stackFrame.GetMethod().Name, csvFormattedMessage); LogBuilder.AppendLine(); }
/// <summary> /// Returns function name in call stack /// </summary> /// <returns></returns> private static string GetCallerName() { System.Diagnostics.StackTrace st = new System.Diagnostics.StackTrace(true); // true means get line numbers. System.Diagnostics.StackFrame[] frames = st.GetFrames(); // [2] == <Caller> // [1] == TraceEnter()/TraceExit(), // [0] == GetCallerName(), System.Diagnostics.StackFrame f = frames[2]; return(f.GetMethod().DeclaringType.Name + "." + f.GetMethod().Name); }
public static void CreateErrorLog(string LogMsg) { // Dim frame As StackFrame = New StackFrame(1, True) //Dim ClassName As String = frame.GetMethod.ReflectedType.Name //Dim FunctionName As String = frame.GetMethod.Name //Dim LineNo As Integer = frame.GetFileLineNumber StackFrame frame = new StackFrame(1, true); string ClassName = frame.GetMethod().ReflectedType.Name; string FuntionName = frame.GetMethod().Name; int LineNo = frame.GetFileLineNumber(); CreateErrorLog(LogMsg, ClassName + "." + FuntionName, GetLocalIPAddress()); }
public static string FormatLocation(StackFrame frame) { StringBuilder location = new StringBuilder(); location.Append(frame.GetMethod().DeclaringType.ToString()); location.Append("=>"); location.Append(frame.GetMethod().ToString()); location.Append(" ["); location.Append(frame.GetILOffset()); location.Append(":"); location.Append(frame.GetNativeOffset()); location.Append("]"); return location.ToString(); }
public static Type GetCallingType() { if (EnvironmentHelper.IsProcessHostedByTool) { return typeof(object); } //#if NETFX_CORE // var type = typeof(object); //#else // var stackTrace = StackTraceHelper.GetStackTrace(); // var stackFrame = stackTrace.GetFrame(2); // var type = stackFrame.GetMethod().DeclaringType; //#endif #if NET var frame = new StackFrame(2, false); var type = frame.GetMethod().DeclaringType; #elif NETFX_CORE var type = typeof(object); #else var frame = new StackTrace().GetFrame(2); var type = frame.GetMethod().DeclaringType; #endif return type; }
public string GetLastLogin(string id) { var s = ""; try { var query = string.Format("SELECT * from WP_GAA_Users where Unique_ID like '{0}';", id); using (var connection = new MySqlConnection(ConnectionString)) { connection.Open(); using (var cmd = new MySqlCommand(query, connection)) { using (var r = cmd.ExecuteReader()) { while (r.Read()) { var loginOrdinal = r.GetOrdinal("Last_Used"); if (r.IsDBNull(loginOrdinal)) s = DateTime.MinValue.ToString(); else s = r.GetString("Last_Used"); } } } } } catch (Exception ex) { var sf = new StackFrame(); var methodBase = sf.GetMethod(); Database.InsertErrorToDb(methodBase.Name, ex.Message, ex.ToString()); } return s; }
/// <summary> /// Converts a System.Diagnostics.StackFrame to a Microsoft.ApplicationInsights.Extensibility.Implementation.TelemetryTypes.StackFrame. /// </summary> internal static IStackFrame GetStackFrame(System.Diagnostics.StackFrame stackFrame, int frameId) { var convertedStackFrame = new Telemetry.DataContract.StackFrame() { level = frameId }; var methodInfo = stackFrame.GetMethod(); string fullName; if (methodInfo.DeclaringType != null) { fullName = methodInfo.DeclaringType.FullName + "." + methodInfo.Name; } else { fullName = methodInfo.Name; } convertedStackFrame.method = fullName; convertedStackFrame.assembly = methodInfo.Module.Assembly.FullName; convertedStackFrame.fileName = stackFrame.GetFileName(); // 0 means it is unavailable int line = stackFrame.GetFileLineNumber(); if (line != 0) { convertedStackFrame.line = line; } return(convertedStackFrame); }
public string combine_paths(string leftItem, params string[] rightItems) { if (leftItem == null) { var methodName = string.Empty; var stackFrame = new System.Diagnostics.StackFrame(1); if (stackFrame != null) { methodName = stackFrame.GetMethod().Name; } throw new ApplicationException("Path to combine cannot be empty. Tried to combine null with '{0}'.{1}".format_with(string.Join(",", rightItems), string.IsNullOrWhiteSpace(methodName) ? string.Empty : " Method called from '{0}'".format_with(methodName))); } var combinedPath = Platform.get_platform() == PlatformType.Windows ? leftItem : leftItem.Replace('\\', '/'); foreach (var rightItem in rightItems) { if (rightItem.Contains(":")) { throw new ApplicationException("Cannot combine a path with ':' attempted to combine '{0}' with '{1}'".format_with(rightItem, combinedPath)); } var rightSide = Platform.get_platform() == PlatformType.Windows ? rightItem : rightItem.Replace('\\', '/'); if (rightSide.StartsWith(Path.DirectorySeparatorChar.to_string()) || rightSide.StartsWith(Path.AltDirectorySeparatorChar.to_string())) { combinedPath = Path.Combine(combinedPath, rightSide.Substring(1)); } else { combinedPath = Path.Combine(combinedPath, rightSide); } } return(combinedPath); }
/// <summary> /// Throws a new exception with the name of the parent function and value of the HR /// </summary> /// <param name="hr">Error # to include</param> internal void ThrowExceptionHere(int hr) { StackTrace stackTrace = new StackTrace(); System.Diagnostics.StackFrame stackFrame = stackTrace.GetFrame(1); throw new Exception(String.Format("Error in {0}: {1}", stackFrame.GetMethod().Name, hr)); }
public override bool Include(StackFrame frame) { var method = frame.GetMethod(); if (IsHiddenMember(method)) { return false; } var type = method.DeclaringType; // TODO (https://github.com/dotnet/roslyn/issues/5250): look for other types indicating that we're in Roslyn code if (type == typeof(CommandLineRunner)) { return false; } // Type is null for DynamicMethods and global methods. // TODO (tomat): we don't want to include awaiter helpers, shouldn't they be marked by DebuggerHidden in FX? if (type == null || IsTaskAwaiter(type) || IsTaskAwaiter(type.DeclaringType)) { return false; } return true; }
///////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////// /// <summary>Method to trace the current call with an additional message</summary> /// <param name="msg"> msg string to display</param> /// <param name="startFrame">the startFrame to uses</param> /// <param name="indent"> intendation</param> ////////////////////////////////////////////////////////////////////// [Conditional("TRACE")] static private void TraceCall(string msg, StackFrame startFrame, int indent) { // puts out the callstack and the msg try { if (startFrame != null) { StringBuilder outMsg = new StringBuilder(); MethodBase method = startFrame.GetMethod(); while (indent-- > 0) outMsg.Append(" "); outMsg.Append("--> " + method.DeclaringType.Name + "." + method.Name + "()"); if (!String.IsNullOrEmpty(msg)) outMsg.Append(": " + msg); Tracing.TraceMsg(outMsg.ToString()); } else { Tracing.TraceMsg("Method Unknown: " + msg); } Trace.Flush(); } catch { Tracing.TraceMsg(msg); } }
public static ScopeLogger GetClassLogger(ILogTape baseLogger = null, int framesToSkip = 1) { // extracted from: https://github.com/NLog string loggerName; Type declaringType; do { StackFrame frame = new StackFrame(framesToSkip, false); var method = frame.GetMethod(); declaringType = method.DeclaringType; if (declaringType == null) { loggerName = method.Name; break; } framesToSkip++; loggerName = declaringType.FullName; } while (declaringType.Module.Name.Equals("mscorlib.dll", StringComparison.OrdinalIgnoreCase)); if (baseLogger == null) baseLogger = commonLogTape; return new ScopeLogger(loggerName, baseLogger); }
public static void Write(LogType lt, string message) { StackFrame frame = new StackFrame(1); MethodBase method = frame.GetMethod(); string loc = method.DeclaringType.Name; Write(lt, loc == "Main" ? "MapleSharp" : loc, message); }
public void Enrich(LogEvent e, out string propertyName, out object propertyValue) { var frame = new StackFrame(4); //warning! this can change after refactoring propertyName = "method"; MethodBase method = frame.GetMethod(); var sb = new StringBuilder(); sb.Append(method.DeclaringType.FullName); sb.Append("."); sb.Append(method.Name); sb.Append("("); bool isFirst = true; foreach(ParameterInfo p in method.GetParameters()) { if (!isFirst) { sb.Append(", "); } else { isFirst = false; } sb.Append(p.ParameterType.Name); sb.Append(" "); sb.Append(p.Name); } sb.Append(")"); propertyValue = sb.ToString(); }
public static void Log(string message) { var trace = new StackFrame(1); var methodBase = trace.GetMethod(); var type = methodBase.DeclaringType; LogManager.GetLogger(type).Info(message); }
public void ShouldSetMemberfilterForMethodInfoOfTypeMethod() { StoryRunnerFilter filter = null; MemberInfo member = null; Given( () => { var stack = new StackFrame(2); // member = stack.GetMethod(); } ); When( () => { filter = StoryRunnerFilter.GetFilter(member); } ); Then( () => { Assert.That(filter.MethodNameFiler.ToString(), Is.EqualTo("^ShouldSetMemberfilterForMethodInfoOfTypeMethod$")); Assert.That(filter.ClassNameFilter.ToString(), Is.EqualTo("^" + typeof (StoryRunnerFilterSpecs).Name + "$")); Assert.That(filter.NamespaceFilter.ToString(), Is.EqualTo("^" + typeof(StoryRunnerFilterSpecs).Namespace + "$")); } ); }
public static string GetCurrentMethod() { System.Diagnostics.StackTrace st = new System.Diagnostics.StackTrace(); System.Diagnostics.StackFrame sf = st.GetFrame(1); return(sf.GetMethod().Name); }
/// <summary> /// returns a stack frame item from a stack frame. This /// </summary> /// <param name="frame"></param> /// <returns></returns> public StackFrameItem(StackFrame frame) { // set default values m_lineNumber = NA; m_fileName = NA; m_method = new MethodItem(); m_className = NA; try { // get frame values m_lineNumber = frame.GetFileLineNumber().ToString(System.Globalization.NumberFormatInfo.InvariantInfo); m_fileName = frame.GetFileName(); // get method values MethodBase method = frame.GetMethod(); if (method != null) { if(method.DeclaringType != null) m_className = method.DeclaringType.FullName; m_method = new MethodItem(method); } } catch (Exception ex) { LogLog.Error(declaringType, "An exception ocurred while retreiving stack frame information.", ex); } // set full info m_fullInfo = m_className + '.' + m_method.Name + '(' + m_fileName + ':' + m_lineNumber + ')'; }
private static void Log(LogLevel logLevel, string msg) { if (logLevel < LogLevel) return; StackFrame frame = new StackFrame(2, true); var method = frame.GetMethod(); var lineNumber = frame.GetFileLineNumber(); var color = Console.ForegroundColor; switch (logLevel) { case LogLevel.None: break; case LogLevel.Debug: Console.ForegroundColor = ConsoleColor.DarkGray; break; case LogLevel.Info: Console.ForegroundColor = ConsoleColor.Gray; break; case LogLevel.Warning: Console.ForegroundColor = ConsoleColor.Yellow; break; case LogLevel.Error: Console.ForegroundColor = ConsoleColor.Red; break; } Console.WriteLine("{0}.{1}:{2} - {3}", method.DeclaringType.FullName, method.Name, lineNumber, msg); Console.ForegroundColor = color; }
/// <summary> /// Initializes a new instance of the <see cref="ExceptionFrame"/> class. /// </summary> /// <param name="frame">The <see cref="StackFrame"/>.</param> public ExceptionFrame(StackFrame frame) { if (frame == null) return; int lineNo = frame.GetFileLineNumber(); if (lineNo == 0) { //The pdb files aren't currently available lineNo = frame.GetILOffset(); } var method = frame.GetMethod(); if (method != null) { Module = (method.DeclaringType != null) ? method.DeclaringType.FullName : null; Function = method.Name; Source = method.ToString(); } else { // on some platforms (e.g. on mono), StackFrame.GetMethod() may return null // e.g. for this stack frame: // at (wrapper dynamic-method) System.Object:lambda_method (System.Runtime.CompilerServices.Closure,object,object)) Module = "(unknown)"; Function = "(unknown)"; Source = "(unknown)"; } Filename = frame.GetFileName(); LineNumber = lineNo; ColumnNumber = frame.GetFileColumnNumber(); }
public static void HandleException(Exception ex, string msg) { try { if (_exceptionUseReflection) { var frame = new StackFrame(1); frame.GetMethod(); } if (ex.InnerException != null) { } if (!string.IsNullOrEmpty(msg)) { msg = "**************" + msg + "**************" + Environment.NewLine; } else { msg = Environment.NewLine; } var message = (_exceptionRecurseError) ? msg + RecurseErrorStack(ex) : msg; if (message.Length > 0) { Ea.GetEvent<DisplayExceptionMessage>().Publish(message); Ea.GetEvent<HideBusyIndicator>().Publish(string.Empty); } } catch (Exception iex) { throw (new Exception("Exception in HandleException(Exception ex, string msg): " + iex.Message)); } }
public OSAELog() { StackFrame frame = new StackFrame(1); MethodBase method = frame.GetMethod(); Type type = method.DeclaringType; Log = LogManager.GetLogger(type); var root = ((log4net.Repository.Hierarchy.Hierarchy)LogManager.GetRepository()).Root; var attachable = root as log4net.Core.IAppenderAttachable; if (attachable != null) { log4net.Repository.Hierarchy.Hierarchy hier = log4net.LogManager.GetRepository() as log4net.Repository.Hierarchy.Hierarchy; if (hier != null) { var fileAppender = (log4net.Appender.RollingFileAppender)hier.GetAppenders().Where( appender => appender.Name.Equals("RollingLogFileAppender", StringComparison.InvariantCultureIgnoreCase)).FirstOrDefault(); var adoAppender = (log4net.Appender.AdoNetAppender)hier.GetAppenders().Where( appender => appender.Name.Equals("MySql_ADONetAppender", StringComparison.InvariantCultureIgnoreCase)).FirstOrDefault(); if (Common.TestConnection().Success) { if (adoAppender != null) { adoAppender.ConnectionString = Common.ConnectionString; adoAppender.ActivateOptions(); } root.RemoveAppender(fileAppender); } } } }
// Copied from NLog static string GetClassFullName() { string className; Type declaringType; int framesToSkip = 2; do { #if SILVERLIGHT StackFrame frame = new StackTrace().GetFrame(framesToSkip); #else StackFrame frame = new StackFrame(framesToSkip, false); #endif MethodBase method = frame.GetMethod(); declaringType = method.DeclaringType; if (declaringType == null) { className = method.Name; break; } framesToSkip++; className = declaringType.FullName; } while (declaringType.Module.Name.Equals("mscorlib.dll", StringComparison.OrdinalIgnoreCase)); return className; }
/// <summary> /// Run code in a new worker thread. WorkerDelegate should return true to end, false to repeat. /// </summary> /// <param name="worker">Delegate to be run</param> /// <param name="waitTime"></param> public static void Start(Func<bool> worker, int waitTime = 50) { if (IsRunning) return; WaitTime = waitTime; var frame = new StackFrame(1); var method = frame.GetMethod(); var type = method.DeclaringType; var ns = type != null ? type.Namespace : string.Empty; _worker = worker; _thread = new Thread(SafeWorkerDelegate) { Name = string.Format("Worker: {0}.{1}", ns, type), IsBackground = true, Priority = ThreadPriority.BelowNormal, }; Logger.LogDebug("Starting {0} Thread Id={1}", _thread.Name, _thread.ManagedThreadId); _working = true; _thread.Start(); OnStarted.Invoke(); }
/// <summary> /// 获取日志记录器(为当前类找出匹配的日志记录器) /// </summary> public ILogger GetCurrentClassLogger() { var frame = new StackFrame(2); //调用日志记录器的类所在的堆栈帧 Type classType = frame.GetMethod().ReflectedType; // 查找配置中所有匹配的日志记录器 IList<ILogger> loggers = FindLoggers(classType); if (loggers.Count == 0) { return LogManager.NullLogger; } if (loggers.Count == 1) return loggers[0]; MultiLogger logger = new MultiLogger(loggers); LogLevel minLevel = LogLevel.Fatal; foreach (var logger1 in loggers) { if (logger1.MinLevel < minLevel) minLevel = logger1.MinLevel; } logger.LoadConfig(new LoggerConfig{MinLevel = minLevel, Name = "MultiLogger"}); return logger; }
/// <summary> /// 获取成员变量对应属性的缓存信息 /// </summary> /// <param name="type">JObject继承类的类型</param> /// <param name="isSet">是否为设置值</param> /// <param name="fieldName">java成员变量名称</param> /// <returns>缓存信息对象实例</returns> public static JCacheInfo GetCacheFieldParam(Type type, bool isSet, string fieldName) { PropertyInfo pinfo = null; MethodBase dotnetMethod = null; int iNext = 2; do { StackFrame frame = new StackFrame(iNext++, true); dotnetMethod = frame.GetMethod(); if (dotnetMethod == null) break; if (!dotnetMethod.IsSpecialName) continue; if (!dotnetMethod.DeclaringType.IsSubclassOf(typeof(JObject))) continue; BindingFlags bindingFlags = !dotnetMethod.IsStatic ? BindingFlags.IgnoreCase | BindingFlags.Public : BindingFlags.IgnoreCase | BindingFlags.Static | BindingFlags.Public; type = dotnetMethod.DeclaringType; pinfo = type.GetProperty(fieldName); if (pinfo != null) break; } while (dotnetMethod != null); if (pinfo == null) throw new MethodAccessException("未找到调用链上的属性。"); MethodInfo mi = (MethodInfo)dotnetMethod; bool isStatic = dotnetMethod.IsStatic; bool isVoid = mi.ReturnType == typeof(void); JCacheInfo jcacheInfo = new JCacheInfo { IsVoid = isVoid, IsStatic = isStatic, Name = fieldName }; if (isSet) jcacheInfo.Params = mi.GetParameters().ToList(); return jcacheInfo; }
private static string callerMethod(int i) { System.Diagnostics.StackFrame frame = new System.Diagnostics.StackFrame(i + 1); var method = frame.GetMethod(); return(method.DeclaringType.ToString() + " : " + method.Name); }
private void PrintException(Exception ex, List <GeneratedCode> generatedCodes) { var frames = new List <Interface.StackFrame>(); var stackTrace = new StackTrace(ex, true); for (int i = 0; i < stackTrace.FrameCount; ++i) { System.Diagnostics.StackFrame diagnosticFrame = stackTrace.GetFrame(i); // Extract method name MethodBase method = diagnosticFrame.GetMethod(); // Note(Maik): Skip internal render methods in case of a stack trace. if (Attribute.IsDefined(method, typeof(HideStackTraceAttribute))) { continue; } Type declaringType = method.DeclaringType; var methodSb = new StringBuilder(); if (declaringType != null) { methodSb.Append(declaringType.FullName).Append("."); } methodSb.Append(method.Name); // Extract original filename, line and column int?line = null; if (diagnosticFrame.GetFileLineNumber() != 0) { line = diagnosticFrame.GetFileLineNumber(); } int?column = null; if (diagnosticFrame.GetFileColumnNumber() != 0) { column = diagnosticFrame.GetFileColumnNumber(); } string filename = diagnosticFrame.GetFileName(); GeneratedCode generatedCode = generatedCodes.FirstOrDefault(gcode => string.Compare(gcode.TemplatePath, filename, StringComparison.OrdinalIgnoreCase) == 0); if ((generatedCode != null) && (line != null)) { var position = new TextPosition(line.Value, column ?? 1); TextFilePosition original = generatedCode.SourceMap.FindSourceByGenerated(position); if (original.IsValid) { filename = original.Name; line = original.Line; column = original.Column; } } var msgFrame = new Interface.StackFrame(methodSb.ToString(), filename, line, column); frames.Add(msgFrame); } // for this.MessageHandler.Message(TraceLevel.Error, $"{ex.GetType().FullName}: {ex.Message}", string.Empty, new TextPosition()); this.MessageHandler.StackTrace(frames); }
private void Log(string logtype, string msg, params object[] objs) { System.Diagnostics.StackTrace st = new System.Diagnostics.StackTrace(2); System.Diagnostics.StackFrame sf = st.GetFrame(0); string meth = sf.GetMethod().Name; this.Log(logtype, typename, meth, msg, objs); }
public static void Write(string format, params object[] args) { #if TRACE System.Diagnostics.StackTrace stackTrace = new System.Diagnostics.StackTrace(); System.Diagnostics.StackFrame stackFrame = stackTrace.GetFrame(1); System.Reflection.MethodBase methodBase = stackFrame.GetMethod(); Console.WriteLine("[thread " + System.Threading.Thread.CurrentThread.ManagedThreadId + ", " + methodBase.DeclaringType.Name + "." + methodBase.Name + "] " + string.Format(format, args)); #endif }
/// <summary> /// Used for function argument checking. /// Without specifying a exception type, the thrown exception will be of type ViolatedContractException /// </summary> /// <param name="condition">Condition that is checked for function arguments</param> /// <param name="message">The error message that is associated with the contract violation</param> /// <param name="args">Name of argment(s) that lead to the contract violation</param> public static void Requires(bool condition, string arg) { if (!condition) { var stackFrame = new System.Diagnostics.StackFrame(1, true); var method = stackFrame.GetMethod(); var methodName = string.Format("{0}.{1}(..)", method.DeclaringType.Name, method.Name); var message = string.Format(ArgumentValidationFailedMsgTemplate, methodName); Requires <ViolatedContractException>(condition, message, arg); } }
public static void PrintCodePosition(LogColor logColor) { StackFrame stackFrame = new System.Diagnostics.StackFrame(1, true); string message = "-> { " + stackFrame.GetMethod().ToString() + " }"; string[] filePath = stackFrame.GetFileName().Split('/'); message += " in " + filePath[filePath.Length - 1]; // Append the file name message += "::" + stackFrame.GetFileLineNumber().ToString(); DebugLog.LogColor(message, logColor); return; }
static void InternalTraceCall(int levels) { System.Diagnostics.StackFrame stack; stack = new System.Diagnostics.StackFrame(levels); System.Reflection.MethodBase method = stack.GetMethod(); if (method != null) { string name = method.Name + " \tin class " + method.DeclaringType.Name; System.Diagnostics.Trace.WriteLine("Call Trace: \t" + name); } }
public void TrackAsyncRequest(System.Object handle, string path) { var sf = new System.Diagnostics.StackFrame(2, true); if (sf.GetMethod().Name.Contains("SpawnAsyncOldVer")) { sf = new System.Diagnostics.StackFrame(3, true); } InProgressAsyncObjects[handle] = NewRequest(path, sf); }
static void InternalTraceCall(int levels) { System.Diagnostics.StackFrame stack; stack = new System.Diagnostics.StackFrame(levels); System.Reflection.MethodBase method = stack.GetMethod(); if (method != null) { string name = method.Name + " \tin class " + method.DeclaringType.Name; XSharpProjectPackage.Instance.DisplayOutPutMessage("Call Trace: \t" + name); } }
public static void LogCurrentStackTrace() { System.Diagnostics.StackTrace st = new System.Diagnostics.StackTrace(); Debug.Log("LogCurrentStackTrace(): "); for (int i = 1; i < st.FrameCount; i++) { System.Diagnostics.StackFrame sf = st.GetFrame(i); Debug.Log(string.Format("Method: {0} (Line: {1})", sf.GetMethod(), sf.GetFileLineNumber())); } }
private void WriteToFile(Exception ex) { System.Diagnostics.StackTrace st = new System.Diagnostics.StackTrace(ex, true); System.Diagnostics.StackFrame frame = st.GetFrame(0); string methodName = frame.GetMethod().Name; int line = frame.GetFileLineNumber(); StringBuilder sb = new StringBuilder(); sb.Append("Error: " + ex.Message.ToString() + " Method name: " + methodName + " LineNo: " + Convert.ToInt16(line)); CommonClass.WriteErrorErrFile(Request.RawUrl.ToString(), ex.StackTrace.ToString() + "-->" + sb.ToString()); }
public override string GetFullyQualifiedTopProcedure() { StackTrace st = new StackTrace(false); for (int i = 0; i < st.FrameCount; i++) { System.Diagnostics.StackFrame sf = st.GetFrame(i); string assembly_name = sf.GetMethod().Module.Assembly.GetName().ToString(); // this is fragile if (assembly_name.Contains(".ManagedChess") || assembly_name.Contains(".ExtendedReflection")) { continue; } var erMethod = MetadataFromReflection.GetMethod(sf.GetMethod()); return(erMethod.FullName); } return(""); }
public void Pop() { #if DEBUG_METHOD_CALL System.Diagnostics.StackTrace stackTrace = new System.Diagnostics.StackTrace(true); System.Diagnostics.StackFrame frame = stackTrace.GetFrame(1); Debug.LogFormat("Command Stack Pop: {0} in file {1} at line {2}", frame.GetMethod().Name, System.IO.Path.GetFileName(frame.GetFileName()), frame.GetFileLineNumber()); #endif if (!isAtStart) { commands[currentStackIndex--].Revoke(); } }
public void ErrHandle(Exception ex, int appId) { try { System.Diagnostics.StackFrame stackframe = new System.Diagnostics.StackFrame(1); string msg = stackframe.GetMethod().ReflectedType.FullName + "." + stackframe.GetMethod().Name + " - " + ex.Message; // Write to Trace Log Trace(_Err + msg, false); // // Send email to SysAdmin // Email blE = new Email(); // blE.SendMailMessage("iApplications", _AdminEmail, "", "", "iApplications Error", msg); // // Write to Event Log // WriteEventLog("iApplications", msg); // Create record in Bug Tracker //WriteAppErr(appId, userId, stackframe.GetMethod().ReflectedType.FullName, msg, loginGuid); } catch (Exception e) { ErrHandle(e); } }
public void Push(ICommand command) { #if DEBUG_METHOD_CALL System.Diagnostics.StackTrace stackTrace = new System.Diagnostics.StackTrace(true); System.Diagnostics.StackFrame frame = stackTrace.GetFrame(1); Debug.LogFormat("Command Stack Push: {0} in file {1} at line {2}", frame.GetMethod().Name, System.IO.Path.GetFileName(frame.GetFileName()), frame.GetFileLineNumber()); #endif ResetTail(); ++currentStackIndex; command.Invoke(); commands.Add(command); }
private static string jFUNC(int iSkipFuncLevel = 1) { nSD.StackTrace st = new nSD.StackTrace(); nSD.StackFrame sf = st.GetFrame(iSkipFuncLevel); nSD.StackFrame sf_prev = st.GetFrame(iSkipFuncLevel + 1); string prev_func = ""; if (sf_prev != null) { prev_func = sf_prev.GetMethod().ToString(); } return(prev_func + ">" + sf.GetMethod().ToString() + ":" + sf.GetFileName() + ":" + sf.GetFileLineNumber()); }
public override bool GetCurrentStackTrace(int n, System.Collections.Generic.List <string> procs, System.Collections.Generic.List <string> files, System.Collections.Generic.List <int> lineNos) { StackTrace st = new StackTrace(true); for (int i = 0; i < st.FrameCount; i++) { System.Diagnostics.StackFrame sf = st.GetFrame(i); string assembly_name = sf.GetMethod().Module.Assembly.GetName().ToString(); // this is fragile if (assembly_name.Contains(".ManagedChess") || assembly_name.Contains(".ExtendedReflection")) { continue; } string file = sf.GetFileName(); if (file == null || file == "") { file = "NONE"; } string method = sf.GetMethod().Name; int lineno = sf.GetFileLineNumber(); procs.Add(method); files.Add(file); lineNos.Add(lineno); if (lineNos.Count >= n) { break; } } return(true); }
public static void LogError(object message, Exception e = null) { string stackTrace = StackTraceUtility.ExtractStackTrace(); string ErrorLocation = string.Empty; #if UNITY_EDITOR if (e != null) { System.Diagnostics.StackTrace trace = new System.Diagnostics.StackTrace(e, true); System.Diagnostics.StackFrame frame = trace.GetFrame(0); ErrorLocation = "\n" + frame.GetFileName() + "." + frame.GetMethod() + ": " + frame.GetFileLineNumber(); } #endif Loom.QueueMessage(Loom.messageType.Error, message.ToString() + ErrorLocation + "\n" + stackTrace); }
public static string GetCurrentMethodName() { string name = string.Empty; try { System.Diagnostics.StackTrace st = new System.Diagnostics.StackTrace(); System.Diagnostics.StackFrame sf = st.GetFrame(2); name = sf.GetMethod().Name; } catch (Exception) { name = "Method"; } return("Exception in Method: " + name); }
public static StackFrame Create(System.Diagnostics.StackFrame frame) { if (frame == null) { return(null); } string fileName = null; bool isTaskAwaiter = false; ITypeMember member = null; try { fileName = frame.GetFileName(); } catch (SecurityException) { // CAS check failure } var method = frame.GetMethod(); if (method != null) { isTaskAwaiter = method.DeclaringType.IsTaskAwaiter() || method.DeclaringType.DeclaringType.IsTaskAwaiter(); var property = GetPropertyForMethodAccessor(method); if (property != null) { member = Property.Create(property); } else { member = Method.Create(method); } } return(new StackFrame( fileName, frame.GetFileLineNumber(), frame.GetFileColumnNumber(), frame.GetILOffset(), frame.GetNativeOffset(), frame.GetMethodAddress(), frame.GetMethodIndex(), isTaskAwaiter, ParseInternalMethodName(frame.GetInternalMethodName()), member)); }