2
votes

I have created a custom Exception that has data pertaining to our application. I want to ensure this data gets logged when an exception is thrown and logged to the event log.

I have tried creating a custom TextFormatter which is being called but am not sure how to access the current exception so I can add our custom information to the log entry.

There is something I am not understanding and would appreciate any help around adding custom tokens (and data) to Enterprise Library 5.0 TextFormatters.

Thanks, ...Marc

2

2 Answers

2
votes

You could extend TextFormatter. I think the issue there is that TextFormatter formats a LogEntry:

public override string Format(
    LogEntry log
)

So you need to get your custom data into the LogEntry. (Which I think is what your question is asking.)

An alternative (and I think simpler) approach is to use the ExtendedProperties of LogEntry. If you are using the Exception Handling Block (EHAB) to log your exception then you can add all of your custom information to the IDictionary Data property. At runtime, the contents of the Data dictionary are added to the ExtendedProperties. Specific properties can then be logged by using tokens in the formatter definition.

e.g.

public class MyException : Exception
{
    private string myCustomProperty;

    public string MyCustomProperty
    {
         get
         {
             return myCustomProperty;
         }
         set
         {
             myCustomProperty = value;
             Data["MyCustomProperty"] = value;
         }
    }
}

Then you can handle the exception using EHAB with a logging policy:

ExceptionPolicy.HandleException(ex, "Logging Exception Handler");

In your template add something like the following:

MyCustomProperty: {keyvalue(MyCustomProperty)}

This will then log your custom property.

If you are not using EHAB then you could not set the Data value in your exception class and then create small helper class to add your custom property to the ExtendedProperties:

public void LogException(Exception ex)
{
    LogEntry logEntry = new LogEntry();
    //...
    logEntry.ExtendedProperties.Add("MyCustomProperty", ex.MyCustomProperty);

    Logger.Write(logEntry);
}

If logging of custom exception properties is a general problem for you then you could add all of your custom properties to the Data dictionary and then in the helper method copy all of the Data key/value pairs to the ExtendedProperties.

1
votes

Lab2 of the Extensibility Hands-On Labs provides step-by-step guidance on building custom tracelistener and text formatters.