Majak
Majak

Reputation: 1633

C# library logging

I have implemented my own C# logger class using StreamWriter. In my application, I have public static instance of this logger and I'm able to log anything from any part of application code, like:

Program.logger.Write(LogLevel.Info, "Log test");

I have also some C# dll library which I'm using in application. The question is, am I able to add logging into library functions and link it somehow with application logger? I know about Trace class, but I don't know how to link it. I suppose that I have to trace in library functions, and then listen these traces in application code, but how?

I don't want to use any third-party libraries for logging.

Upvotes: 0

Views: 2168

Answers (1)

Yacoub Massad
Yacoub Massad

Reputation: 27861

There are many ways you can solve your problem. Here I describe how you can solve it through using the Trace class since this is the option you mentioned in your question. Please note that this might not be the best approach.

First create a custom TraceListener:

public class MyTraceListener : TraceListener
{
    public override void Write(string message)
    {
        //Here consume your static logger
    }

    public override void WriteLine(string message)
    {
        //Here consume your static logger
    }
}

Then, at the entry point of your application, register the listener like this:

Trace.Listeners.Add(new MyTraceListener());

Now if any code (even the ones in the library) use Trace.WriteLine like this:

Trace.WriteLine("From library");

You would be able to listen to that and forward it to your custom logger.

Upvotes: 1

Related Questions