Debajit Maji
Debajit Maji

Reputation: 11

how to take log file backup automatically

How to take automatically backup of a log file(.txt) when it's size reached a threshold level, say 5MB. The backup file name should be like (log_file_name)_(system_date) and original log file should be cleaned(0 KB).

Please help. Thanks in advance.

Upvotes: 1

Views: 344

Answers (1)

Mennan
Mennan

Reputation: 4497

Check your log file size using lenght().Then check if its bigger then 5mb call extendLogFile() func.

This is c# code u can easly convert to java

Size check:

if (size > 400 * 100 * 100)
{
   extendLogFile(Path);
}

Copy old log file in archive directory and create new log file:

private static void extendLogFile(string lPath)
{
        string name = lPath.Substring(0, lPath.LastIndexOf("."));
        string UniquName = GenerateUniqueNameUsingDate(); // create a unique name for old log files like '12-04-2013-12-43-00'

        string ArchivePath = System.IO.Path.GetDirectoryName(lPath) + "\\Archive";
        if (!string.IsNullOrEmpty(ArchivePath) && !System.IO.Directory.Exists(ArchivePath))
        {
            System.IO.Directory.CreateDirectory(ArchivePath);
        }

        string newName = ArcivePath + "\\" + UniquName;

        if (!File.Exists(newName))
        {

            File.Copy(lPath, newName + ".txt");

            using (FileStream stream = new FileStream(lPath, FileMode.Create))
            using (TextWriter writer = new StreamWriter(stream))
            {
                writer.WriteLine("");
            }
        }


 }

Upvotes: 1

Related Questions