Search code examples
c#loggingsystem.diagnostics

How to initialize logging in DLL


I have a DLL which will be used from a non-.NET application, so it doesn't appear that it will read a config file.
I've read solutions where you can code custom solutions to explicitly read the config from a DLL, but I don't see how to get the logging component to read that.
The config page for logging in System.Diagnostics claims that you can set everything from code. I have found how to create and add a listener.

    static LogFactory() {
        TextWriterTraceListener myListener = new TextWriterTraceListener("C:\\Logs\\app.log", "myListener");
        Trace.Listeners.Add(myListener);
        myListener.WriteLine("Test message.");
        Trace.WriteLine("Another test");
        myListener.Flush();
    }

The file is created but nothing gets written to it, either from this explicit write, or from any call to logging in the app. TRACE is set in the build options.


Solution

  • It's not clear from your question how exactly is the DLL going to be used from the non-.NET application and how they are communicating with each other, but ideally the DLL would not have its own log... It would write to the log of the main app that is consuming it.

    That means you would design your DLL in such a way that the consumer can provide you with a way to write to their logs (e.g. by passing an ILogger interface that are common/known by both DLL and host app, or at least a delegate of some kind e.g. Action<string>) through an agreed upon bootstrapping method that the host app would call as part of the bootstrapping of the app.

    If you do decide to have a separate logging for the DLL without cooperation with the host app, then you could try using a ModuleInitializer which is a special function you can add to your .NET assembly that runs when the assembly is loaded for the first time.

    As of this writing, an easy way to add ModuleInitializers to assemblies is through a Fody plugin called ModuleInit.

    As for emitting the logs from within your DLL (regardless of the approach above), you might want to consider Serilog or NLog which offer a much more rich logging capabilities compared to Trace.