C# – Log design approach

cdesignloggingobject-oriented-design

Logging was always a nightmare for me! Now I have to implement it again for a proxy system.
In this proxy application, some systems ask proxy system to call some other services.
What I have to log is

  • Request Time
  • Requester IP
  • Request Parameters as XML
  • Requested Service Name
  • Requested Service Method
  • Response Time
  • Response data as XML
  • Response Message (If any exception occurs it will logged as Message)

I considered to append two lines to my methods:

// Log Request
Task.Factory.StartNew(() => Logger.Log(RequestParameters.ToXML(),Assembly.GetCallingAssembly().FullName, MethodBase.GetCurrentMethod().Name, DateTime.Now));

// Invoke requested service and get response

// Log Response
Task.Factory.StartNew(() => Logger.Log(Response.ToXML(), DateTime.Now));

I also want to log nested transactions.

Assume a transaction contains a request and a response. A transaction may contains many other internal transactions. When I receive a request, I should register a transaction, and insert a request for it, later, when response received, I should update the transaction response. Please note that I'm trying to store request and response relationship for better tracking.

How can I safely add this logging procedure to methods? I want to restrict developers to implement this logging systems in all methods, some thing like interface or inheritance for method body is required. Can I do this by attributes? Then how?

Best Answer

To restrict developers to use the logging mechanism for anything they want, make its visibility only internal. You can then make it available only to your own projects by adding the InternalsVisibleTo assembly attribute.

To safely and uniformly add the logging mechanism to methods, implement only the functionality in the methods, and wrap the methods in delegates, somewhat like in the following C# like pseudocode:

internal Func<RequestParameters, Response> WrapServiceClientWithLogger(Func<RequestParameters, Response> callService)
{
    return requestParameters => {
        // Log Request
        Task.Factory.StartNew(() => Logger.Log(requestParameters.ToXML(),
            Assembly.GetCallingAssembly().FullName, GetMethodName(callService), 
            DateTime.Now));

        var response = callService(requestParameters);

        // Log Response
        Task.Factory.StartNew(() => Logger.Log(Response.ToXML(), DateTime.Now));
        return response;
    }
}
Related Topic