I'd like to be able to log message information in a database, and I'm trying to decide how best to do that. Is it possible to configure the WCF logging mechanisms to write to a database instead of a file? Thanks.
-
1Blog [Configuring WCF service to utilise Enterprise Library: Logging application to log data to database](http://weblogs.asp.net/sukumarraju/archive/2011/11/07/configuring-wcf-service-to-utilise-enterprise-library-logging-application-to-log-data-to-database.aspx) has step-by-step instructions, how to configure 'Database Trace listener' – Michael Freidgeim Sep 26 '12 at 12:32
3 Answers
You need to have two things:
- a proper config to enable .NET tracing
- a trace listener to capture the trace messages and store them in a database
For #1:
You need to turn on tracing in WCF first - you need an entry in <system.serviceModel>
that enables tracing:
<system.serviceModel>
<diagnostics>
<messageLogging
logEntireMessage="true"
logMalformedMessages="false"
logMessagesAtServiceLevel="true"
logMessagesAtTransportLevel="false"
maxMessagesToLog="300000"
maxSizeOfMessageToLog="200000"/>
</diagnostics>
</system.serviceModel>
Next, you need to configure .NET tracing as such:
<system.diagnostics>
<sources>
<source name="System.ServiceModel"
switchValue="Information, ActivityTracing"
propagateActivity="true">
<listeners>
<add name="xml" />
</listeners>
</source>
<source name="System.ServiceModel.MessageLogging">
<listeners>
<add name="xml" />
</listeners>
</source>
</sources>
<sharedListeners>
<add name="xml" type="WcfTrace.Trace.WebTraceListener,WcfTrace.Trace" />
</sharedListeners>
</system.diagnostics>
Here, instead of the WebTraceListener, or other pre-defined listeners, you can also plug in your own database-oriented trace listener.
For #2:
You can - of course - write your own SqlTraceListener
- or you can use one of the many ready-made solutions out there, for instance this one here (download the code from Codeplex).

- 732,580
- 175
- 1,330
- 1,459
If you don't need the whole SOAP-message, I would suggest to use log4net with custom IParameterInspector or IDispatchMessageInspector implementation, cause in this case you can write to log only what you need. Otherwise, take marc_s's solution.

- 2,537
- 2
- 19
- 27