Wednesday, September 12, 2012

Nifty little logging function for .NET code

This is not directly related to FIM 2010, but thought I'd share it anyway.

Whenever I write some code (workflows, Management Agents or such), I like to add a little logging. Usually I make sure that it can be switched on and off through a registry key.

In the log, it's nice if you can see just where in the code processing is taking place. Instead of hard coding function names, I use the little function below to get me a string of the current function names.


        public static string GetEntryPointName()
        {
            StackTrace trace = new StackTrace();
            int index = 0;
            string str = null;
            for (index = trace.FrameCount - 2; index >= 2; index += -1)
            {
                if (str != null)
                {
                    str = str + "->";
                }
                str = str + trace.GetFrame(index).GetMethod().Name;
            }
            trace = null;
            return str;
        }

You'll need to include System.Diagnostics to use the StackTrace method.

Throughout my code, I now just put something similar to this -

Log(string.Format("{0}: {1}", GetEntryPointName(), logMessage);

The output in the logging is similar to this (this is a snippet from a log file for my PowerShell Management Agent) -


InvokeBeginImportWorker->OpenImportConnection->Log InvokeBeginImportWorker->OpenImportConnection: Enter
InvokeBeginImportWorker->OpenImportConnection Getting schema
InvokeBeginImportWorker->OpenImportConnection Type: user
InvokeBeginImportWorker->OpenImportConnection Anchor attribute: objectGuid
InvokeBeginImportWorker->OpenImportConnection Attribute: objectSid
InvokeBeginImportWorker->OpenImportConnection Attribute: homeDirectory
InvokeBeginImportWorker->OpenImportConnection Attribute: sAMAccountName
InvokeBeginImportWorker->OpenImportConnection Attribute: sn
InvokeBeginImportWorker->OpenImportConnection Attribute: givenName
InvokeBeginImportWorker->OpenImportConnection Attribute: objectGuid
InvokeBeginImportWorker->OpenImportConnection Attribute: displayName
InvokeBeginImportWorker->OpenImportConnection Got schema
InvokeBeginImportWorker->OpenImportConnection->InitializeConfigParameters->Log InvokeBeginImportWorker->OpenImportConnection->InitializeConfigParameters: Enter


Now, go log your pants off...

No comments:

Post a Comment