c#自定义日志记录
发布时间:2020-12-16 08:55:31 所属栏目:asp.Net 来源:网络整理
导读:前言:自定义写入日志,需要注意多线程下文件读取写入时异常问题处理:下面列举了2种优化方案: 废话不多说,直接上代码: ? 很简单:将类复制到项目中,最后在配置文件上配置一下:logUrl即可。 默认保存在:项目/temp/log ?自定义日志类1: /// summary //
前言:自定义写入日志,需要注意多线程下文件读取写入时异常问题处理:下面列举了2种优化方案: 废话不多说,直接上代码: ? 很简单:将类复制到项目中,最后在配置文件上配置一下:logUrl即可。 默认保存在:项目/temp/log ?自定义日志类1: /// <summary> /// 日志类 </summary> <remarks>Creator: v-lxh CreateTime: 2016/7/26 11:18:09</remarks> <Description></Description> public class Log { <summary> 写入日志. </summary> <param name="strList">The STR list.</param> </remarks> <Description></Description> static void WriteLog(params object[] strList) { //判断是否开启日志模式 if (!LogModel) return; if (strList.Count() == 0) return; 日志文件路径 string strDicPath = ""try { strDicPath = HttpContext.Current.Server.MapPath("~/temp/log/"); if (strDicPath == null || strDicPath == ) { strDicPath = System.Configuration.ConfigurationManager.AppSettings[logUrl"] + /temp/log/; } } catch (Exception e) { strDicPath = System.Configuration.ConfigurationManager.AppSettings[; } string strPath = strDicPath + string.Format({0:yyyy年-MM月-dd日}",DateTime.Now) + 日志记录.txtif (!Directory.Exists(strDicPath)) { Directory.CreateDirectory(strDicPath); } File.Exists(strPath)) { using (FileStream fs = File.Create(strPath)) { } } string str = File.ReadAllText(strPath); StringBuilder sb = new StringBuilder(); foreach (var item in strList) { sb.Append(rn" + DateTime.Now.ToString() + -----" + item + ); } File.WriteAllText(strPath,sb.ToString() + rn-----z-----rn" + str); } } ? ??初稿1--优化1-使用Lock锁定资源: ? Creator: lixh CreateTime: 2017/3/23 11:18:09 Log { 日期文件夹路径 ; 静态方法todo:在处理话类型之前自动调用,去检查日志文件夹是否存在 static Log() { todo:通过当前http请求上下文获取的服务器相对路径下的物理路径--非静态资源--占用资源 string strDicPath = System.Web.HttpContext.Current.Server.MapPath("~/temp/log/"); 静态类型--获取应用所在的物理路径--节省资源 //strDicPath = System.Web.HttpRuntime.AppDomainAppPath + "templogs"; ? //初稿2-优化-使用微软提供的读写锁: 读写锁,当资源处于写入模式时,其他线程写入需要等待本次写入结束之后才能继续写入 private static ReaderWriterLockSlim LogWriteLock = ReaderWriterLockSlim(); { todo:自动创建文件(但不能创建文件夹),并设置文件内容追加模式,使用using会自动释放FileSteam资源 LogWriteLock.EnterWriteLock(); write.Close(); write.Dispose(); } } (Exception) { } finally { LogWriteLock.ExitWriteLock(); } } ? (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
相关内容
- asp.net-mvc – Kendoui MVC EditorTemplateName在PopUp编辑
- Asp.Net Identity – 登录后更新声明
- asp.net – WebMatrix Razor页面和全局使用语句
- 是否停止支持单声道ASP.Net?
- ASP.NET – IHttpModule.BeginRequest触发2X,Application_B
- asp.net – 获取当前用户的GUID?
- 单元测试ASP.NET WebAPI控制器的POST操作
- 使用ASP.Net Web API进行多部分表单POST
- asp.net – 让Visual Studios使用子域名?
- Asp.net中的下拉列表验证使用必需字段验证器