save Debug To Log - CSharp System.IO

CSharp examples for System.IO:StreamWriter

Description

save Debug To Log

Demo Code


using System.Text;
using System.Linq;
using System.IO;//from  w  w w.  j  av  a 2 s. c om
using System.Collections.Generic;
using System;

public class Main{
        public static void saveDebugToLog(string information)
        {
            DateTime debugTime = DateTime.Now;
            string previousLogContent;

            // Trying to open exist log file and copy it contents.
            try
            {
                StreamReader fileContentCopy = new StreamReader("Logs/debug/" + debugTime.ToShortDateString() + ".log");
                previousLogContent = fileContentCopy.ReadToEnd();
                fileContentCopy.Close();
            }
            catch
            {
                previousLogContent = "";
            }

            // Recreating log contents and adding new enter.
            StreamWriter logSaver = new StreamWriter("Logs/debug/" + debugTime.ToShortDateString() + ".log");
            logSaver.WriteLine(previousLogContent);
            logSaver.WriteLine(debugTime.ToLocalTime().ToLongTimeString() + " - debug adnotation: ");
            logSaver.WriteLine("Message: " + information + "\n");
            logSaver.Close();
        }
}

Related Tutorials