Skip to content

Instantly share code, notes, and snippets.

@ArseniySavin
Created September 22, 2016 08:33
Show Gist options
  • Save ArseniySavin/28b4bb0d21ba0b051c0c19323f09da5f to your computer and use it in GitHub Desktop.
Save ArseniySavin/28b4bb0d21ba0b051c0c19323f09da5f to your computer and use it in GitHub Desktop.
TraceListener with writing message to data base
/* Config setting
<configuration>
<system.diagnostics>
<sources>
<source name="System.ServiceModel.MessageLogging">
<listeners>
<add name="xml" />
</listeners>
</source>
</sources>
<sharedListeners>
<add name="xml"
type="<Namespace>.DataBaseWriterTraseListiner, <Assembly name>, Version=1.0.0.0, Culture=neutral, PublicKeyToken=<Token key | null>"
initializeData="DB" />
</sharedListeners>
</system.diagnostics>
<system.serviceModel>
<diagnostics wmiProviderEnabled="true">
<endToEndTracing propagateActivity="true" />
<messageLogging
logEntireMessage="true"
logMalformedMessages="false"
logMessagesAtServiceLevel="false"
logMessagesAtTransportLevel="true"
>
</messageLogging>
</diagnostics>
</system.serviceModel>
</configuration>
*/
public class DataBaseWriterTraseListiner : TraceListener
{
string action;
Guid messageID = Guid.Empty;
const string REGEX_PATTERN = @"[.\w]+$";
const string ENVELOP = "Envelope";
const string ACTION = "Action";
const string MESSAGEID = "MessageID";
public DataBaseWriterTraseListiner()
{
}
public DataBaseWriterTraseListiner(string name)
: base(name)
{
if(name != "DB")
throw new NotImplementedException("The saving trace message to file not implemented!");
}
public override void Write(string message)
{
}
public override void WriteLine(string message)
{
string parseMessage = string.Empty;
string actionAttribute = string.Empty;
string source = string.Empty;
XDocument xDoc = XDocument.Parse(message);
List<XElement> docList = xDoc.Descendants().ToList<XElement>();
if(docList.Exists(m => m.Name.LocalName == ENVELOP))
{
source = xDoc.Root.FirstAttribute.NextAttribute.Value;
if(docList.Exists(m => m.Name.LocalName == ACTION))
{
action = docList.SingleOrDefault(m => m.Name.LocalName == ACTION).Value;
}
if(Regex.IsMatch(action, REGEX_PATTERN))
actionAttribute = Regex.Match(action, REGEX_PATTERN, RegexOptions.IgnoreCase).Value;
if(docList.Exists(m => m.Name.LocalName == MESSAGEID))
{
if(!messageID.Equals(docList.SingleOrDefault(m => m.Name.LocalName == MESSAGEID).Value))
{
messageID = Guid.Parse(docList.SingleOrDefault(m => m.Name.LocalName == MESSAGEID).Value.Replace("urn:uuid:", string.Empty));
}
}
parseMessage = docList.Elements().Single(m => m.Name.LocalName == ENVELOP).ToString();
WriteTraceToDB(source, actionAttribute, action, parseMessage);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment