I am writing an add-in for Solidworks. Because this is not a standalone program, but is only executed inside a running instance of Solidworks, debugging alone is kind of frustrating.
So, and because it is a good thing to do anyways, I started logging data using TraceSources and TraceListeners.
My add-in consists of several classes (not a big deal), so the usual approach would be to define TraceSources in every class and use a config file to assign the same listener to these sources. However, since this add-in is a dll and does not run as a standalone, I cannot use a config file. Therefore, I use a Singleton to configure the Listeners in code:
public sealed class CustomTracer
{
private static volatile CustomTracer instance;
private static object syncRoot = new Object();
private TextWriterTraceListener textListener;
public TraceListener Listener
{
get => textListener;
}
private bool _configured;
public bool Configured
{
get => _configured;
}
public static CustomTracer Instance
{
get
{
if (instance == null)
{
lock (syncRoot)
{
if (instance == null)
instance = new CustomTracer();
}
}
return instance;
}
}
private CustomTracer(string logpath = "c:/temp/SwPUMCINAddin.log")
{
textListener= new TextWriterTraceListener(logpath);
Trace.AutoFlush = true;
}
}
and then simply use them in every class:
class SampleClass
{
private static readonly TraceSource Tracer = new TraceSource("MyTracer");
public SampleClass()
{
SetUpTrace();
}
private void SetUpTrace()
{
CustomTracer Listener = CustomTracer.Instance;
var sourceSwitch = new SourceSwitch("SourceSwitch", "Verbose");
Tracer.Switch = sourceSwitch;
Tracer.Listeners.Add(Listener.Listener);
}
}
This approach works fine, but know I have the location of the logfile hardcoded. This is - IMHO - 1) ugly and 2) might fail if the directory does not exist or the user does not have write permisson.
I would like to store the logfile in the current working directory of Solidworks. However, the addin is most likely loaded when Solidworks starts. The current working directory however changes when a different document is loaded (the singleton is already instantiated then).
What would be the best approach to log the contents of all the classes into the same logfile in the cwd without using a config file?