user209293
user209293

Reputation: 889

C# writing to log file

I want to write some events and exceptions to a log file when my app is running. The log file size is limited to N Megabytes. When the file size is more than N Megabytes, I want to overwrite from the start of the file. Since the file size is N megabytes I don't want to copy to temporary file and then rename it.

Give any suggestions/approach for the above problem.

Upvotes: 0

Views: 9857

Answers (7)

user1722368
user1722368

Reputation:

Why don't you try enterprise logging library from Microsoft which will give you many more features than the older FileIO operations or the log4net.

Microsoft has released 5.0 version of enterprise library, which will help you write logs and also configuring them easily with a UI, give it a try.

Upvotes: 0

vaitrafra
vaitrafra

Reputation: 662

float N = 1; //Log File size in MB
FileInfo logFile = new FileInfo("c:\\myLogFile.txt");
if (logFile.Length > 1024 * N)
{
   logFile.Delete();
   logFile.Create();
}

using (StreamWriter logStream = logFile.AppendText())
   logStream.Write("String to write");

the simpliest way, and probably the worst. Edited to reflect Hans Kesting comments.

Upvotes: 2

tsimbalar
tsimbalar

Reputation: 5990

Check out log4net ! It is really flexible and allows you to change the behaviour of logging at run-time (where to log / how to log / what to log ...).

The RollingFileAppender allows you to define the behaviour when a given size-limit is reached, and it could probably answer your question.

Upvotes: 2

Timur Sadykov
Timur Sadykov

Reputation: 11377

As alternative to Log4Net I can recommend NLog We find it more transparent and easy to use after own simple log class.

Upvotes: 1

Zephyr
Zephyr

Reputation: 7823

If your question refers to the .Net trace listener which writes .svclog files then the answer is no: you cannot configure it to start writing from the beginning when it reaches a certain limit.

However, Microsoft have a solution called Circular Tracing that you can try to circumvent the problem of log files growing without limit.

Upvotes: 0

Nicholas Mayne
Nicholas Mayne

Reputation: 1754

Either use Log4net (http://logging.apache.org/log4net/index.html) where you can do this

    logger.Debug("Here is a debug log.");
    logger.Info("... and an Info log.");
    logger.Warn("... and a warning.");
    logger.Error("... and an error.");
    logger.Fatal("... and a fatal error.");

or use the Enterprise Libaries (http://msdn.microsoft.com/en-us/library/ff648951.aspx) where you can do this

    LogEntry entry = new LogEntry()
                         {
                             Message = "Hello Ent. Lib. Logging"
                         };
    Logger.Write(entry);

Both can be configured to point to a file thru the web/app.config.

Upvotes: 2

TalentTuner
TalentTuner

Reputation: 17556

Try Log4Not , or Enterprise Library logging component by Microsoft

Upvotes: 2

Related Questions