SelrekJohn
SelrekJohn

Reputation: 476

Service Logging not working

I am trying to add some logging functionality to a service, however I want it to create a new log, copy the old log into the new one and delete the original.

Sudo for ClearLog: if log1 full create log2, delete contents of log1

Please see code below, currently the ClearLog function is not doing what I want.

Can anyone see what I'm doing wrong?

        public static void WriteLog(string txt)
    {
        string fp = _AppPath + @"\Logging";
        try
        {
            File.AppendAllText(fp + @"\Log1.txt", txt);
        }
        catch (IOException iex)
        {
            Debug.Print("Error writing log" + iex.ToString());
        }
    }
    private static void ClearLog()
    {
        string fp = _AppPath + @"\Logging";
        try
        {
            if (!File.Exists(fp + @"\Log1.txt"))
            {
                WriteErrorLog("");
            }
            else
            {
                File.AppendAllText(fp + @"\Log1.txt", fp + @"\Log2.txt");
                File.Delete(fp + @"\Log1.txt");
                WriteLog("");
            }
        }
        catch (Exception ex)
        {
            WriteLog("Clear log failed " + ex.ToString());
        }
    }

Upvotes: 0

Views: 35

Answers (1)

PurpleSmurph
PurpleSmurph

Reputation: 2107

Try creating a public static field of the file path, as you're opening the same file twice it seems.

IE: public static string logfp = _AppPath + @"\Logging";

Then rename everything in those two functions logfp.

Improved example (can use paths in both or declared throughout)

        private static void ClearLog()
    {
        string logfp = _AppPath + @"\Logging";
        try
        {
            if (File.Exists(logfp + @"\Log2.txt"))
            {
                File.Delete(logfp + @"\Log2.txt");

                if (File.Exists(logfp + @"\Log1.txt"))
                {
                    File.Copy(logfp + @"\Log1.txt", logfp + @"\Log2.txt");
                    File.Delete(logfp + @"\Log1.txt");
                }
                else
                {
                    File.AppendAllText(logfp + @"\Log1.txt", "New Log created: " + DateTime.Now.ToString());//showing you when it was created
                }
            }
            else
            {
                File.Copy(logfp + @"\Log1.txt", logfp + @"\Log2.txt");
                File.Delete(logfp + @"\Log1.txt");
            }
        }
        catch (Exception ex)
        {
            WriteErrorLog("Clear log failed " + ex.ToString());
        }
    }

Upvotes: 1

Related Questions