【C#写日志两个简单方法】
方法一:以日期为日志文件名.
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效果如何
作者:一个大西瓜
-------------------------------------------
个性签名:独学而无友,则孤陋而寡闻。做一个灵魂有趣的人!
如果觉得这篇文章对你有小小的帮助的话,记得在右下角点个“推荐”哦,博主在此感谢!
万水千山总是情,打赏一分行不行,所以如果你心情还比较高兴,也是可以扫码打赏博主,哈哈哈(っ•̀ω•́)っ✎⁾⁾!
posted on 2017-12-11 15:43 一个大西瓜咚咚咚 阅读(12752) 评论(0) 编辑 收藏 举报