Logging aspect

BLToolkit.NET

Business Logic Toolkit for .NET www.bltoolkit.net
 

This aspect allows logging some diagnostic information with minimum efforts. All you need to do is to decorate your class with the Log attribute. If you have a class hierarchy you can decorate only your base class. Diagnostic information will be logged for all virtual and abstract members of your abstract class.

LoggingAspect.cs
using System;
using System.Threading;

using NUnit.Framework;

using BLToolkit.Aspects;
using BLToolkit.Reflection;

namespace HowTo.Aspects
{
    [TestFixture]
    public class LoggingAspectTest
    {
        [Log]
        public abstract class TestClass
        {
            // Here we customize the logging settings.
            // This call will be logged in spite of default settings.
            //
            [Log(MinCallTime=50)]
            public virtual void Test1(int i)
            {
                Thread.Sleep(100);
            }

            // This call is not going to be logged (see default settings below).
            //
            public virtual void Test2(DateTime dt)
            {
                Thread.Sleep(100);
            }

            // By default exception calls are logged.
            //
            public virtual void Test3(string s)
            {
                throw new ApplicationException("Test exception.");
            }
        }

        [Test]
        public void Test()
        {
            // By setting MinCallTime to some value, we prevent logging any call
            // which is shorter than the provided value.
            //
            LoggingAspect.MinCallTime = 1000;

            TestClass t = TypeAccessor<TestClass>.CreateInstance();

            t.Test1(1);
            t.Test2(DateTime.Now);

            try
            {
                t.Test3("3");
            }
            catch
            {
            }
        }
    }
}

Here is the logging output.

4/20/2008 11:19:44 PM: HowTo.Aspects.LoggingAspectTest.BLToolkitExtension.TestClass.Test1(1) - 105 ms.

4/20/2008 11:19:46 PM: HowTo.Aspects.LoggingAspectTest.BLToolkitExtension.TestClass.Test3("3") - 1507 ms
                       with exception 'System.ApplicationException' - "Test exception.".
 
© 2010 www.bltoolkit.net
[email protected]