Reputation: 1047
I've got a logging library that provides a GUI which allows end-users to enable/disable logging on a class-by-class basis. This allows support personel to have the end-user enable logging on classes of interest in solving a problem without flooding the log with junk we don't care about (there's a bit more to this, but it should suffice for purposes of this question). The GUI must list all of the classes which use the logging library.
The approach I've used in the past (in Win32 apps) was to provide a register function which users of the library would call to list the classes which use the library. This works, but is painful and error prone. Given that I'm working in .NET now, I was hoping that I could somehow get a list of these classes myself at runtime so I could populate the GUI without requiring registration.
Is there a way to accomplish this?
Upvotes: 1
Views: 207
Reputation: 23198
When we log, each class that wants to log creates a static instance of a logger for its type. Through this method you could track each instance as it's created and allow the user to disable logs as needed.
private static readonly ILog LOG = LogManager.GetLog(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
However, this naturally won't get fired until the static members of the class are loaded (I think when the class/type is first accessed) so I suppose it's plausible that you won't see a full listing of classes that would want to log until after they're all accessed.
Upvotes: 1
Reputation: 62093
4.5 - simple. Add the needed information as parameters to the called method, annotate them, the compiler does the rest.
Looks like this: private void OnPropertyChanged([CallerMemberName] String caller = null)
SADLY no class name ;) SO, out of luck also there.
Otherwise - no fast reliable way, sorry.
to enable/disable logging on a class-by-class basis.
What I do is have a generic logger FOR A class (Logger). This is open for errors, but it also allows me to log something for another class - for exampüle in a helper method - manually. About as good as it gets and QUITE standard (nlog has a similar mechanism).
Upvotes: 0
Reputation: 31394
Yes you can use reflection. The following code to list all classes (and structs) currently loaded:
foreach(Assembly asm in AppDomain.CurrentDomain.GetAssemblies()
foreach(Type type in asm.GetTypes()){
}
}
AppDomain.CurrentDomain.GetAssemblies() will list all of the assemblies loaded in the app domain and then use GetTypes() to list all of the classes and structs that the assembly contiains.
Upvotes: 0
Reputation: 34489
You could create a new StackTrace (this isn't just for exception reporting) but it isn't very speedy...
Upvotes: 0