Форматирование ApplicationData в Service Trace Viewer как XML
Я использую TraceSource
записать информацию в XmlWriterTraceListener
, Сообщение, которое я регистрирую, представляет собой XML, однако, когда я просматриваю сообщение в Service Trace Viewer, оно не отображается как XML, оно отображается как строка. Есть ли способ сделать это? Вот мой app.config
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<system.diagnostics>
<trace autoflush="true" />
<sources>
<source name="system.framework.db.utility" switchName="switchInformation">
<listeners>
<remove name="Default" />
<add name="arquivoXml" />
</listeners>
</source>
</sources>
<switches>
<add name="switchErro" value="Error"/>
<add name="switchInformation" value="Information"/>
</switches>
<sharedListeners>
<add name="arquivoXml"
type="System.Diagnostics.XmlWriterTraceListener"
initializeData="C:\Temp\trace.svclog">
</add>
</sharedListeners>
</system.diagnostics>
</configuration>
Ниже мой код:
namespace system.framework.db.utility.sqlserver
{
internal class SqlDBTransManager : IDBManagerConnection
{
private static readonly TraceSource ts = new TraceSource("system.framework.db.utility");
private void RunSqlInternal(String pSql, DBManagerParams pDBManagerParams, DBManagerConnection pTransac)
{
//Lots of code, and below is the log
StringBuilder sb = new StringBuilder(1000);
XmlWriterSettings settings = new XmlWriterSettings();
settings.ConformanceLevel = ConformanceLevel.Document;
using (XmlWriter xml = XmlWriter.Create(sb, settings))
{
xml.WriteStartDocument(true);
xml.WriteStartElement("log");
xml.WriteAttributeString("Método", "RunSql");
xml.WriteString(pSql);
xml.WriteEndElement();
xml.WriteEndDocument();
xml.Flush();
}
ts.TraceEvent(TraceEventType.Information, 1, sb.ToString());
oCommand.ExecuteNonQuery();
}
}
}
А ниже показано, как это отображается в Service Trace Viewer.
Есть ли так или иначе, что под <ApplicationData>
тег отформатирован как XML?
РЕДАКТИРОВАТЬ
Я открыл svcfile и увидел, что строка неправильно закодирована. Почему не так?
<ApplicationData><log Método="RunSql">drop procedure dbo.spfwug_in_controle_versao</log></ApplicationData>
2 ответа
Я смог сделать это сбрасывая TraceSource
и использование Enterprise Library 5.0. Это был XmlLogEntry
это решило мою проблему. Ниже приведен код:
internal class SqlDBTransManager : IDBManagerConnection
{
private void RunSqlInternal(String pSql, DBManagerParams pDBManagerParams, DBManagerConnection pTransac)
{
////Lots of code, and below is the log
XmlDocument doc = new XmlDocument();
XPathNavigator nav = doc.CreateNavigator();
using (XmlWriter xml = nav.AppendChild())
{
xml.WriteStartElement("log");
xml.WriteAttributeString("Método", "RunSql");
xml.WriteString(pSql);
xml.WriteEndElement();
xml.Flush();
}
XmlLogEntry entry = new XmlLogEntry();
entry.Xml = nav;
entry.Priority = 1;
entry.Categories = new String[] { "DB" };
entry.Severity = TraceEventType.Information;
Logger.Write(entry);
oCommand.ExecuteNonQuery();
}
}
После этого я настраиваю прослушиватель трассировки XML в файле web.config:
<configuration>
<configSections>
<section name="loggingConfiguration" type="Microsoft.Practices.EnterpriseLibrary.Logging.Configuration.LoggingSettings, Microsoft.Practices.EnterpriseLibrary.Logging, Version=5.0.414.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" requirePermission="true" />
</configSections>
<loggingConfiguration name="Logging Application Block" tracingEnabled="true"
defaultCategory="System.ServiceModel" logWarningsWhenNoCategoriesMatch="true">
<listeners>
<add name="XML Trace Listener" type="Microsoft.Practices.EnterpriseLibrary.Logging.TraceListeners.XmlTraceListener, Microsoft.Practices.EnterpriseLibrary.Logging"
listenerDataType="Microsoft.Practices.EnterpriseLibrary.Logging.Configuration.XmlTraceListenerData, Microsoft.Practices.EnterpriseLibrary.Logging"
fileName="c:\\temp\\trace_framework.svclog" traceOutputOptions="DateTime, Timestamp, ProcessId, ThreadId" />
</listeners>
<categorySources>
<add switchValue="All" name="System.ServiceModel">
<listeners>
<add name="XML Trace Listener" />
</listeners>
</add>
</categorySources>
<specialSources>
<allEvents switchValue="All" name="All Events">
<listeners>
<add name="XML Trace Listener" />
</listeners>
</allEvents>
<notProcessed switchValue="All" name="Unprocessed Category">
<listeners>
<add name="XML Trace Listener" />
</listeners>
</notProcessed>
<errors switchValue="All" name="Logging Errors & Warnings">
<listeners>
<add name="XML Trace Listener" />
</listeners>
</errors>
</specialSources>
</loggingConfiguration>
После этого отправляемый мной XML-файл правильно отформатирован как XML-файл в формате svclog.
Не нужно загромождать свой код корпоративной библиотекой; просто используйте метод TraceData() объекта TraceSource, передав XPathNavigator в качестве аргумента объекта:
TextReader reader = new StringReader(message);
var xml = new XPathDocument(reader).CreateNavigator();
this.traceSource.TraceData(TraceEventType.Information, -2, xml);