Search Results

Search found 16 results on 1 pages for 'stackframe'.

Page 1/1 | 1 

  • getting the name of the calling method

    - by zeocrash
    Basically i've got a web service that i'm trying to put some kind of usage logging in. To do this i've created a class with a logging method. I instatiate the class on the service and then call the logging method in each of the web methods. I'm trying to find a way of getting the name of the method that has called the loggong method Public sub tstmethod log_object.log_method end sub in this case the returned name i'm looking for is "tstmethod" Everywhere i've seen has said to either use Dim stackframe As New Diagnostics.StackFrame Return stackframe.GetMethod.Name.ToString Or to use Dim stackframe As New Diagnostics.StackFrame Return stackframe.GetMethod.DeclaringType.FullName which i call inside the logging method getmethod.name.tostring returns the name of the logging method getmethod.declaringtype.fullname returns the name of the logging class no matter what i do i cannot find a way of getting the name of the method that called the logging method in this case "tstmethod"

    Read the article

  • Obtaining references to function objects on the execution stack from the frame object?

    - by Marcin
    Given the output of inspect.stack(), is it possible to get the function objects from anywhere from the stack frame and call these? If so, how? (I already know how to get the names of the functions.) Here is what I'm getting at: Let's say I'm a function and I'm trying to determine if my caller is a generator or a regular function? I need to call inspect.isgeneratorfunction() on the function object. And how do you figure out who called you? inspect.stack(), right? So if I can somehow put those together, I'll have the answer to my question. Perhaps there is an easier way to do this?

    Read the article

  • Identifying a function call in a python script line in runtime

    - by Dani
    I have a python script that I run with 'exec'. The script's string has calls to functions. When a function is called, I would like it to know the line number and offset in line for that call in the script (in the string I fed exec with). Here is an example. If my script is: foo1(); foo2(); foo1() foo3() And if I have code that prints (line,offset) in every function, I should get (0,0), (0,8), (0,16), (1,0) In most cases this can be easily done by getting the stack frame, because it contains the line number and the function name. The only problem is when there are two functions with the same name in a certain line. Unfortunately this is a common case for me. Any ideas?

    Read the article

  • C#/.NET Little Wonders: Getting Caller Information

    - by James Michael Hare
    Originally posted on: http://geekswithblogs.net/BlackRabbitCoder/archive/2013/07/25/c.net-little-wonders-getting-caller-information.aspx Once again, in this series of posts I look at the parts of the .NET Framework that may seem trivial, but can help improve your code by making it easier to write and maintain. The index of all my past little wonders posts can be found here. There are times when it is desirable to know who called the method or property you are currently executing.  Some applications of this could include logging libraries, or possibly even something more advanced that may server up different objects depending on who called the method. In the past, we mostly relied on the System.Diagnostics namespace and its classes such as StackTrace and StackFrame to see who our caller was, but now in C# 5, we can also get much of this data at compile-time. Determining the caller using the stack One of the ways of doing this is to examine the call stack.  The classes that allow you to examine the call stack have been around for a long time and can give you a very deep view of the calling chain all the way back to the beginning for the thread that has called you. You can get caller information by either instantiating the StackTrace class (which will give you the complete stack trace, much like you see when an exception is generated), or by using StackFrame which gets a single frame of the stack trace.  Both involve examining the call stack, which is a non-trivial task, so care should be done not to do this in a performance-intensive situation. For our simple example let's say we are going to recreate the wheel and construct our own logging framework.  Perhaps we wish to create a simple method Log which will log the string-ified form of an object and some information about the caller.  We could easily do this as follows: 1: static void Log(object message) 2: { 3: // frame 1, true for source info 4: StackFrame frame = new StackFrame(1, true); 5: var method = frame.GetMethod(); 6: var fileName = frame.GetFileName(); 7: var lineNumber = frame.GetFileLineNumber(); 8: 9: // we'll just use a simple Console write for now 10: Console.WriteLine("{0}({1}):{2} - {3}", 11: fileName, lineNumber, method.Name, message); 12: } So, what we are doing here is grabbing the 2nd stack frame (the 1st is our current method) using a 2nd argument of true to specify we want source information (if available) and then taking the information from the frame.  This works fine, and if we tested it out by calling from a file such as this: 1: // File c:\projects\test\CallerInfo\CallerInfo.cs 2:  3: public class CallerInfo 4: { 5: Log("Hello Logger!"); 6: } We'd see this: 1: c:\projects\test\CallerInfo\CallerInfo.cs(5):Main - Hello Logger! This works well, and in fact CallStack and StackFrame are still the best ways to examine deeper into the call stack.  But if you only want to get information on the caller of your method, there is another option… Determining the caller at compile-time In C# 5 (.NET 4.5) they added some attributes that can be supplied to optional parameters on a method to receive caller information.  These attributes can only be applied to methods with optional parameters with explicit defaults.  Then, as the compiler determines who is calling your method with these attributes, it will fill in the values at compile-time. These are the currently supported attributes available in the  System.Runtime.CompilerServices namespace": CallerFilePathAttribute – The path and name of the file that is calling your method. CallerLineNumberAttribute – The line number in the file where your method is being called. CallerMemberName – The member that is calling your method. So let’s take a look at how our Log method would look using these attributes instead: 1: static int Log(object message, 2: [CallerMemberName] string memberName = "", 3: [CallerFilePath] string fileName = "", 4: [CallerLineNumber] int lineNumber = 0) 5: { 6: // we'll just use a simple Console write for now 7: Console.WriteLine("{0}({1}):{2} - {3}", 8: fileName, lineNumber, memberName, message); 9: } Again, calling this from our sample Main would give us the same result: 1: c:\projects\test\CallerInfo\CallerInfo.cs(5):Main - Hello Logger! However, though this seems the same, there are a few key differences. First of all, there are only 3 supported attributes (at this time) that give you the file path, line number, and calling member.  Thus, it does not give you as rich of detail as a StackFrame (which can give you the calling type as well and deeper frames, for example).  Also, these are supported through optional parameters, which means we could call our new Log method like this: 1: // They're defaults, why not fill 'em in 2: Log("My message.", "Some member", "Some file", -13); In addition, since these attributes require optional parameters, they cannot be used in properties, only in methods. These caveats aside, they do let you get similar information inside of methods at a much greater speed!  How much greater?  Well lets crank through 1,000,000 iterations of each.  instead of logging to console, I’ll return the formatted string length of each.  Doing this, we get: 1: Time for 1,000,000 iterations with StackTrace: 5096 ms 2: Time for 1,000,000 iterations with Attributes: 196 ms So you see, using the attributes is much, much faster!  Nearly 25x faster in fact.  Summary There are a few ways to get caller information for a method.  The StackFrame allows you to get a comprehensive set of information spanning the whole call stack, but at a heavier cost.  On the other hand, the attributes allow you to quickly get at caller information baked in at compile-time, but to do so you need to create optional parameters in your methods to support it. Technorati Tags: Little Wonders,CSharp,C#,.NET,StackFrame,CallStack,CallerFilePathAttribute,CallerLineNumberAttribute,CallerMemberName

    Read the article

  • How to get StackFrame at compile time from PDB?

    - by Usman
    Hello, I need to get stack frame of function from any pdb (All in/out arguments and their types). I got function name and address of certain function from pdb, now I need to know all parameters(in/out) of that function from pdb file programatically. Is there any way..?? Regards Usman

    Read the article

  • to write log files in two different files

    - by Sun
    my application run on customized client framework,the client framework used log4net to log their own log files. we are(our application) has to use the same log4net to log our log files in our own path(say our customized path). currently the our log files are created but log are not writing in that file.it is writting in the client framework log file. searched lot of sites the link http://stackoverflow.com/questions/308436/log4net-programmatcially-specify-multiple-loggers-with-multiple-file-appenders helped me to configure the log4net config programatically, still im log statemets are not written in my log file.the code used as below public class TraceLog { private string message = string.Empty; private static ILog ILogger = null; private static TraceLog instance = new TraceLog(); private TraceLog() { SetLevel("Log4net.MainForm", "ALL"); AddAppender("Log4net.MainForm", CreateFileAppender("FileAppender", "C:\\mylog.log")); } public static TraceLog Instance { get { return instance; } } public void Debug(string logMessage) { message = PrepareLog(logMessage); ILogger.Debug(message); } protected string PrepareLog(string logMessage) { string message = GetFileMethodLineNumberInfo(); message += logMessage; return message; } protected string GetFileMethodLineNumberInfo() { StackTrace stackTrace = new StackTrace(true); // The position 3 is relative to the index of the specified method StackFrame stackFrame = stackTrace.GetFrame(3); return (stackFrame.GetMethod().DeclaringType.Name + "/" + stackFrame.GetMethod().Name + "/" + stackFrame.GetFileLineNumber() + ":"); } private static void SetLevel(string loggerName, string levelName) { ILogger = LogManager.GetLogger(loggerName); log4net.Repository.Hierarchy.Logger l = (log4net.Repository.Hierarchy.Logger)ILogger.Logger; l.Level = l.Hierarchy.LevelMap[levelName]; } private static void AddAppender(string loggerName, IAppender appender) { ILogger = LogManager.GetLogger(loggerName); log4net.Repository.Hierarchy.Logger l = (log4net.Repository.Hierarchy.Logger)ILogger.Logger; l.AddAppender(appender); } private static IAppender CreateFileAppender(string name, string fileName) { FileAppender appender = new FileAppender(); appender.Name = name; appender.File = fileName; appender.AppendToFile = true; //PatternLayout layout = new PatternLayout(); //layout.ConversionPattern = "%d [%t] %-5p %c [%x] - %m%n"; //layout.ActivateOptions(); //appender.Layout = layout; appender.ActivateOptions(); return appender; } } } anyone pls help how to solve this

    Read the article

  • Can I get the method local variables through a stack trace in C#?

    - by smwikipedia
    I want to get a detailed log about my stack trace. I can get a StackFrame and then the method and then get all the parameters of that method. Just as the following code: StackTrace st = new StackTrace(); StackFrame[] sfs = st.GetFrames(); foreach (StackFrame sf in sfs) { MethodBase method = sf.GetMethod(); ParameterInfo[] pis = method.GetParameters(); foreach (ParameterInfo pi in pis) { .... } Console.WriteLine(method.Name); } But how could I get the local variables infomation within a method? Could someone shed some light on me? Many thanks.

    Read the article

  • How to get stack trace of a running process from within a Visual Studio add-in?

    - by Jack
    I am writing a Visual Studio add-in in C# which will run while I am debugging a process in the same Visual Studio window and I need access to that the process' stack trace from within my add-in. I tried putting this code into my add-in but it returns the add-in's stack trace, not the process I am debugging. System.Diagnostics.StackTrace stacktrace = new System.Diagnostics.StackTrace(true); System.Diagnostics.StackFrame stackframe = stacktrace.GetFrame(0); Any help would be appreciated.

    Read the article

  • How to get stack trace of a running process from a Visual Studio add-in?

    - by Jack
    I am writing a Visual Studio add-in in C# and I need access to the currently running process' stack trace. I tried putting this code into my add-in but it returns the add-in's stack trace, not the process I am debugging. System.Diagnostics.StackTrace stacktrace = new System.Diagnostics.StackTrace(true); System.Diagnostics.StackFrame stackframe = stacktrace.GetFrame(0); Any help would be appreciated.

    Read the article

  • Accessing program information that gdb sees in C++

    - by anon
    I have a program written in C++, on Linux, compiled with -g. When I run it under gdb, I can 1) set breakpoints 2) at those breakpoints, print out variables 3) see the stackframe 4) given a variable that's a structure, print out parts of the structure (i.e. how ddd displays information). Now, given that my program is compiled with "-g" -- is there anyway that I can access this power within my program itself? I.e. given that my program is compiled with "-g", is there some std::vector<string> getStackFrame(); function I can call to get the current stackframe at the current point of execution? Given a pointer to an object and it's type ... can I do std::vector getClassMember(class_name); ? I realize the default answer is "no, C++ doesn't support that level of introspection" -- however, recall I'm on linux, my program is compiled with "-g", and gdb can do it, so clearly the inforamtion is there. Question is: is there some API for accessing it? EDIT: PS Naysers, I'd love to see a reason for closing this question.

    Read the article

  • loadparm.c:4864, leaking memory?

    - by RandomOzzy
    I’m running Ubuntu 14.04 Server with a LAMP stack, Samba, and FTP, no GUI, just SSHing into the server and working on it. I’m having trouble searching down a solution to this issue, but as far as I can Google for it, it might have something to do with Samba. no talloc stackframe at ../source3/param/loadparm.c:4864, leaking memory?? The warning doesn't pop up at any kind of regular intervals or in response to the same or repeated actions. It pops up between things I’m doing - changing directories, editing files, copying stuff, and it often pops up when I first log in. Has anyone got experience fixing this issue?

    Read the article

  • Why not to use StackTrace to find what method called you

    - by Alex.Davies
    Our obfuscator, SmartAssembly, does some pretty crazy reflection. It's an obfuscator, it's sort of its job to do things in the most awkward way possible. But sometimes, you can go too far. One such time is this little gem from the strings encoding feature: StackTrace stackTrace = new StackTrace(); StackFrame frame = stackTrace.GetFrame(1); Type ownerType = frame.GetMethod().DeclaringType; It's designed to find the type where the calling method is defined. A user found that strings encoding occasionally broke on x64 systems. Very strange. After some debugging (thank god for Reflector Pro, it would be impossible to debug processed assemblies without it) I found that the ownerType I got back was wrong. The reason is that the x64 JIT does tail call optimisation. This saves space on the stack, and speeds things up, by throwing away a method's stack frame if the last thing that it calls is the only thing returned. When this happens, the call to StackTrace faithfully tells you that the calling method is the one that called the one we really wanted. So using StackTrace isn't safe for anything other than debugging, and it will make your code fail in unpredictable ways. Don't use it!

    Read the article

  • ZFS pool broken after upgrading to 14.04 LTS

    - by cruiserparts
    Well, I have been putting off upgrading to 14.04 for fear that I would break something. Actually for fear that it would break zfs (or I would break it). I am bascially slightly better than novice at linux. Spent the last couple of hours trying to get the pool back. Now I am at the stage where I don't think I have a complete failure, but I am worried that I may break it. So if could help me not break it, and recover it, I would be thankful. My zfs is file storage and not boot. It was working fine for a year and was working perfectly before the upgrade (scrub and everything was fine). I was confident that the upgrade would work (or at least I could fix it) because I had upgraded once in the past, the pool went missing, but I was able to get it back. I have reinstalled zfs, zfs utilities, and some dependencies (after searching this forum) I think what happened is 14.04 deleted some config file, or specified disk names differntly, but I could be wrong. When I set the pool up originally, I was using specific device Ids as I recall (because I did not want to break things if they got reassigned at boot) So see if this helps. I can confirm that old mountpoint folders are there but empty. no talloc stackframe at ../source3/param/loadparm.c:4864, leaking memory pool: naspool1 state: UNAVAIL status: One or more devices could not be used because the label is missing or invalid. There are insufficient replicas for the pool to continue functioning. action: Destroy and re-create the pool from a backup source. see: http://zfsonlinux.org/msg/ZFS-8000-5E scan: none requested config: NAME STATE READ WRITE CKSUM naspool1 UNAVAIL 0 0 0 insufficient replicas raidz1-0 UNAVAIL 0 0 0 insufficient replicas scsi-SATA_WDC_WD1001FALS-_WD-WMATV0990825 UNAVAIL 0 0 0 scsi-SATA_WDC_WD1001FALS-_WD-WMATV2995365 UNAVAIL 0 0 0 scsi-SATA_WDC_WD10EARS-00_WD-WMAV51894349 UNAVAIL 0 0 0 ___@ourserver:~$ sudo zpool import naspool1 cannot import 'naspool1': a pool with that name is already created/imported, and no additional pools with that name were found ___@ourserver:~$ sudo zfs list no datasets available What other output can I post to help? I'm thinking the update deleted some zfs config files. It seems like the pool exists and certainly 3 perfectly working disks did not fail at once. I am worried that I may break something without a little bit of guideance. Thanks.

    Read the article

  • Generate BitmapSource from UIElement

    - by Joel
    I am attempting to generate a BitmapFrame that is based on a UIElement. Here is my function: private BitmapFrame RenderToBitmap2() { RenderTargetBitmap renderBitmap = new RenderTargetBitmap(200, 200, 96, 96, PixelFormats.Pbgra32); DrawingVisual drawingVisual = new DrawingVisual(); DrawingContext drawingContext = drawingVisual.RenderOpen(); VisualBrush aVisualBrush = new VisualBrush(GenerateTestStackPanel()); drawingContext.DrawRectangle(aVisualBrush, new Pen(Brushes.Green, 2), new Rect(new Size(150, 150))); drawingContext.Close(); renderBitmap.Render(drawingVisual); return BitmapFrame.Create(renderBitmap); } For testing and debugging purposes, I am using an additional function that creates a simple StackFrame that should create a valid visual element that can be represented: private StackPanel GenerateTestStackPanel() { // Create a red Ellipse. Ellipse myEllipse = new Ellipse(); myEllipse.Fill = Brushes.Green; myEllipse.StrokeThickness = 2; myEllipse.Stroke = Brushes.Black; // Set the width and height of the Ellipse. myEllipse.Width = 200; myEllipse.Height = 200; // Add the Ellipse to the StackPanel. StackPanel myStackPanel = new StackPanel(); myStackPanel.Children.Add(myEllipse); return myStackPanel; } For some reason, the VisualBrush is not being rendered in the DrawRetangle(...) function. I can see the green border but nothing else. In addition, if I swap out the VisualBrush with a standard brush, it works great: drawingContext.DrawRectangle(Brushes.Plum, new Pen(Brushes.Green, 2), new Rect(new Size(150, 150))); Thanks in advance! -Joel

    Read the article

  • Accessing frame info in gdb

    - by Maelstrom
    In gdb, is there a way to access the contents of info frame in a script? I'm debugging a problem somewhere between Apache, PHP, APC and my own code, and I have about a hundred cores to choose from. Following the instructions here http://bugs.php.net/bugs-generating-backtrace.php I end up with a stacktrace like: #0 0x0121a31a in do_bind_function (opline=0xa94dd750, function_table=0x9b9cf98, compile_time=0 '\0') at /usr/src/debug/php-5.2.7/Zend/zend_compile.c:2407 #1 0x0124bb2e in ZEND_DECLARE_FUNCTION_SPEC_HANDLER (execute_data=0xbfef7990) at /usr/src/debug/php-5.2.7/Zend/zend_vm_execute.h:498 #2 0x01249dfa in execute (op_array=0xb79d5d3c) at /usr/src/debug/php-5.2.7/Zend/zend_vm_execute.h:92 #3 0x01261e31 in ZEND_INCLUDE_OR_EVAL_SPEC_VAR_HANDLER (execute_data=0xbfef80d0) at /usr/src/debug/php-5.2.7/Zend/zend_vm_execute.h:7809 #4 0x01249dfa in execute (op_array=0xb79d55ec) at /usr/src/debug/php-5.2.7/Zend/zend_vm_execute.h:92 ... #26 0x09caa894 in ?? () #27 0x00000000 in ?? () The stack will always look similar, with function execute and ZEND_something interleaved several times. I need to go up to the last instance of execute (up 2 in this case) and print myVar. Obviously gdb knows the function names, but does it surface them in any user variables I could access? Typing frame 2 shows a one-line version, and info frame shows a single stackframe in detail. I want to do something like while ($current_frame.function_name != "execute") {up;} print myVar but I don't see how to do it strictly within gdb. Is there a variable / structure / special memory location / something that allows access to gdb's information on either the whole stack (like bt) or to the current stack frame (like info frame)?

    Read the article

  • The Return Of __FILE__ And __LINE__ In .NET 4.5

    - by Alois Kraus
    Good things are hard to kill. One of the most useful predefined compiler macros in C/C++ were __FILE__ and __LINE__ which do expand to the compilation units file name and line number where this value is encountered by the compiler. After 4.5 versions of .NET we are on par with C/C++ again. It is of course not a simple compiler expandable macro it is an attribute but it does serve exactly the same purpose. Now we do get CallerLineNumberAttribute  == __LINE__ CallerFilePathAttribute        == __FILE__ CallerMemberNameAttribute  == __FUNCTION__ (MSVC Extension)   The most important one is CallerMemberNameAttribute which is very useful to implement the INotifyPropertyChanged interface without the need to hard code the name of the property anymore. Now you can simply decorate your change method with the new CallerMemberName attribute and you get the property name as string directly inserted by the C# compiler at compile time.   public string UserName { get { return _userName; } set { _userName=value; RaisePropertyChanged(); // no more RaisePropertyChanged(“UserName”)! } } protected void RaisePropertyChanged([CallerMemberName] string member = "") { var copy = PropertyChanged; if(copy != null) { copy(new PropertyChangedEventArgs(this, member)); } } Nice and handy. This was obviously the prime reason to implement this feature in the C# 5.0 compiler. You can repurpose this feature for tracing to get your hands on the method name of your caller along other stuff very fast now. All infos are added during compile time which is much faster than other approaches like walking the stack. The example on MSDN shows the usage of this attribute with an example public static void TraceMessage(string message, [CallerMemberName] string memberName = "", [CallerFilePath] string sourceFilePath = "", [CallerLineNumber] int sourceLineNumber = 0) { Console.WriteLine("Hi {0} {1} {2}({3})", message, memberName, sourceFilePath, sourceLineNumber); }   When I do think of tracing I do usually want to have a API which allows me to Trace method enter and leave Trace messages with a severity like Info, Warning, Error When I do print a trace message it is very useful to print out method and type name as well. So your API must either be able to pass the method and type name as strings or extract it automatically via walking back one Stackframe and fetch the infos from there. The first glaring deficiency is that there is no CallerTypeAttribute yet because the C# compiler team was not satisfied with its performance.   A usable Trace Api might therefore look like   enum TraceTypes { None = 0, EnterLeave = 1 << 0, Info = 1 << 1, Warn = 1 << 2, Error = 1 << 3 } class Tracer : IDisposable { string Type; string Method; public Tracer(string type, string method) { Type = type; Method = method; if (IsEnabled(TraceTypes.EnterLeave,Type, Method)) { } } private bool IsEnabled(TraceTypes traceTypes, string Type, string Method) { // Do checking here if tracing is enabled return false; } public void Info(string fmt, params object[] args) { } public void Warn(string fmt, params object[] args) { } public void Error(string fmt, params object[] args) { } public static void Info(string type, string method, string fmt, params object[] args) { } public static void Warn(string type, string method, string fmt, params object[] args) { } public static void Error(string type, string method, string fmt, params object[] args) { } public void Dispose() { // trace method leave } } This minimal trace API is very fast but hard to maintain since you need to pass in the type and method name as hard coded strings which can change from time to time. But now we have at least CallerMemberName to rid of the explicit method parameter right? Not really. Since any acceptable usable trace Api should have a method signature like Tracexxx(… string fmt, params [] object args) we not able to add additional optional parameters after the args array. If we would put it before the format string we would need to make it optional as well which would mean the compiler would need to figure out what our trace message and arguments are (not likely) or we would need to specify everything explicitly just like before . There are ways around this by providing a myriad of overloads which in the end are routed to the very same method but that is ugly. I am not sure if nobody inside MS agrees that the above API is reasonable to have or (more likely) that the whole talk about you can use this feature for diagnostic purposes was not a core feature at all but a simple byproduct of making the life of INotifyPropertyChanged implementers easier. A way around this would be to allow for variable argument arrays after the params keyword another set of optional arguments which are always filled by the compiler but I do not know if this is an easy one. The thing I am missing much more is the not provided CallerType attribute. But not in the way you would think of. In the API above I did add some filtering based on method and type to stay as fast as possible for types where tracing is not enabled at all. It should be no more expensive than an additional method call and a bool variable check if tracing for this type is enabled at all. The data is tightly bound to the calling type and method and should therefore become part of the static type instance. Since extending the CLR type system for tracing is not something I do expect to happen I have come up with an alternative approach which allows me basically to attach run time data to any existing type object in super fast way. The key to success is the usage of generics.   class Tracer<T> : IDisposable { string Method; public Tracer(string method) { if (TraceData<T>.Instance.Enabled.HasFlag(TraceTypes.EnterLeave)) { } } public void Dispose() { if (TraceData<T>.Instance.Enabled.HasFlag(TraceTypes.EnterLeave)) { } } public static void Info(string fmt, params object[] args) { } /// <summary> /// Every type gets its own instance with a fresh set of variables to describe the /// current filter status. /// </summary> /// <typeparam name="T"></typeparam> internal class TraceData<UsingType> { internal static TraceData<UsingType> Instance = new TraceData<UsingType>(); public bool IsInitialized = false; // flag if we need to reinit the trace data in case of reconfigured trace settings at runtime public TraceTypes Enabled = TraceTypes.None; // Enabled trace levels for this type } } We do not need to pass the type as string or Type object to the trace Api. Instead we define a generic Api that accepts the using type as generic parameter. Then we can create a TraceData static instance which is due to the nature of generics a fresh instance for every new type parameter. My tests on my home machine have shown that this approach is as fast as a simple bool flag check. If you have an application with many types using tracing you do not want to bring the app down by simply enabling tracing for one special rarely used type. The trace filter performance for the types which are not enabled must be therefore the fasted code path. This approach has the nice side effect that if you store the TraceData instances in one global list you can reconfigure tracing at runtime safely by simply setting the IsInitialized flag to false. A similar effect can be achieved with a global static Dictionary<Type,TraceData> object but big hash tables have random memory access semantics which is bad for cache locality and you always need to pay for the lookup which involves hash code generation, equality check and an indexed array access. The generic version is wicked fast and allows you to add more features to your tracing Api with minimal perf overhead. But it is cumbersome to write the generic type argument always explicitly and worse if you do refactor code and move parts of it to other classes it might be that you cannot configure tracing correctly. I would like therefore to decorate my type with an attribute [CallerType] class Tracer<T> : IDisposable to tell the compiler to fill in the generic type argument automatically. class Program { static void Main(string[] args) { using (var t = new Tracer()) // equivalent to new Tracer<Program>() { That would be really useful and super fast since you do not need to pass any type object around but you do have full type infos at hand. This change would be breaking if another non generic type exists in the same namespace where now the generic counterpart would be preferred. But this is an acceptable risk in my opinion since you can today already get conflicts if two generic types of the same name are defined in different namespaces. This would be only a variation of this issue. When you do think about this further you can add more features like to trace the exception in your Dispose method if the method is left with an exception with that little trick I did write some time ago. You can think of tracing as a super fast and configurable switch to write data to an output destination or to execute alternative actions. With such an infrastructure you can e.g. Reconfigure tracing at run time. Take a memory dump when a specific method is left with a specific exception. Throw an exception when a specific trace statement is hit (useful for testing error conditions). Execute a passed delegate which e.g. dumps additional state when enabled. Write data to an in memory ring buffer and dump it when specific events do occur (e.g. method is left with an exception, triggered from outside). Write data to an output device. …. This stuff is really useful to have when your code is in production on a mission critical server and you need to find the root cause of sporadic crashes of your application. It could be a buggy graphics card driver which throws access violations into your application (ok with .NET 4 not anymore except if you enable a compatibility flag) where you would like to have a minidump or you have reached after two weeks of operation a state where you need a full memory dump at a specific point in time in the middle of an transaction. At my older machine I do get with this super fast approach 50 million traces/s when tracing is disabled. When I do know that tracing is enabled for this type I can walk the stack by using StackFrameHelper.GetStackFramesInternal to check further if a specific action or output device is configured for this method which is about 2-3 times faster than the regular StackTrace class. Even with one String.Format I am down to 3 million traces/s so performance is not so important anymore since I do want to do something now. The CallerMemberName feature of the C# 5 compiler is nice but I would have preferred to get direct access to the MethodHandle and not to the stringified version of it. But I really would like to see a CallerType attribute implemented to fill in the generic type argument of the call site to augment the static CLR type data with run time data.

    Read the article

1