How to add custom attribute to tracelistener in Config file in wpf app

I have the following log file tracelistener that extends filelogtracelistener and it works fine and I can log messages, but I want to specify an additional custom attribute in this for example. MaxUsers and below - how it should look.

 <add name="myFileListener" 
      type="MyCustomFileLogTraceListener, Microsoft.MyTools.Connections" 
      BaseFileName="IncidentTracking"
      Location="LocalUserDirectory" MaxUsers="500" />

      

This attribute is currently normal, so the config file gives errors. How do I add a custom attribute like this and use it back in my code?

I think we can add a custom config section as a solution, but want to know if there is something and better solution out of the box?

+3


source to share


2 answers


As per this article, the TraceListener.Attributes> property gets the custom trace listener attributes defined in the application config file.

he also quotes:

Classes derived from the TraceListener class can add custom attributes by overriding the GetSupportedAttributes method and returning a string array of custom attribute names.

I was able to implement what you wanted by doing this example

string[] _supportedAttributes = new string[] { "MaxUsers", "maxusers", "maxUsers" };

/// <summary>
/// Allowed attributes for this trace listener.
/// </summary>
protected override string[] GetSupportedAttributes() {
    return _supportedAttributes;
}

/// <summary>
/// Get the value of Max Users Attribute 
/// </summary>
public int MaxUsers {
    get {
        var maxUsers = -1; // You can set a default if you want
        var key = Attributes.Keys.Cast<string>().
            FirstOrDefault(s => string.Equals(s, "maxusers", StringComparison.InvariantCultureIgnoreCase));
        if (!string.IsNullOrWhiteSpace(key)) {
            int.TryParse(Attributes[key], out maxUsers);
        }
        return maxUsers;
    }
}

      



This will allow me to add a custom attribute to the config file that looks like

<add name="myFileListener" type="MyCustomFileLogTraceListener, Microsoft.MyTools.Connections" 
      BaseFileName="IncidentTracking"
      Location="LocalUserDirectory" MaxUsers="500" />

      

Note:

The attribute collection is not populated from the configuration file until after you have completely instantiated your listener. You must make sure that it is called after your listener object is fully created, but before it is first used.

+2


source


There is no way to change the schema, so you need to add a custom section. There are many articles explaining how to do this, how to create this custom config section



-1


source







All Articles