Phil
Phil

Reputation: 2181

How do I integrate logging into .NET code contract

I am trying to wrap my head around .NET's code contract. When using code contract, how do I log the assert causing the method in question to fail. For example, look at this code:

  Public IsMatch(string x, string, y) 
{ 

    Contract.Assert(!string.IsNullOrWhiteSpace(x)); 
     Contract.Assert(!String.IsNullOrWhitespace(y));

       return x == y;
 }

Let say x = string.Empty. This will cause the method to fail. How do I log that the assert cause the method above to fail. I can have many asserts such as this in a large app and it would be nice to know which one is the trouble-maker.

Upvotes: 2

Views: 462

Answers (2)

Polity
Polity

Reputation: 15130

Look at: http://msdn.microsoft.com/en-us/library/system.diagnostics.contracts.contract.aspx

Basically as a second parameter you can specify a message.

That said, Contract.Assert is farely primitive. Post conditions can better be checked using Contract.Requires since its a requirement for your method.

Edit: Post conditions should ofcourse be pre conditions

Upvotes: 3

Merlyn Morgan-Graham
Merlyn Morgan-Graham

Reputation: 59111

When using code contract, how do I log the assert causing the method in question to fail?

If you're talking about logging, I assume you mean at runtime rather than static verification.

The asserts raise exceptions when they fail. You can write a try/catch block to log exceptions:

try
{
    bool result = SomeClass.IsMatch(x, y);
}
catch(Exception e)
{
    logger.Error(e.ToString()); // Use whatever logging mechanism here
    throw; // Note: Make sure you rethrow if you catch "Exception e"
}

This will get you the stack trace of the exception, which will point to the line where the assertion failed.

As Polity mentioned, you can also include a userMessage parameter on each assertion. That way your logs will contain custom error messages in addition to the stack trace.

If you need a good logger class, look at the NLog library.

Upvotes: 3

Related Questions