Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Singleton Logging Class

I am trying to figure out the best strategy for logging on the async-IO web server I am working on. I thought the easiest way was to have a singleton class that keeps Filestreams open for the appropriate log files so I could just do something like:

Util.Logger.GetInstance().LogAccess(str);

Or something like that.

My class looks like this:

public sealed class Logger {
   private static StreamWriter sw;
   private static readonly Logger instance = new Logger();
   private Logger() {
      sw = new StreamWriter(logfile);
   }
   public static Logger GetInstance() {
      return instance;
   }
   public void LogAccess(string str) {
      sw.WriteLine(str);
   }
}

This is all just in my head really, and I'm looking for suggestions on how to make it better and also make sure I'm doing it properly. The biggest thing is I need it to be thread safe, which obviously it is not in its current state. Not sure of the best way to do that.

like image 300
The.Anti.9 Avatar asked Jul 13 '10 05:07

The.Anti.9


People also ask

What C is used for?

C programming language is a machine-independent programming language that is mainly used to create many types of applications and operating systems such as Windows, and other complicated programs such as the Oracle database, Git, Python interpreter, and games and is considered a programming foundation in the process of ...

Is C language easy?

C is a general-purpose language that most programmers learn before moving on to more complex languages. From Unix and Windows to Tic Tac Toe and Photoshop, several of the most commonly used applications today have been built on C. It is easy to learn because: A simple syntax with only 32 keywords.

What is the full name of C?

In the real sense it has no meaning or full form. It was developed by Dennis Ritchie and Ken Thompson at AT&T bell Lab. First, they used to call it as B language then later they made some improvement into it and renamed it as C and its superscript as C++ which was invented by Dr. Stroustroupe.

Is C programming hard?

C is more difficult to learn than JavaScript, but it's a valuable skill to have because most programming languages are actually implemented in C. This is because C is a “machine-level” language. So learning it will teach you how a computer works and will actually make learning new languages in the future easier.


1 Answers

This is taken care of for you automatically if you use NLog - you define all of your loggers in a .config file and then you access all of them via the static LogManager class, which is a Singleton.

Here's an example which illustrates the thread-safe nature of NLog:

https://github.com/nlog/nlog/wiki/Tutorial#Adding_NLog_to_an_application

like image 125
Aaronontheweb Avatar answered Sep 22 '22 14:09

Aaronontheweb