0

I have an application in .NET that I need to log. I want to log certain events and exceptions. I saw online that log4net was being heavily recommended for this purpose. I set it up to quickly begin logging to a txt file.

But this is not good enough for my purposes. From within my application, I'd like to be able to pull up a monitor which has a live listing of all the logs being generated.

If log4net the best approach for this? If not, what is?

I have no problem consuming the log events and finding my own way to display the data, I just don't know what the best way is to send the logging events to my monitor form.

Michael Mankus
  • 4,628
  • 9
  • 37
  • 63

1 Answers1

3

You may want to look at log2console, which is an excellent logging monitor compatible with log4net. It can listen to the log4net remoting appender and present the data quite nicely.

If you need to implement your own monitor from within the program, I would suggest trying out the MemoryAppender. There's some helpful info here (the question is actually a very nice tutorial)

As you can see, he has set up two appenders - one which is logging to file and one which is logging to the memory appender. In your monitor, you can get a handle to the appender using the following code:

Hierarchy hierarchy = LogManager.GetRepository() as Hierarchy;
MemoryAppender mappender = hierarchy.Root.GetAppender("MemoryAppender") as MemoryAppender;

And you can cycically get the new events in a background thread with mappender.GetEvents(), before clearing it with mappender.Clear(). Keep in mind that this is not thread safe, so creating a thread safe wrapper for your logging is probably a good idea.

Community
  • 1
  • 1
havardhu
  • 3,576
  • 2
  • 30
  • 42
  • What part is not thread safe? Are you saying that `GetEvents()` is not thread safe because there might be events getting logged? Same with `Clear()`? This seems to be exactly what I'm looking for, but the thread safe stuff has me concerned. My plan was to have a form with a forms timer that ticks every five seconds. Each five seconds I would call `GetEvents()` and then `Clear()`. Then I would display those events to the form and wait until the next timer tick. Are you saying this could be unsafe? – Michael Mankus Apr 25 '13 at 11:25
  • It is safe to use it multithreaded, but you might risk loosing some log messages if anything is logged in between the GetEvents call and the Clear call. If you make a wrapper for log4net where all logging + access to the appender is controlled by a lock {} then you'll be ok regardless – havardhu Apr 28 '13 at 08:08