Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why use singleton for application logging?

Tags:

c#

singleton

I was reading about the disadvantages of singleton patterns. A valid use of singleton suggested in many forums is the Logging application. I was wondering why this is a valid use of the pattern. Aren't we maintaing the state information in memory throughout the application?

Why not just use a function:

class Logger
{
    public static void Log(string message)
    {
         //Append to file

    }
}
like image 392
Nemo Avatar asked Mar 16 '12 02:03

Nemo


1 Answers

To answer "why not just use a function": this code works incorrectly in multi-thread logging. If two threads try to write the same file, an exception will be thrown. And this is why it's good to use singleton for logging. In this solution, we have a thread safe singleton container, other threads push messages(logs) into the container safely. And the container(always a thread-safe queue) writes the messages/logs into a file/db/etc one by one.

like image 178
Cheng Chen Avatar answered Oct 05 '22 23:10

Cheng Chen