網頁用Log方法彙總

工作上常用的文字Log方法,Debug的時候需要抓流程跑到哪一段出錯或是要記錄參數資料可以使用

1.Winform應用程式使用

#region Logs
        private void WriteLog(string Desc)
        {
            //資料夾 : /Log/
            SavePath = Application.StartupPath + "/Log/";
            //檔案名稱 : 20070801Log.txt
            FileName = DateTime.Now.ToString("yyyyMMdd") + "Log.txt";
            try
            {
                //檢查:資料夾是否存在(若沒有則建立它)
                bool folderExists;
                folderExists = Directory.Exists(SavePath);
                if (folderExists == false)
                {
                    Directory.CreateDirectory(SavePath);
                }
                //檢查:檔案是否存在(若沒有則建立它)
                bool fileExists;
                fileExists = File.Exists(SavePath + FileName);
                if (fileExists == false)
                {
                    File.WriteAllText(SavePath + FileName, string.Empty);
                }

                File.WriteAllText(SavePath + FileName, Desc + "\r\n");
            }
            catch (Exception ex)
            {
                rtbInfo.Text = rtbInfo.Text + ex.Message + "\r\n";
            }
        }
        #endregion

2.網頁用純文字Log

#region Logs
        /// <summary> 
        /// 紀錄資料純放文字檔 <para></para>  
        /// 只會刪除存放天數小於6個月的txt檔案 
        /// </summary> 
        /// <param name="Msg">訊息</param>  
        public static void LogTxt(string Msg)
        {
            if (!string.IsNullOrEmpty(Msg))
                LogTxt(Msg, "log", 180);
        }
        public static void LogTxt(int Msg)
        {
            LogTxt(Convert.ToString(Msg), "log", 180);
        }
        /// <summary> 
        /// 紀錄資料純放文字檔 <para></para>  
        /// 可自訂存放天數的txt檔案 
        /// </summary> 
        /// <param name="Msg">訊息</param> 
        /// <param name="directory">自訂資料夾(選填)</param> 
        /// <param name="retainDay">存放天數(選填)</param>  
        public static void LogTxt(string Msg, string directory = "log", int retainDay = 180)
        {
            DeleteFile("*.txt", retainDay, directory);

            if (!string.IsNullOrEmpty(Msg))
            {
                System.IO.Directory.CreateDirectory(System.Web.Hosting.HostingEnvironment.MapPath("~/" + directory));
                try
                {
                    System.IO.File.AppendAllText(string.Format(System.Web.Hosting.HostingEnvironment.MapPath("~/" + directory) + "/Log-{0}.txt", DateTime.Now.ToString("yyyy-MM-dd")), string.Concat(new object[] { Msg, Environment.NewLine }));
                }
                catch (Exception Ex)
                {
                    System.IO.File.AppendAllText(string.Format(System.Web.Hosting.HostingEnvironment.MapPath("~/" + directory) + "/Log-{0}.txt", DateTime.Now.ToString("yyyy-MM-dd")), string.Concat(new object[] { "=============Error===============" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff") + Environment.NewLine + Ex.ToString() + Environment.NewLine + "=============Error===============", Environment.NewLine }));
                }
            }
        }
        private static void DeleteFile(string FilePattern, int retainDay, string directory)
        {
            try
            {
                System.IO.Directory.CreateDirectory(System.Web.Hosting.HostingEnvironment.MapPath("~/" + directory));
                String[] FileCollection;
                if (string.IsNullOrEmpty(FilePattern))
                    FileCollection = System.IO.Directory.GetFiles(System.Web.Hosting.HostingEnvironment.MapPath("~/" + directory));
                else
                    FileCollection = System.IO.Directory.GetFiles(System.Web.Hosting.HostingEnvironment.MapPath("~/" + directory), FilePattern);

                for (int i = 0; i < FileCollection.Length; i++)
                {
                    System.IO.FileInfo theFileInfo = new System.IO.FileInfo(FileCollection[i]);
                    TimeSpan TIS = DateTime.Now.Subtract(theFileInfo.LastWriteTime);
                    if (TIS.TotalDays > retainDay)
                        System.IO.File.Delete(theFileInfo.FullName);
                }
            }
            catch (Exception)
            {
            }

        }
        #endregion

3.VB.NET網頁用的Log

先宣告

Private mu As New Mutex(False)

#Region "Logs"
    Private Sub AddLog(ByVal sMsg As String, ByVal folderName As String)
        Dim sb As New StringBuilder()
        sb.AppendLine("---------------------------------------------------------")
        sb.AppendLine("紀錄時間:" & DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"))
        sb.AppendLine(sMsg)
        sb.AppendLine("---------------------------------------------------------")
        AddData(sb.ToString(), Server.MapPath(folderName + "\"), DateTime.Now.ToString("yyyy-MM-dd"))
    End Sub

    Private Sub AddData(ByVal sMsg As String, ByVal filePath As String, ByVal filename As String)
        mu.WaitOne()
        If Not Directory.Exists(filePath) Then
            Directory.CreateDirectory(filePath)
        End If
        filePath &= filename & ".txt"
        Dim fi As New FileInfo(filePath)
        If Not fi.Exists Then
            Using sw As StreamWriter = fi.CreateText()
                sw.WriteLine(sMsg)
                sw.Flush()
                sw.Close()
            End Using
        Else
            Using sw As StreamWriter = fi.AppendText()
                sw.WriteLine(sMsg)
                sw.Flush()
                sw.Close()
            End Using
        End If
        mu.ReleaseMutex()
    End Sub
#End Region