方法一:以日期為日志文件名.
public void WriteLog(string msg) { string filePath = AppDomain.CurrentDomain.BaseDirectory + "Log"; if (!Directory.Exists(filePath)) { Directory.CreateDirectory(filePath); } string logPath = AppDomain.CurrentDomain.BaseDirectory + "Log\\" + DateTime.Now.ToString("yyyy-MM-dd") + ".txt"; try { using (StreamWriter sw = File.AppendText(logPath)) { sw.WriteLine("消息:" + msg); sw.WriteLine("時間:" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")); sw.WriteLine("**************************************************"); sw.WriteLine(); sw.Flush(); sw.Close(); sw.Dispose(); } } catch (IOException e) { using (StreamWriter sw = File.AppendText(logPath)) { sw.WriteLine("異常:" + e.Message); sw.WriteLine("時間:" + DateTime.Now.ToString("yyy-MM-dd HH:mm:ss")); sw.WriteLine("**************************************************"); sw.WriteLine(); sw.Flush(); sw.Close(); sw.Dispose(); } } }
利用泛型進行打印日志
/// <summary> /// 打印日志 /// </summary> /// <param name="msg"></param> public static void WriteLog(string msg) { string filePath = AppDomain.CurrentDomain.BaseDirectory + "Log"; if (!Directory.Exists(filePath)) { Directory.CreateDirectory(filePath); } string logPath = AppDomain.CurrentDomain.BaseDirectory + "Log\\" + DateTime.Now.ToString("yyyy-MM-dd") + ".txt"; try { using (StreamWriter sw=File.AppendText(logPath)) { sw.WriteLine("消息:" + msg); sw.WriteLine("時間:" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")); sw.WriteLine("**************************************************"); sw.WriteLine(); sw.Flush(); sw.Close(); sw.Dispose(); } } catch (IOException e) { using (StreamWriter sw = File.AppendText(logPath)) { sw.WriteLine("異常:" + e.Message); sw.WriteLine("時間:" + DateTime.Now.ToString("yyy-MM-dd HH:mm:ss")); sw.WriteLine("**************************************************"); sw.WriteLine(); sw.Flush(); sw.Close(); sw.Dispose(); } } } /// <summary> /// 打印Model日志 /// </summary> /// <typeparam name="T"></typeparam> /// <param name="model"></param> public static void WriteLog<T>(T model) where T:class { string filePath = AppDomain.CurrentDomain.BaseDirectory + "Log"; if (!Directory.Exists(filePath)) { Directory.CreateDirectory(filePath); } string logPath = AppDomain.CurrentDomain.BaseDirectory + "Log\\" + DateTime.Now.ToString("yyyy-MM-dd") + ".txt"; try { using (StreamWriter sw = File.AppendText(logPath)) { Type type = typeof(T); string msg = string.Join("*****", type.GetProperties().Select(m=>m.Name+":"+m.GetValue(model))); sw.WriteLine("消息:" + msg); sw.WriteLine("時間:" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")); sw.WriteLine("**************************************************"); sw.WriteLine(); sw.Flush(); sw.Close(); sw.Dispose(); } } catch (IOException e) { using (StreamWriter sw = File.AppendText(logPath)) { sw.WriteLine("異常:" + e.Message); sw.WriteLine("時間:" + DateTime.Now.ToString("yyy-MM-dd HH:mm:ss")); sw.WriteLine("**************************************************"); sw.WriteLine(); sw.Flush(); sw.Close(); sw.Dispose(); } } }
方法二:以文檔名稱和日期結合作為文件名
public void WriteLog(string documentName, string msg) { string errorLogFilePath = System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Log"); if (!System.IO.Directory.Exists(errorLogFilePath)) { System.IO.Directory.CreateDirectory(errorLogFilePath); } string logFile = System.IO.Path.Combine(errorLogFilePath, documentName + "@" + DateTime.Today.ToString("yyyy-MM-dd") + ".txt"); bool writeBaseInfo = System.IO.File.Exists(logFile); StreamWriter swLogFile = new StreamWriter(logFile, true, Encoding.Unicode); swLogFile.WriteLine(DateTime.Now.ToString("HH:mm:ss") + "\t" + msg); swLogFile.Close(); swLogFile.Dispose(); }
方法三: 使用log4net類庫輸出日志
1.下載log4net類庫 並選擇項目對應的框架版本
下載地址:http://logging.apache.org/log4net/download_log4net.cgi
2.添加log4net引用,創建LogHelper類。
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using log4net; using log4net.Core; [assembly: log4net.Config.XmlConfigurator(Watch = true)] namespace BoilerDashboard.Common { public class LogHelper { /// <summary> /// 輸出日志到Log4Net /// </summary> /// <param name="t"></param> /// <param name="ex"></param> #region static void WriteLog(Type t, Exception ex) public static void WriteLog(Type t, Exception ex) { log4net.ILog log = log4net.LogManager.GetLogger(t); log.Error("Error", ex); } #endregion /// <summary> /// 輸出日志到Log4Net /// </summary> /// <param name="t"></param> /// <param name="msg"></param> #region static void WriteLog(Type t, string msg) public static void WriteLog(Type t, string msg) { log4net.ILog log = log4net.LogManager.GetLogger(t); log.Error(msg); } #endregion } }
方法四:Microsoft Enterprise Library里面的Log功能
以VS2012里面建立的一個控制台程序為例
1. 安裝Microsoft Enterprise Library里面的Logging Application模塊。
在需要使用Log功能的項目上面右鍵,選擇Manage NuGet Packeages...
2. 在Manage NuGet Packeages窗口里面找到Enterprise Library - Logging Application Block,然后安裝
安裝成功以后,項目引用中會增加兩個新的引用。
3. 我們需要對App.config文件進行配置。在這里我們使用配置編輯工具:Microsoft.Practices.EnterpriseLibrary.ConfigConsoleV6.vsix。這個工具的下載地址:http://www.microsoft.com/en-us/download/details.aspx?id=38789
4. 配置App.config文件。右鍵App.config文件選擇Edit configuration file v6,打開配置工具窗口。
5. 選擇菜單命令Block -> Add Logging Settings
6. 在Logging Target Listeners里面點加號按鈕,然后選擇Add Rolling Flat File Trace Listener(生成可以進行自動分割的文本文件)。
7. 一般需要設置的參數有:Asynchronous(選true則進行異步log), File Exist Behavior(選), File Name, Formatter Name, Max Archived Files, Roll Interval, Roll Size KB。
其中Formatter Name的值從Log Message Formatters中生成的值中選取。
8. 生成 Message Format。在Log Message Formatters中點擊加號按鈕,選擇Add Text Formatter
點擊Template右側的...按鈕,打開Template Editor對話框,對Template的內容進行編輯
編輯后在App.config中生成的xml代碼如下:
Logging formatter
9. 在窗口左側區域中點擊Cotegories右邊的加號按鈕。生成一個新的Category
10. 在新生成的Category區域中修改Name屬性,然后點擊Listeners右邊的加號按鈕,選擇在Logging Target Listeners區域中已經生成的Listener。
11. 對已經進行的設置保
12. 寫個簡單的測試程序看看生成的Log效果如何
