简体   繁体   中英

Logging in C# application without using third party logger

I am working on a C# console application that is scheduled to run automatically using windows task scheduler. I want to log the info being run in that application step by step with timestamp.

I also need to make sure that the log file size doesn't exceed 10 MB and gets broken into new file when it happens. No more than 5 log file must be there ,if more than 5 files are there the oldest one must be auto deleted.

I am not allowed to use any 3rd party logger as Log4net etc. In such a case do I have a solution to this problem using any inbuilt Microsoft functionality or class. I am more than willing to use custom code. I am able to log the data but deleting and splitting the file is a bit of a problem, any pointer would help

To get the size of a file in C# use:

FileInfo fi = new FileInfo(logFilename);
var size = fi.Length;

size is the size of your file in bytes. To check it isn't greater than 5GB, check it against 5*1024*1024.

To rename the log file to an archive file use:

System.IO.File.Move(logFilename, archiveFileName);

The archive file name can be just your log file name with the date suffix or something simple like that.

Assuming you have all your log files in one folder, you can count how many using:

int fileCount = Directory.GetFiles(logFileFolder).Length;

To delete the oldest files (except the first five) use something like:

foreach (var fileInfo in new DirectoryInfo(logFileFolder)
    .GetFiles().OrderByDescending(f => f.LastWriteTime).Skip(5))
{
     fileInfo.Delete();
}

I think that is all you need. Wrap this up in a method that is called whenever you write a log statement.

If you want to use a Microsoft ready built library, then look at Enterprise Library . This contains a logging application block. I think you can also download the source code and build it yourself, which frees you from your restriction of downloading DLLs.

However, you can, of course, also download the source for other open source logging frameworks like NLog (which I recommend) and use them.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM