I've put together a short example of a trace listener I created. For this sample all messages are written to a SQL server table using the custom listener. Any error messages are also written to the console window.
My sample console application that creates trace messages
Code:
class CS_ConsoleApp
{
static void Main(string[] args)
{
for (int i = 0; i < 20; i++)
{
if (i >= 0 & i <= 2)
{
Trace.TraceError("{0} FOUND!!!!! THIS IS TERRIBLE!!!!.", i);
}
else
{
if (isPrime(i))
{
Trace.TraceInformation("{0} is prime.", i);
}
else
{
Trace.TraceWarning("{0} is not prime.", i);
}
}
}
Console.ReadLine();
}
static bool isPrime(int number)
{
if (number % 2 == 0) return false; //Even number
for (int i = 3; i < number; i += 2)
{
if (number % i == 0) return false;
}
return true;
}
App.Config
Code:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<system.diagnostics>
<trace autoflush="true">
<!-- Trace filters can be set to Information, Warning, Error-->
<listeners>
<!-- Write Messages to Console -->
<add name="consoleListener" type="System.Diagnostics.ConsoleTraceListener">
<filter type="System.Diagnostics.EventTypeFilter"
initializeData="Error" />
</add>
<!-- Implement Custom Listener -->
<add name="sqlListener"
type="SFHP.Automation.Tracing.SqlListener, Tracing, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null">
<filter type="System.Diagnostics.EventTypeFilter"
initializeData="Information"/>
</add>
</listeners>
</trace>
</system.diagnostics>
</configuration>
The class I created to handle (listen) for the messages
Code:
public class SqlListener : TraceListener
{
public override void TraceEvent(TraceEventCache eventCache, string source, TraceEventType eventType, int id, string format, params object[] args)
{
const string commandText = "INSERT INTO dbo.Logging(host, application, level, logInfo) VALUES (@host, @application, @level, @logInfo)";
if (this.Filter.ShouldTrace(eventCache, source, eventType, id, format, args, null, null) == true)
{
using (var con = new SqlConnection("server=SomeServer;database=SomeDatabase;trusted_connection=true"))
{
con.Open();
using (var cmd = new SqlCommand(commandText, con))
{
cmd.Parameters.Add("@host", System.Data.SqlDbType.VarChar).Value = System.Environment.MachineName;
cmd.Parameters.Add("@application", System.Data.SqlDbType.VarChar).Value = source; ;
cmd.Parameters.Add("@level", System.Data.SqlDbType.VarChar).Value = eventType.ToString();
cmd.Parameters.Add("@logInfo", System.Data.SqlDbType.VarChar).Value = string.Format(format, args);
cmd.ExecuteNonQuery();
}
}
}
}
public override void Write(string message)
{
throw new System.NotImplementedException();
}
public override void WriteLine(string message)
{
throw new System.NotImplementedException();
}
}