前言:自定义写入日志,需要注意多线程下文件读取写入时异常问题处理:下面列举了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>Creator: v-lxh CreateTime: 2016/7/26 11:18:09</remarks>
/// <Description></Description>
public static void WriteLog(params object[] strList)
{
//判断是否开启日志模式
//if (!LogModel) return;
if (strList.Count() == ) 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["logUrl"] + "/temp/log/";
}
string strPath = strDicPath + string.Format("{0:yyyy年-MM月-dd日}", DateTime.Now) + "日志记录.txt";
if (!Directory.Exists(strDicPath))
{
Directory.CreateDirectory(strDicPath);
}
if (!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("\r\n" + DateTime.Now.ToString() + "-----" + item + "");
}
File.WriteAllText(strPath, sb.ToString() + "\r\n-----z-----\r\n" + str);
} }

 初稿1--优化1-使用Lock锁定资源:

   /// <summary>
/// 日志类
/// </summary>
/// <remarks>Creator: lixh CreateTime: 2017/3/23 11:18:09</remarks>
/// <Description></Description>
public class Log
{
//日期文件夹路径
public static string strDicPath = ""; //静态方法todo:在处理话类型之前自动调用,去检查日志文件夹是否存在
static Log()
{
//todo:通过当前http请求上下文获取的服务器相对路径下的物理路径--非静态资源--占用资源
//string strDicPath = System.Web.HttpContext.Current.Server.MapPath("~/temp/log/"); //静态类型--获取应用所在的物理路径--节省资源
//strDicPath = System.Web.HttpRuntime.AppDomainAppPath + "\\temp\\logs\\";
       //winform等非web程序可使用以下方法:
       strDicPath = System.Threading.Thread.GetDomain().BaseDirectory.Replace("\\bin\\Debug", "") + "\\temp\\logs\\";
//创建文件夹
if (!Directory.Exists(strDicPath))
{
Directory.CreateDirectory(strDicPath);
}
} /// <summary>
/// 写入日志.
/// </summary>
/// <param name="strList">The STR list.</param>
/// <remarks> </remarks>
/// <Description></Description>
public static void WriteLog(params object[] strList)
{
if (strList.Count() == ) return;
string strPath = ""; //文件路径
try
{
strPath = strDicPath + string.Format("{0:yyyy年-MM月-dd日}", DateTime.Now) + "日志记录.txt";
}
catch (Exception e)
{
strDicPath = "C:\\temp\\log\\";
strPath = strDicPath + string.Format("{0:yyyy年-MM月-dd日}", DateTime.Now) + "日志记录.txt";
} //todo:自动创建文件(但不能创建文件夹),并设置文件内容追加模式,使用using会自动释放FileSteam资源
using (FileStream stream = new FileStream(strPath, FileMode.Append))
{
lock (stream) //锁定资源,一次只允许一个线程写入
{
StreamWriter write = new StreamWriter(stream);
string content = "";
foreach (var str in strList)
{
content += "\r\n" + DateTime.Now.ToString() + "-----" + str;
}
content += "\r\n-----z-----\r\n";
write.WriteLine(content); //关闭并销毁流写入文件
write.Close();
write.Dispose();
}
}
} /// <summary>
/// 写入日志.
/// </summary>
/// <param name="strList">The STR list.</param>
/// <remarks></remarks>
/// <Description></Description>
public static void WriteLog(Action DefFunc, Func<string> ErrorFunc = null)
{
try
{
DefFunc();
}
catch (Exception ex)
{
string strPath = strDicPath + string.Format("{0:yyyy年-MM月-dd日}", DateTime.Now) + "日志记录.txt"; //todo:自动创建文件(但不能创建文件夹),并设置文件内容追加模式,使用using会自动释放FileSteam资源
using (FileStream stream = new FileStream(strPath, FileMode.Append))
{
lock (stream) //锁定资源,一次只允许一个线程写入
{
StreamWriter write = new StreamWriter(stream);
string content = "\r\n" + DateTime.Now.ToString() + "-----" + ex.Message;
content += "\r\n" + DateTime.Now.ToString() + "-----" + ex.StackTrace;
content += "\r\n-----z-----\r\n";
write.WriteLine(content); //关闭并销毁流写入文件
write.Close();
write.Dispose();
}
}
}
}
}

//初稿2-优化-使用微软提供的读写锁:

//读写锁,当资源处于写入模式时,其他线程写入需要等待本次写入结束之后才能继续写入
private static ReaderWriterLockSlim LogWriteLock = new ReaderWriterLockSlim();
/// <summary>
/// 写入日志.
/// </summary>
/// <param name="strList">The STR list.</param>
/// <remarks> </remarks>
/// <Description></Description>
public static void WriteLog(params object[] strList)
{
if (strList.Count() == ) return;
string strPath = ""; //文件路径
try
{
strPath = strDicPath + string.Format("{0:yyyy年-MM月-dd日}", DateTime.Now) + "日志记录.txt";
}
catch (Exception e)
{
strDicPath = "C:\\temp\\log\\";
strPath = strDicPath + string.Format("{0:yyyy年-MM月-dd日}", DateTime.Now) + "日志记录.txt";
} try
{
//todo:自动创建文件(但不能创建文件夹),并设置文件内容追加模式,使用using会自动释放FileSteam资源
LogWriteLock.EnterWriteLock(); using (FileStream stream = new FileStream(strPath, FileMode.Append))
{
StreamWriter write = new StreamWriter(stream);
string content = "";
foreach (var str in strList)
{
content += "\r\n" + DateTime.Now.ToString() + "-----" + str;
}
content += "\r\n-----z-----\r\n";
write.WriteLine(content); //关闭并销毁流写入文件
write.Close();
write.Dispose();
}
}
catch (Exception)
{ }
finally {
LogWriteLock.ExitWriteLock();
}
}

c#自定义日志记录的更多相关文章

  1. Windows server2012 IIs 8 自定义日志记录

    问题: 通过CDN加速的网站,记录日志时无法追踪源IP,日志的IP都为CDN节点ip. 分析: 1.在解析记录header时,CDN实际会把源IP以其它header的形式回传,如网宿为[Cdn-Src ...

  2. shell脚本中自定义日志记录到文件

    自定义日志函数和前期变量 # adirname - return absolute dirname of given file adirname() { odir=`pwd`; cd `dirname ...

  3. 基于.NetCore3.1系列 —— 日志记录之自定义日志组件

    一.前言 回顾:日志记录之日志核心要素揭秘 在上一篇中,我们通过学习了解在.net core 中内置的日志记录中的几大核心要素,在日志工厂记录器(ILoggerFactory)中实现将日志记录提供器( ...

  4. IIS 7完全攻略之日志记录配置(摘自网络)

    IIS 7完全攻略之日志记录配置 作者:泉之源 [IT168 专稿]除了 Windows 提供的日志记录功能外,IIS 7.0 还可以提供其他日志记录功能.例如,可以选择日志文件格式并指定要记录的请求 ...

  5. ASP.NET MVC自定义Module记录管道事件执行顺序

    1. 在Visual Studio 新建项目,模板为空,下面结构选择MVC. 2. 在项目中新建一个类MyModule,实现IHttpModule接口 namespace SimpleApp.Infr ...

  6. 如何自行给指定的SAP OData服务添加自定义日志记录功能

    有的时候,SAP标准的OData实现或者相关的工具没有提供我们想记录的日志功能,此时可以利用SAP系统强大的扩展特性,进行自定义日志功能的二次开发. 以SAP CRM Fiori应用"My ...

  7. 基于.NetCore3.1系列 —— 日志记录之初识Serilog

    一.前言 对内置日志系统的整体实现进行了介绍之后,可以通过使用内置记录器来实现日志的输出路径.而在实际项目开发中,使用第三方日志框架(如: Log4Net.NLog.Loggr.Serilog.Sen ...

  8. 如何定制.NET6.0的日志记录

    在本章中,也就是整个系列的第一部分将介绍如何定制日志记录.默认日志记录仅写入控制台或调试窗口,这在大多数情况下都很好,但有时需要写入到文件或数据库,或者,您可能希望扩展日志记录的其他信息.在这些情况下 ...

  9. ASP.NET全局错误处理和异常日志记录以及IIS配置自定义错误页面

    应用场景和使用目的 很多时候,我们在访问页面的时候,由于程序异常.系统崩溃会导致出现黄页.在通常的情况下,黄页对于我们来说,帮助是极大的,因为它可以帮助我们知道问题根源,甚至是哪一行代码出现了错误.但 ...

随机推荐

  1. [译]MVC网站教程(一):多语言网站框架

    本文简介 本博文介绍了 Visual Studio 工具生成的 ASP.NET MVC3 站点的基本框架:怎样实现网站的语言的国际化与本地化功能,从零开始实现用户身份认证机制,从零开始实现用户注册机制 ...

  2. Net作业调度(四)—quartz.net持久化和集群

    介绍 在实际使用quartz.net中,持久化能保证实例重启后job不丢失. 集群能均衡服务器压力和解决单点问题. quartz.net在这两方面配置都比较简单. 持久化 quartz.net的持久化 ...

  3. Hystrix框架2--超时

    timeout 在调用第三方服务时有些情况需要对服务响应时间进行把控,当超时的情况下进行fallback的处理 下面来看下超时的案例 public class CommandTimeout exten ...

  4. bootstrap-popover的配置与灵活应用

    首先罗列一下配置参数: 1.animation true/false 是否动画 2.placement 'right'/'left'/top/bottom/function(){return 'rig ...

  5. 修改input框默认黄色背景

    input:-webkit-autofill, textarea:-webkit-autofill, select:-webkit-autofill { -webkit-box-shadow: 0 0 ...

  6. KnockoutJS 3.X API 第六章 组件(1) 组件和自定义元素 - 概述

    Components (组件)是一个强大的,干净的方式组织您的UI代码,可重复使用的块. : -可以表示单独的控件/窗口小部件或应用程序的整个部分 -包含自己的视图,通常(但可选)自己的视图模型 -可 ...

  7. MongoDB replica set IDs do not match

    在搭建MongoDB(版本 3.2.9)的Replica Set时,使用 rs.status() 查看Replica Set的状态,发现一个成员异常:replica set IDs do not ma ...

  8. SSIS的 Data Flow 和 Control Flow

    Control Flow 和 Data Flow,是SSIS Design中主要用到的两个Tab,理解这两个Tab的作用,对设计更高效的package十分重要. 一,Control Flow 在Con ...

  9. 一篇通俗易懂的CSS层叠顺序与层叠上下文研究

    网上有很多这方面的教程,但不是苦涩难懂就是从哪copy过来的,反正很长一段时间我是没看懂,时间长了也没打算去研究了,主要原因是,基本上很少会遇到那些问题(所以说啊,要是没有研究精神的才懒得管它).但自 ...

  10. jQuery 2.0.3 源码分析Sizzle引擎 - 超级匹配

    声明:本文为原创文章,如需转载,请注明来源并保留原文链接Aaron,谢谢! 通过Expr.find[ type ]我们找出选择器最右边的最终seed种子合集 通过Sizzle.compile函数编译器 ...