C#簡単にログファイルを書くクラス

3365 ワード

 /// <summary>
    /// Log  。
    /// </summary>
    public sealed class Log
    {
        public Log()
        {
            //
            // TODO:  
            //
        }

        ~Log()
        {

        }

        static StreamWriter CreateLogFile(string FileName)
        {
            string Path = Application.StartupPath + "\\Log";
            if (!Directory.Exists(Path))
                Directory.CreateDirectory(Path);

            string FilePath = string.Format("{0}\\{1} {2:yyyyMMdd}.log", Path, FileName, DateTime.Today);

            if (!File.Exists(FilePath))
                return File.CreateText(FilePath);

            return File.AppendText(FilePath);
        }

        public static void WriteErrorInfo(string s, Exception ex)
        {
            lock (thisLock)
            {
                StreamWriter SW = CreateLogFile("Error");

                SW.WriteLine(DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss") + "  " + s);
                SW.WriteLine(ex.Message);
                SW.WriteLine(ex.StackTrace);
                Write(s);
            }
        }

        private static Object thisLock = new Object();
        public static void Write(string s)
        {
            string sFileName = null;
            StreamWriter SW;
            lock (thisLock)
            {
                sFileName = Application.StartupPath + "\\Log";
                if (!Directory.Exists(sFileName)) Directory.CreateDirectory(sFileName);

                sFileName = string.Format("{0}\\Log\\{1:yyyyMMdd}.log", Application.StartupPath, DateTime.Today);
                if (!File.Exists(sFileName))
                    SW = File.CreateText(sFileName);
                else
                    SW = File.AppendText(sFileName);
                SW.WriteLine(DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss") + "  " + s);
                SW.Close();
            }
        }

        public static void ThrowException(string ErrMsg)
        {
            Write(ErrMsg);
            throw new Exception(ErrMsg);
        }

        public static void Read(string filename, ref string sMsg)
        {
            string sFileName = null;

            sFileName = Application.StartupPath + "\\Log";
            if (!Directory.Exists(sFileName)) Directory.CreateDirectory(sFileName);

            sFileName = string.Format("{0}\\Log\\{1}", Application.StartupPath, filename); // + ".log"

            if (!File.Exists(sFileName)) return;
            
            StreamReader SR;
            string S;
            SR = File.OpenText(sFileName);
            S = SR.ReadLine();
            while (S != null)
            {
                sMsg += S + "\r
"; S = SR.ReadLine(); } SR.Close(); } }