c#自定义日志记录
前言:自定义写入日志,需要注意多线程下文件读取写入时异常问题处理:下面列举了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#自定义日志记录的更多相关文章
- Windows server2012 IIs 8 自定义日志记录
问题: 通过CDN加速的网站,记录日志时无法追踪源IP,日志的IP都为CDN节点ip. 分析: 1.在解析记录header时,CDN实际会把源IP以其它header的形式回传,如网宿为[Cdn-Src ...
- shell脚本中自定义日志记录到文件
自定义日志函数和前期变量 # adirname - return absolute dirname of given file adirname() { odir=`pwd`; cd `dirname ...
- 基于.NetCore3.1系列 —— 日志记录之自定义日志组件
一.前言 回顾:日志记录之日志核心要素揭秘 在上一篇中,我们通过学习了解在.net core 中内置的日志记录中的几大核心要素,在日志工厂记录器(ILoggerFactory)中实现将日志记录提供器( ...
- IIS 7完全攻略之日志记录配置(摘自网络)
IIS 7完全攻略之日志记录配置 作者:泉之源 [IT168 专稿]除了 Windows 提供的日志记录功能外,IIS 7.0 还可以提供其他日志记录功能.例如,可以选择日志文件格式并指定要记录的请求 ...
- ASP.NET MVC自定义Module记录管道事件执行顺序
1. 在Visual Studio 新建项目,模板为空,下面结构选择MVC. 2. 在项目中新建一个类MyModule,实现IHttpModule接口 namespace SimpleApp.Infr ...
- 如何自行给指定的SAP OData服务添加自定义日志记录功能
有的时候,SAP标准的OData实现或者相关的工具没有提供我们想记录的日志功能,此时可以利用SAP系统强大的扩展特性,进行自定义日志功能的二次开发. 以SAP CRM Fiori应用"My ...
- 基于.NetCore3.1系列 —— 日志记录之初识Serilog
一.前言 对内置日志系统的整体实现进行了介绍之后,可以通过使用内置记录器来实现日志的输出路径.而在实际项目开发中,使用第三方日志框架(如: Log4Net.NLog.Loggr.Serilog.Sen ...
- 如何定制.NET6.0的日志记录
在本章中,也就是整个系列的第一部分将介绍如何定制日志记录.默认日志记录仅写入控制台或调试窗口,这在大多数情况下都很好,但有时需要写入到文件或数据库,或者,您可能希望扩展日志记录的其他信息.在这些情况下 ...
- ASP.NET全局错误处理和异常日志记录以及IIS配置自定义错误页面
应用场景和使用目的 很多时候,我们在访问页面的时候,由于程序异常.系统崩溃会导致出现黄页.在通常的情况下,黄页对于我们来说,帮助是极大的,因为它可以帮助我们知道问题根源,甚至是哪一行代码出现了错误.但 ...
随机推荐
- ASP.NET Core 十种方式扩展你的 Views
原文地址:http://asp.net-hacker.rocks/2016/02/18/extending-razor-views.html 作者:Jürgen Gutsch 翻译:杨晓东(Savor ...
- 每周一书《Oracle 12 c PL(SQL)程序设计终极指南》
本周为大家送出的书是<Oracle 12 c PL(SQL)程序设计终极指南>,此书由机械工业出版社出版, 孙风栋,王澜,郭晓惠 著. 内容简介: <Oracle 12c PL/SQ ...
- 你写的Try...Catch真的有必要么?
很多人喜欢用Try...Catch把每一个方法都包裹起来,可是真的有必要么? 为什么要这样做?我估计是大家被BUG吓怕了,生怕生产环境出现各种莫名其妙的错误,比如最经典的NullReferenceEx ...
- 微冷的雨Java基础学习手记(一)
使用Java理解程序逻辑 之凌波微步 船舶停靠在港湾是很安全的,但这不是造船的目的 北大青鸟五道口原玉明老师出品 1.学习方法: 01.找一本好书 初始阶段不适合,可以放到第二个阶段,看到知识点时,要 ...
- CSS效果集锦(持续更新中)
高亮光弧效果 使用CSS3实现的一个高亮光弧效果,当鼠标hover到某一个元素上时,一道光弧从左向右闪过,效果如下: 代码如下: <!DOCTYPE html> <html lang ...
- TODO:小程序开发环境搭建
TODO:小程序开发环境搭建 1.第一步当然是要先注册小程序了 2.登录到小程序 a)完善小程序信息,如名称,图标,描述 3.绑定开发者 4.获取AppID,并设置服务器信息 5.下载并安装开发者工具 ...
- Android开发学习之路-Android Studio真神器!
放假之后电脑配置升级就开始用Android Studio(下面简称AS)了,那个酸爽真的不是一般的啊,这里开一篇博客来记录下AS里面各种酷炫的功能,有更好玩的,大家不要吝啬,评论告诉我吧! 最近And ...
- Java 循环中标签的作用
continue和break可以改变循环的执行流程,但在多重循环中,这两条语句无法直接从内层循环跳转到外层循环.在C语言中,可以通过goto语句实现多重循环的跳转,但在非循环结构中使用goto语句会使 ...
- Dnsmasq安装与配置
默认的情况下,我们平时上网用的本地DNS服务器都是使用电信或者联通的,但是这样也导致了不少的问题,首当其冲的就是上网时经常莫名地弹出广告,或者莫名的流量被消耗掉导致网速变慢.其次是部分网站域名不能正常 ...
- .Net 转战 Android 4.4 日常笔记(9)--常用组件的使用方法[附源码]
经过两天的学习,把常用的组件都学习了一遍,并做成了App 学习可能真没有捷径,跟学习html有点类似,都是一个控件一个控件学习并使用,最后拼凑成一个系统 链接:http://pan.baidu.com ...