views:

2549

answers:

4

I have a web application, that will log some information to a file. I am looking for a simple thread-safe non-blocking file logger class in c#. I have little experience with threading. I known there are great logging components out there like log4Net, Enterprise Library Logging Block, ELMAH, but I do not want an external dependence for my application. I was thinking about using this queue implementation http://www.codeproject.com/KB/cpp/lockfreeq.aspx

A: 

The FileStream.BeginWrite method pushes the write operation onto a thread that's managed by the system. That's the easy bit.

If you put your messages into a synchronized Queue, and have the EndWrite method pull the next item off the queue, then all your logging will be off-thread as far as the app is concerned.

The last step is to wrap putting messages onto the queue to set an event, so that if the queue is empty when EndWrite comes to look for the next message, it can wait for the event to be set.

Steve Gilham
+1  A: 

if you do not want to use external library, you can use Trace class

Ahmed Said
I would also vote for the Trace class when an external dependency is not required. Also, many of the developers just add components like Log4net and Enterprise Lib without considering the complexity of their application. The Debug and Trace classes in .NET can suffice for many small and medium sized apps. You can customize their behavior by changing the config entries or by writing your own TraceListener.
A9S6
A: 

I've done a simple logging mechanism in my project in the office.

I have a log class that is Shared (Static C#).

Inside this class I have a Synchronised Queue, and it has it's own thread.

Then inside this thread, I just have it use a AutoresetEvent with your own defined WaitTime (i use 250ms).

Then when this ResetEvent times out, I collect what is currently in the queue (using DeQueue) and write each on to the File.

Things to remember ... Have a class or struct that can hold the date when the Entry went in, rather than the time you wrote to disk, incase you choose a longer time to sleep your thread.

If you want your application to exit quickly expose a method that will Set the Event to drop it out of the sleep and exit gracefully.

Paul Farry
Can you show some code?
M4N
A: 

Take a look at this; it's simple, yet thread-safe and non-blocking.

Kaveh Shahbazian