public PlayException() { // 读取到堆栈上一帧内容 var frame = new System.Diagnostics.StackTrace(this).GetFrame(-1); MethodBase = frame.GetMethod(); m_message = frame.GetMethod().Name; }
/// <summary> /// Outputs the log. /// </summary> /// <param name="level">log level</param> /// <param name="message">message</param> public void OutputLog(LogEventLevel level, string message) { var frame = new System.Diagnostics.StackTrace().GetFrame(0); var className = frame.GetMethod().ReflectedType.FullName; var method = frame.GetMethod().Name; outputLog(level, message, className, method); }
public void RunPsTest(XunitTracingInterceptor interceptor, params string[] scripts) { var sf = new System.Diagnostics.StackTrace().GetFrame(1); var callingClassType = sf.GetMethod().ReflectedType?.ToString(); var mockName = sf.GetMethod().Name; RunPsTestWorkflow( interceptor, () => scripts, // no custom cleanup null, callingClassType, mockName); }
protected async Task <TResult> MakeRequestAsync <TResult>(params object[] requestParameters) { var targetStack = new System.Diagnostics.StackTrace(1).GetFrames().FirstOrDefault(f => { var t = f.GetMethod().DeclaringType; return(t != typeof(ClientBase) && t.IsInstanceOfType(this)); }); string invokingMethod = targetStack.GetMethod().Name; var request = OperationWrapper.ForRequest(invokingMethod, requestParameters); _lock.Wait(); try { Socket socket = GetSocket(); // Send the client request. await socket.SendWrapperRequestAsync(request); // Now read back the server response. return((await socket.GetWrapperResponseAsync()).GetResultAs <TResult>()); } finally { _lock.Release(); } }
/// <summary> /// Gets parameters used after firing an event. /// </summary> /// <returns>Returns an object array of parameters to pass to the caller of fireEvent.</returns> public override object[] getReturnParams() { if (this.IsCancelled) { System.Diagnostics.StackFrame sf = new System.Diagnostics.StackTrace().GetFrame(1); if (sf != null && sf.GetMethod().Module.Equals(this.GetType().Module) && this.world != null) { List <BlockChangeInfo> blockPosTypes = new List <BlockChangeInfo>(this.blockPosTypes.Count); foreach (BlockChangeInfo oldType in this.blockPosTypes) { object blockVal = this.world.GetType().GetMethod("GetBlock", new Type[] { typeof(int), typeof(int), typeof(int) }).Invoke(this.world, new object[] { oldType.pos.x, oldType.pos.y, oldType.pos.z }); blockPosTypes.Add( (BlockChangeInfo)(typeof(BlockChangeInfo).GetConstructor( new Type[] { typeof(Vector3i), blockVal.GetType(), typeof(bool) } ).Invoke(new object[] { oldType.pos, blockVal, false })) ); } foreach (GameManager gm in SKMain.SkMain.activeGameManagers()) { gm.SetBlocksRPC(blockPosTypes); } } } return(new object[] { this.IsCancelled, this.blockPosTypes, this.world }); }
public static void Log(System.Object message, int StackTraceFrameOffset = 0) { var stackTraceFrame = new System.Diagnostics.StackTrace(true).GetFrame(1 + StackTraceFrameOffset); var line = stackTraceFrame.GetFileLineNumber(); var method = stackTraceFrame.GetMethod(); if (message.GetType().IsArray) { string arrayMessage = "array["; foreach (System.Object obj in message as System.Object[]) { if (obj == null) { arrayMessage += "\n-<i>null</i>"; } else { arrayMessage += "\n-" + obj.ToString(); } } arrayMessage += "\n]"; UnityEngine.Debug.Log(string.Format(LOG_TEXT, method, line, arrayMessage)); } else { UnityEngine.Debug.Log(string.Format(LOG_TEXT, method, line, message)); } }
/// <summary> /// Method for logging debug/trace information to a file. ///NOTE: Read/Write privileges must be given to the web service /// process owner and domain users if impersonation is performed /// </summary> /// <param name="msg"></param> private static void log(String msg) { StreamWriter logger = File.AppendText(LogFile); System.Diagnostics.StackFrame frame = new System.Diagnostics.StackTrace().GetFrame(2); logger.WriteLine(System.DateTime.Now + ", " + frame.GetMethod().Name + ": " + msg); logger.Close(); }
/// <summary> /// log a single line of text to the log file /// </summary> /// <param name="text">text to log</param> public static void Log(string text) { var frame = new System.Diagnostics.StackTrace().GetFrame(1); var method = frame.GetMethod(); write(string.Format("[{0}] {2}.{3}() [{4}({5},{6})]: {1}", DateTime.Now.ToString("dd.MM.yyyy HH:MM:ss"), text, method.ReflectedType.FullName, method.Name, frame.GetFileName(), frame.GetFileLineNumber(), frame.GetFileColumnNumber())); }
public static void Error(System.Object message, int StackTraceFrameOffset = 0) { var stackTraceFrame = new System.Diagnostics.StackTrace(true).GetFrame(1 + StackTraceFrameOffset); var line = stackTraceFrame.GetFileLineNumber(); var method = stackTraceFrame.GetMethod(); UnityEngine.Debug.LogError(string.Format(LOG_TEXT, method, line, message)); }
private static string GetMethodName() { // skip GetMethodName and whatever Scan* method that called it var frame = new System.Diagnostics.StackTrace(2).GetFrame(0); var name = frame.GetMethod().Name; name = name.Substring(4); // trim off "_set"; return(name); }
/// <summary> /// Method for logging debug/trace information to a file. ///NOTE: Read/Write privileges must be given to the web service /// process owner and domain users if impersonation is performed /// </summary> /// <param name="msg"></param> private static void log(String msg) { if (LogFile == null) { // TODO: log this to event log return; } lock (LogFile) { StreamWriter logger = File.AppendText(LogFile); System.Diagnostics.StackFrame frame = new System.Diagnostics.StackTrace().GetFrame(2); logger.WriteLine(System.DateTime.Now + ", " + frame.GetMethod().Name + ": " + msg); logger.Close(); } }
public static Error.IError Create(Error.Level level, string title, string message) { System.Diagnostics.StackFrame frame = new System.Diagnostics.StackTrace().GetFrame(2); System.Reflection.MethodBase method = frame.GetMethod(); Type type = method.DeclaringType; System.Reflection.AssemblyName assembly = type.Assembly.GetName(); return new Entry() { Time = DateTime.Now, Level = level, Title = title, Message = message, AssemblyName = assembly.Name, AssemblyVersion = assembly.Version.ToString(), Type = type.FullName, Method = method.Name, Filename = frame.GetFileName(), Line = frame.GetFileLineNumber(), Column = frame.GetFileColumnNumber(), }; }
private Type GetParentTypeName(IContext iContext) { if (iContext.Request.Target == null || iContext.Request.Target.Member == null) { try { #if DEBUG var frame = new System.Diagnostics.StackTrace(true).GetFrame(11); return frame.GetMethod().DeclaringType; #else return typeof(ILog); #endif } catch (Exception) { return typeof (ILog); } } return iContext.Request.Target.Member.ReflectedType; }
// ------------------------------------------------------------------------------------ // Methods // Write to the console public void Write(DebugLevel debugLevel, MessageLevel messageLevel, string message) { if (Application.platform != RuntimePlatform.IPhonePlayer) { System.Diagnostics.StackFrame stackFrame = new System.Diagnostics.StackTrace(1, true).GetFrame(0); // Get a stack frame from the caller string fileName = stackFrame.GetFileName(); // Get file name of caller string[] fileNameSplit = fileName.Split(new char[] { '\\' }); // Split file name string scriptName = fileNameSplit [fileNameSplit.Length - 1]; // Extract script name from file name string methodName = stackFrame.GetMethod().ToString(); // Get method name of caller int lineNumber = stackFrame.GetFileLineNumber(); // Get line number of caller message = message + System.Environment.NewLine + scriptName + " - " + methodName + " - L" + lineNumber; // Append stack data to message } if ((int)debugLevel <= (int)debug) // Filter messages of higher level than requested { if (playerConsole) // If print all messages in player console { Debug.LogError(message); // Print a LogError } else { switch (messageLevel) // Switch on message level { case MessageLevel.Log: Debug.Log(message); // Print a Log break; case MessageLevel.LogWarning: Debug.LogWarning(message); // Print a LogWarning break; case MessageLevel.LogError: Debug.LogError(message); // Print a LogError break; } } } }
private string qualifiedObjName() { System.Diagnostics.StackFrame sf = new System.Diagnostics.StackTrace(true).GetFrame(2); string sMethodName = sf.GetMethod().Name; string sClassname = sf.GetMethod().DeclaringType.Name; return string.Format("{0}.{1} Line {2}", sClassname, sMethodName, sf.GetFileLineNumber().ToString()); }
/// <summary> /// using reflection we try to get the type name and the method name, from where the log message was entered /// </summary> /// <returns></returns> private static string GetMethodName() { //try to get frame from calling place var frame = new System.Diagnostics.StackTrace(true).GetFrame(2); //if(frame.GetFileName() == null) //{ // return string.Empty; //} return $"{frame.GetMethod().Name}()"; }
/// <summary> /// Log the message to the log file, provided the logging was /// initialized. /// </summary> /// <param name="message">The message being logged.</param> /// <param name="noTimeStamp">Used to override the default inclusion /// of date/time stamp in each logged line.</param> /// <param name="staticOutputLocation">Used to set console output to a /// fixed location. This is useful for output such as progress /// percentage etc.</param> /// <returns>true if logging was successful, false if not.</returns> public static bool Log(string message, bool noTimeStamp = false, bool staticOutputLocation = false, bool includeStackFrame = false, bool overLoaded = false) { // No logging code should EVER terminate it's parent program // through exceptions. try { // Check if caller wants StackFrame info included. if (includeStackFrame) { int frameOffset = 1; // Check if an overloaded method is used to call Log(). if (overLoaded) { frameOffset++; } // Get the StackFrame including FileInfo. var stackFrame = new System.Diagnostics.StackTrace(true) .GetFrame(frameOffset); // Append the StackFrame info to the message. message = string.Format(message + " --->>> Called from {0} in {1} line {2} column {3}.", stackFrame.GetMethod().ToString(), stackFrame.GetFileName(), stackFrame.GetFileLineNumber(), stackFrame.GetFileColumnNumber()); } // We use a single & because if we're not logging to the // console, it does not matter to what value // staticOutputLocation is set. The use of single & prevents // run time evaluation of the value of staticOutputLocation // if logToConsole is false thus improving runtime execution // performance. if (logToConsole & staticOutputLocation) { // We want static location output so we capture the current // cursor location. _cursorLeft = Console.CursorLeft; _cursorTop = Console.CursorTop; } // Write to the log file. _writer.WriteLine(prependTimeStamp(message, noTimeStamp)); // Flush the writer so no messages are stuck in the buffer. _writer.Flush(); // Check if console output is required. if (logToConsole) { // Are we keeping output in a static location? if (staticOutputLocation) { // Reset the cursor before output. Console.CursorTop = _cursorTop; Console.CursorLeft = _cursorLeft; // Output the message with a large trailing // blank to clear previous output from the static // console line. Console.WriteLine( prependTimeStamp(message, noTimeStamp) + " " + " " + " "); // Reset the cursor after output. Console.CursorTop = _cursorTop; Console.CursorLeft = _cursorLeft; } // No static output location is required. else { // Simply write the message to the console. Console.WriteLine(prependTimeStamp( message, noTimeStamp)); } } if (logToEventLog) { // Write to Event Log's Application log System.Diagnostics.EventLog.WriteEntry("Application", prependTimeStamp(message, noTimeStamp), logToEventLogEntryType); } } // Something went wrong. catch (Exception ex) { System.Diagnostics.EventLog.WriteEntry("Application", ex.ToString(), logToEventLogEntryType); _outputColor = Console.ForegroundColor; Console.ForegroundColor = ConsoleColor.Red; // Check if output is going to the console. if (logToConsole) { // Write console output, stamped if needed. Console.WriteLine( prependTimeStamp(ex.ToString(), noTimeStamp)); } // No logging code should EVER terminate it's parent program // through exceptions. Wrap this file output in a try/catch // in case file writing throws an exception. try { // Reset the writer to open log file in append mode. using (System.IO.StreamWriter writer = new System.IO.StreamWriter(_logPath, true)) { // Write the exception to the log file, stamped if // needed. writer.WriteLine( prependTimeStamp(ex.ToString(), noTimeStamp)); // Flush the file writer buffer. writer.Flush(); } } // Have to distinguish between inner and outer exceptions. catch (Exception ex2) { System.Diagnostics.EventLog.WriteEntry("Application", ex2.ToString(), logToEventLogEntryType); // Write the inner exception error. Quix.Core.writeConsoleError(ex2.ToString()); } // Reset the console foreground color. Console.ForegroundColor = _outputColor; // Return false since something went wrong during logging. return(false); } // Logging succeeded. return(true); }
/// <summary> /// Initialises the Logger prior to use /// </summary> public static void Initialise(string source_name) { try { if (_event_log == null) { lock (typeof(Logger)) { if (_event_log == null) { CreateLog(source_name); _event_log = new System.Diagnostics.EventLog(_eventlog_name, ".", source_name); try { string max_event_log_type = System.Web.Configuration.WebConfigurationManager.AppSettings["MaxEventLogType"]; if (!string.IsNullOrEmpty(max_event_log_type)) { _max_event_log_type = (System.Diagnostics.EventLogEntryType)System.Enum.Parse(typeof(System.Diagnostics.EventLogEntryType), max_event_log_type); } } catch { } } } } System.Diagnostics.StackFrame lFrame = new System.Diagnostics.StackTrace(1).GetFrame(0); MandatoryLog(System.Diagnostics.EventLogEntryType.Information, string.Format("Build version [{0}]", lFrame.GetMethod().DeclaringType.AssemblyQualifiedName)); #if DEBUG MandatoryLog(System.Diagnostics.EventLogEntryType.Information, "Debug Build"); #else MandatoryLog(System.Diagnostics.EventLogEntryType.Information, "Release Build"); #endif MandatoryLog(System.Diagnostics.EventLogEntryType.Information, string.Format("Running on OS Version [{0}]", System.Environment.OSVersion)); MandatoryLog(System.Diagnostics.EventLogEntryType.Information, string.Format("Running on .Net Version [{0}]", System.Environment.Version)); System.Net.IPHostEntry my_ips = System.Net.Dns.GetHostEntry(System.Environment.MachineName); MandatoryLog(System.Diagnostics.EventLogEntryType.Information, string.Format("Running on machine [{0}] [{1}]", System.Environment.MachineName, (my_ips != null && my_ips.AddressList.Length > 0) ? my_ips.AddressList[0].ToString() : "no-ip?")); MandatoryLog(System.Diagnostics.EventLogEntryType.Information, string.Format("Running as User [{0}]", System.Security.Principal.WindowsIdentity.GetCurrent().Name)); } catch (Exception) { //Can't do anything with logging failures. } }