Most TraceSource
tracing examples show how it is done via configuration. I am trying to achieve this via code.
I have a simple assembly as follows:
using System;
using System.Diagnostics;
using System.Threading;
namespace TracingLib
{
public class AppTracer
{
public event EventHandler AppStarted;
public event EventHandler AppStopped;
private bool CancelRequested = false;
public void Start()
{
Thread thread = new Thread(new ThreadStart(() =>
{
if(AppStarted != null) AppStarted(this, new EventArgs());
TraceSource ts = new TraceSource("ThreadSource");
ts.TraceInformation("Thread Begins");
//ts.Flush();
int i = 0;
while (!CancelRequested)
{
ts.TraceInformation("i: {0}", i++);
//ts.Flush();
Debug.Print("i : {0}", i);
Thread.Sleep(5000);
}
if (AppStopped != null) AppStopped(this, new EventArgs());
}));
thread.Start();
}
public void Stop()
{
CancelRequested = true;
}
}
}
I am consuming this in a console application.
using System;
using System.Threading;
using TracingLib;
namespace caTracingLibImplementation
{
class Program
{
static void Main(string[] args)
{
AppTracer tracer = new AppTracer();
ManualResetEvent waiter = new ManualResetEvent(false);
tracer.AppStopped += (sender, e) =>
{
waiter.Set();
};
TraceSource ts = new TraceSource("ThreadSource");
ts.Listeners.Add(new ConsoleTraceListener());
var sw = new SourceSwitch("foo");
sw.Level = SourceLevels.Warning;
ts.Switch = sw;
tracer.Start();
Console.WriteLine("AppTracer started...");
Thread.Sleep(10000);
tracer.Stop();
Console.WriteLine("AppTracer stopped...");
Console.WriteLine("Waiting to stop...");
waiter.WaitOne();
Console.WriteLine("End of program");
}
}
}
If I try to enable tracing via the console application I cannot see the trace messages.