views:

497

answers:

3

I have an existing .net service, and I want to configure it to write messages to a log file. I added in the following in the service configuration:

<system.diagnostics>
  <sources>
    <source name="My.Service" switchValue="All">
      <listeners>
        <add name="text" type="System.Diagnostics.TextWriterTraceListener" initializeData="c:\log.txt" traceOutputOptions="Timestamp"/>
      </listeners>
    </source>
  </sources>
</system.diagnostics>

The problem is that the log file becomes quickly very large, so I was wondering if it's possible to configure some sort of log rotation.
Since the process locks the file for writing, it's not possible to rotate it manually, say with a script periodically renaming the file, at least without stopping and restarting the service.

Thanks for any suggestion.

A: 

Could you have the log rotation built into the filename so that:

"c:\log.txt"

becomes:

"c:\logDDMMYYYY.txt"

This way the log automatically rolls over to a new file at the end of the day.

Richard
A: 

Maybe you may have a look at log4net a free and easy-to-use logging library for .NET. This library already includes log rotating.

Otherwise you'll have your service to "unlock" the file and/or log to a new file automatically.

Scoregraphic
Looks promising, but may those logger classes be configured as trace listeners?
Paolo Tedesco
It should...there is a TraceAppender class included. The good point, you may always extend the library and write your own appenders (= where and how log is written)
Scoregraphic
oh..I forgot to mention that the library is fully configurable through an separate config file
Scoregraphic
+2  A: 

There is the FileLogTraceListener that I think would do the trick. You can configure it to a daily or weekly interval.

If it's not enough then you will have to write your own tracelistener, just inherit from TraceListener and override the write methods.

jmservera
Thanks, that's exactly what I was looking for, but I had missed it completely! I wonder why it's defined in the Microsoft.VisualBasic assembly instead of System.Diagnostics, anyway, I would think that rotating logs is a fairly common need...
Paolo Tedesco