How to disable / enable WCF tracing in C # application code

It took me a while to get this right, so I decided to share the decision, because it can save someone else a few days of trial and error.

Problem: I want to enable / disable WCF tracing in my C # .NET application and select a trace output file name. I do not want users to edit the .config file, there was too much room for errors.

Here is one solution.

.Config application file:

<?xml version="1.0"?> <configuration> <system.diagnostics> <trace autoflush="true"/> <sources> <source name="System.ServiceModel" switchValue="All"> <listeners> <add name="MyListener"/> </listeners> </source> <source name="System.ServiceModel.MessageLogging" switchValue="All"> <listeners> <add name="MyListener"/> </listeners> </source> <source name="System.ServiceModel.Activation" switchValue="All"> <listeners> <add name="MyListener"/> </listeners> </source> <source name="System.IdentityModel" switchValue="All"> <listeners> <add name="MyListener"/> </listeners> </source> </sources> <sharedListeners> <add name="MyListener" type="MyNamespace.MyXmlListener, MyAssembly"/> </sharedListeners> </system.diagnostics> <system.serviceModel> <diagnostics wmiProviderEnabled="true"> <messageLogging logEntireMessage="true" logMalformedMessages="true" logMessagesAtServiceLevel="true" logMessagesAtTransportLevel="true" maxMessagesToLog="1000" maxSizeOfMessageToLog="8192"/> </diagnostics> </system.serviceModel> <startup> <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.0"/> </startup> </configuration> 

My C # code:

 using System; using System.IO; using System.Diagnostics; namespace MyNamespace { public class MyXmlListener : XmlWriterTraceListener { public static String TraceOutputFilename = String.Empty; public static Stream MakeOutputStream() { if (String.IsNullOrWhiteSpace(TraceOutputFilename)) return Stream.Null; return new FileStream(TraceOutputFilename, FileMode.Create); } public MyXmlListener () : base(MakeOutputStream()) { } } } 

To include WCF tracing in a file, set TraceOutputFilename before creating the WCF object:

 MyXmlListener.TraceOutputFilename = "trace.svclog"; 

I got great benefits from this forum, I hope this post pays for it!

See Specifying fully identified type names for the correct type setting in the .config file.

0
source share

Source: https://habr.com/ru/post/1469305/


All Articles