Elad
Elad

Reputation: 83

Auto log an exception c#

I'm writing an automation (test project) by vs2010. I already have a Logger class with the relevant Info(string), Debug(string) and Error(string, Exception) methods which implements the proper writing messages into file.

Now, I understand that my Info log has to be specifically written within my tests' code, but is there anyway to auto write the error messages as the implementation of the thrown exceptions? The exceptions are part of the design (I need to throw them in order to determine the pass/fail state of each test).

I can do the basic implementation of wrapping all my code in try-catch, write in the catch block the Logger.error(), then throw the exception again, like this:

public class Test
{
    ["TestMethod"]
    public void RunTest()
    {
        try
        {
            //run my code here
        }
        catch (Exception ex)
        {
            Logger.Error("Error message", ex);
            throw;
        }
    }
}

But I'm not sure using try-catch in order to log errors is a proper design.

I've thought of two things:

  1. Create a listener-thread which will catch my exceptions, log them and re-throw them...
  2. Manipulate the Exception class to use mt Log.Error() (or derive MyException from it and manipulate my code to throw only MyException).
  3. I've already tried to install the Enterprise-Library and using the logging-block, but I'm not sure this will suit my needs (and I've failed to get the instance of the LogWriter or use the Logger.Write anyway).

Am I in the right way? Are there any other ways to implement such an "auto write errors"?

Thanks, Elad

Upvotes: 2

Views: 3883

Answers (2)

Osa E
Osa E

Reputation: 1781

One possible way to satisfy your requirement is to wrap your function and methods with logic to handle logging/instrumentation. You can make your test classes all extend a custom base class or just create a utility class and call the wrap functionality. See example below.

Utility class

class Utility
{
    public static void Wrap(Action method, params object[] parameters)
    {
        try
        {
            //additional logging / events - see example below
            Debug.WriteLine("Entering : {0} @ {1}", method.Method.Name, DateTime.Now);
            foreach (var p in parameters)
            {
                Debug.WriteLine("\tParameter : {0}", new object[] { p });
            }


            method();
            //additional logging / events - see example below
            Debug.WriteLine("Exiting : {0} @ {1}", method.Method.Name, DateTime.Now);
        }
        catch (Exception ex)
        {
            //Log exception
            throw;
        }
    }


    public static T Wrap<T>(Func<T> method, params object[] parameters)
    {
        try
        {
            //additional logging / events - see example below
            Debug.WriteLine("Entering : {0} @ {1}", method.Method.Name, DateTime.Now);
            foreach (var p in parameters)
            {
                Debug.WriteLine("\tParameter : {0}", new object[]{p});
            }

            var retValue = method();
            //additional logging / events - see example below
            Debug.WriteLine("Exiting : {0} @ {1}", method.Method.Name, DateTime.Now);
            return retValue;
        }
        catch (Exception ex)
        {
            //Log exception
            throw;
        }

    }
}

Sample usage

public static void SayHello()
    {
        Utility.Wrap(() =>
            {
                SayHello(" world ");
            });
    }

    public static void SayHello(string name)
    {
        Utility.Wrap(() =>
        {
            Console.WriteLine("Hello {0}", name);
        }, name);
    }

    public static int GetCount(string s)
    {
        return Utility.Wrap(() =>
        {
            return string.IsNullOrEmpty(s) ? 0 : s.Length;
        }, s);
    }

Upvotes: 1

JMan
JMan

Reputation: 2629

You should only implement try-catch blocks on the highest level possible in your application. There you can handle your exception and log it.

For unhandled exceptions you can hook up an event, for example: AppDomain.CurrentDomain.UnhandledException

In Asp you can use the On_Error. It depends on the type of the project.

Upvotes: 0

Related Questions