4

I need to modify the <configuration><system.diagnostics> section of an app.config at runtime so that I can:

  1. add a CustomTraceListener under the <sharedListeners> element, which requires special initializeData that can only be ascertained at runtime.

  2. add the CustomTraceListener shared listener to an existing source under the <source><listeners> element.

  3. persist the CustomTraceListener to other assemblies which load their trace source and listener configurations from the config file.

The relevant sections in app.config looks something like this presently:

<system.diagnostics>
  <sources>
    <source name="mysource" switchName="..." switchType="...">
      <listeners>
        <add name="console" />
        <add name="customtracelistener" /> /// need to add new listener here
      </listeners>
    </source>
  </sources>
  <sharedListeners>  
    <add name="console" type="..." initializeData="..." />
    <add name="customtracelistener" type="..." initializeData="..."> /// need to add custom trace listener here 
      <filter type="..." initializeData="Warning"/> /// with a filter
    </add>
  </sharedListeners>
  <switches>
    <add name="..." value="..." />
  </switches>
</system.diagnostics>

Using ConfigurationManager I can easily do:

Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
ConfigurationSection diagnostics = config.GetSection("system.diagnostics");

And when I do this, diagnostics is a System.Diagnostics.SystemDiagnosticsSection type. Interestingly I can't cast diagnostics to a SystemDiagnosticsSection type because I can't find it within any namespace. Regardless, ConfigurationSection doesn't seem to have any methods that I can use to write data into the section.

I also can't cast it to a NameValueConfigurationCollection because diagnostics base type is ConfigurationSection. I heard about this technique but it seems I can't use it.

Do I have to revert to using plain-old XML to accomplish this? I really don't like reinventing the wheel.

3 Answers 3

5

You can locate the path to the app.exe.config file through the ConfigurationManager, then load the config file as an XDocument.

string configPath = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None).FilePath;

XDocument config = XDocument.Load(configPath);
XElement diagnostics = config.Descendants().FirstOrDefault(e => e.Name == "system.diagnostics");

if (diagnostics == default(XElement))
{
    /// <system.diagnostics> element was not found in config
}
else
{
    /// make changes within <system.diagnostics> here...
}

config.Save(configPath);

Trace.Refresh();  /// reload the trace configuration

Once the required changes are made, save the XDocument back to disk, and call Trace.Refresh() to reload the trace configuration.

See MSDN regarding the Trace.Refresh method here.

1
  • How do it in WCF Service ? config.Save restart IIS site ?
    – Kiquenet
    Mar 20, 2019 at 15:09
2

For experience i would warn you to make app.config changes from application if the app is deployed with a good install procedure under protected directories, eg. Program files in MS OS with UAC activated.

To update config files sometimes you need some admin privileges.

The Bad thing is than all run correctly under visual studio / debug or some test procedure, after deploy, in production,you may have some issue...

0

If you make direct changes to the <configuration><system.diagnostics> section of the app.config file at run time, the app needs to be restarted or Trace.Refresh() must be called to have the changes take effect.

Another option is to programmatically add TraceListeners at application start-up, e.g. Trace.Listeners.Add(new TextWriterTraceListener("output.log", "myListener"));

see https://msdn.microsoft.com/en-us/library/sk36c28t(v=vs.110).aspx.

To add a filter with the initializeData value as in your question you can use the TraceListener.Filter property

To share settings across applications you can use the configSource property on the <system.diagnostics> element and put that element in a separate config file. The downside of this is that the file needs to be in the same folder as the app.config. So a change to one file would either need to be copied and pasted to other locations or shared in some other way.

An alternative would be to save a custom config file containing the trace listener information at a location all apps can access and then in each app load the file at start-up and configure the trace listeners as above.


Update

To share logging throughout your application you could create a class that implements the singleton pattern to return your TraceSource instance or to wrap your logging activities. This way you don't have to pass round the same instance

public class Logger
{
    private static Logger _logger;
        private TraceSource _ts;

        private Logger()
        {
        // Configure TraceSource here as required, e.g.
            _ts = new TraceSource("StackOverflow", SourceLevels.All);
            _ts.Listeners.Add(new TextWriterTraceListener(@"c:\temp\tracefile.log"));
        }

        public static Logger Get()
        {
            if (_logger == null)
            {
                _logger = new Logger();
            }

            return _logger;
        }

        public void TraceInfo(string message)
        {
            _ts.TraceInformation(message);
            _ts.Flush();
        }
}

// To use
Logger.Get().TraceInfo("This is a trace message");

You could extend this to then encapsulate the actual messages you want to log so that the code doing the logging doesn't know the specifics and you have just one place where your events are defined, e.g.

public void TraceApplicationStarting()
{
    _ts.TraceEvent(TraceEventType.Verbose, 1, "Application Starting");
}
6
  • Hi David thanks for your response. You're not correct however when you say that you can't apply the changes to a running application - you only have to call Trace.Refresh() and the configuration will be reloaded. This week I have been able to load the configuration file as an XDocument and make the required changes, save the app.exe.config file back to disk, and reload the trace configuration dynamically. Unfortunately I still haven't found a way to do this directly through ConfigurationManager.
    – khargoosh
    Feb 27, 2016 at 0:26
  • I think you also misunderstood my point 3 - I'm not interested in sharing the trace configuration across applications, only across assemblies referenced by a single application. By doing this you can instance a trace source within classes in a dll and they will load the applications trace configuration as specified in the app.exe.config. If you only add a new TraceListener programatically without modifying the config file, the assemblies have no visibility to this, unless you pass around TraceSource to every class instance.
    – khargoosh
    Feb 27, 2016 at 0:30
  • How are you writing trace messages? Adding a new trace listener programmatically applies to all referenced assemblies. I have just confirmed this with a simple console app referencing a separate project and calling Trace.TraceInformation from both the main app and the referenced project, with no configuration in app.config at all. Examining the Trace.TraceListeners collection in the referenced assembly shows the listener I added programmatically
    – David
    Feb 29, 2016 at 16:28
  • It looks like you are using the static Trace class however I'm using an instance of the TraceSource class - as recommended on MSDN here. With TraceSource an instance is required, so I have to either create an instance in each class which requires tracing (which loads configuration from the file) or pass around an instance to every class which is less practical.
    – khargoosh
    Feb 29, 2016 at 21:25
  • See update to answer for a way to share through code base
    – David
    Mar 2, 2016 at 14:54

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.