Click here to Skip to main content
15,885,982 members
Please Sign up or sign in to vote.
3.00/5 (1 vote)
See more:
Hi,

I am writing code to create log files in C#.
I am finding difficulties in implementing below

Once the file size exceeds 100 MB, a new file should be created and the name of the new file should be appended with -1 (say LogFile-1.log) and all the logging should happen in the new file.

My problem is that, how do I find out, which is the current log file and if the current log file size exceeds the limit, a new file should be created and subsequent logging should happen in the new file.

below is my code

if (!File.Exists(fileName))
{
    // Create the file.
    fs = File.Create(fileName);
    fs.Close();
}

//Open file
fs = File.Open(fileName, FileMode.Append, FileAccess.Write);
Publish(obj);// this method writes the data into the file

Code sample will be helpful.
Can someone please help me?
Thanks

Regards

[edit]Code block added, "Ignore HTML..." option disabled - OriginalGriff[/edit]
Posted
Updated 28-Feb-11 20:24pm
v4

This is more complex than it needs to be, because you want to keep the existing file and start a new one with a different name.

As a result, the fileName you are using may not be the name of the file you are saving to, and you have to assume that it isn't because you don't know if you can pass a new name "back up the chain" - the code may be:
Log(@"C:\Logs\LogFile.txt", MyLogMessage);
Which mean it will be the same each time the Log method is called. This means that every time to try to log something, you must search for all files in the specified directory which match the file name given, and a have any number of "-1"s appended to them. You can then add your log entry to the last one.

For example:
Original File : LogFile.txt
It filled up, so you create LogFile-1.txt and have to fill that.
It fills up, so you create LogFile-1-1.txt and start filling that.
And so on.

If you must it this way then you have a small and annoying job on your hands!
Instead, I would work like this:
File the base file until it is full (100mb).
Rename base file with a prefix for the current date and time, in YYYYMMDDHHmmss format.
Create a new log file, and work from that.

It is easier to find the order the files should go in, and easier to find a specific entry if you know when it was logged. And a whole lot easier to log an entry!
 
Share this answer
 
Comments
maheshk_blr 1-Mar-11 4:07am    
Thanks, nice approach
How I would do this:
if(!File.Exists(filename)) //No File? Create
{
    fs = File.Create(filename);
    fs.Close();
}
if(File.ReadAllBytes().Lenght >= 100*1024*1024) // (100mB) File to big? Create new
{
    string filenamebase = "myLogFile"; //Insert the base form of the log file, the same as the 1st filename without .log at the end
    if(filename.contains("-")) //Check if older log contained -x
    {
         int lognumber = Int32.Parse(filename.substring(filename.lastIndexOf("-")+1, filename.Length-4); //Get old number, Can cause exception if the last digits aren't numbers
         lognumber++; //Increment lognumber by 1
         filename = filenamebase + "-" + lognumber + ".log"; //Override filename
    }
    else 
    {
         filename = filenamebase + "-1.log"; //Override filename
    }
    fs = File.Create(filename);
    fs.Close();
}


This will check if the log exists with the filename given in the class (Would be best to safe the filename, else you could make it a string function returning the filename and then use it in the log append function. But it would just avoid it as you got to safe the earlier used filename somewhere with this method.
public string sLogname(string filename)
{
    //Code which alters filename
    return filename;
}

So I suggest to use it in this form:
class Logger {

    string filename;

    public Logger(string basefilename)
    {
        filename = basefilename;
    }

    void Publish(Object obj)
    {
         checkLogFile();
         //Coding of Publish
    }
    
    void checkLogFile()
    {
        //Code of first example
    }
}

Note that I wrote all code with-out checking if it doesn't contain compile errors.
 
Share this answer
 
In addition to above answers you can also read this[^] article
 
Share this answer
 
To answer another Question, I provided advanced and detailed code snapshot, please see: How to create event log under a folder[^], also read discussion to understand the usage.

—SA
 
Share this answer
 
v3

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900