前言:自定义写入日志,需要注意多线程下文件读取写入时异常问题处理:下面列举了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. .NET面试题系列[11] - IEnumerable<T>的派生类

    “你每次都选择合适的数据结构了吗?” - Jeffery Zhao .NET面试题系列目录 ICollection<T>继承IEnumerable<T>.在其基础上,增加了Ad ...

  2. .NET陷阱之六:从枚举值持久化带来大量空间消耗谈起

    好长时间没有写博文了,今天继续. 这次跟大家分享的内容起因于对一个枚举值列表的序列化,下面简化后的代码即能重现.为了明确起见,我显式指定了枚举的基础类型. // 定义一个枚举类型. public en ...

  3. 翻译-使用Ratpack和Spring Boot打造高性能的JVM微服务应用

    这是我为InfoQ翻译的文章,原文地址:Build High Performance JVM Microservices with Ratpack & Spring Boot,InfoQ上的中 ...

  4. Step by step SQL Server 2012的安装

    原创地址:http://www.cnblogs.com/jfzhu/p/4006744.html 转载请注明出处 计算机要先设置固定ip,加入域,然后安装账号需要有本地管理员的权限. 演示环境的操作系 ...

  5. SqlServer英文单词全字匹配

    环境:Vs2013+Sql Server2012 问题:现在数据库记录如下: Sentence列保存的是英文的句子,我现在想找出所有包含“I”(单词)的句子,如果我用 Sentence like '% ...

  6. KnockoutJS 3.X API 第六章 组件(2) 组件注册

    要使Knockout能够加载和实例化组件,必须使用ko.components.register注册它们,从而提供如此处所述的配置. 注意:作为替代,可以实现一个自定义组件加载器(自定义加载器下一节介绍 ...

  7. PHP SESSION机制,从存储到读取

    PHP中,如果要获取SESSION数据,必须要有对应的session_id,session_id的获取方式有两种 1.基于客户端的cookie 2.基于url 先说第一种情况,基于客户端的cookie ...

  8. Constraint3:check约束 和 null

    Check约束用以限制单列或多列的可能取值范围. 1,在check约束中(check(expression)),如果expression返回的结果是Unknown,那么check返回的结果是true. ...

  9. 【Win 10应用开发】SplitView控件

    SplitView控件用于呈现分隔视图,简单地说,就是把一个视图分割为两部分,Content属性所表示的为主要视图,而Pane属性设置的视图则可以隐藏,可以折叠和展开. 估计文字是不太容易介绍这个控件 ...

  10. jquery $.each的用法

    通过它,你可以遍历对象.数组的属性值并进行处理. 使用说明 each函数根据参数的类型实现的效果不完全一致: 1.遍历对象(有附加参数) $.each(Object, function(p1, p2) ...