日志记录类LogHelper
开源日志log4net使用起来很方便,但是项目中不让用,所以自己重写了一个类,用来记录日志,比较简单。
1、首先是可以把日志分成多个类型,分别记录到不同的文件中
/// <summary>
/// 日志类型
/// </summary>
public enum LogType
{
/// <summary>
/// 插入型
/// </summary>
Insert,
/// <summary>
/// 更新型
/// </summary>
Update,
/// <summary>
/// 所有
/// </summary>
All,
/// <summary>
/// 结尾,放在最后
/// </summary>
End
}
我的是分三个,insert插入,update更新,all包括所有的日志。
2、接下来是LogHelper类,代码中已注释,不多说,直接上代码
/// <summary>
/// 记录日志
/// </summary>
public class LogHelper
{ #region 自定义变量
/// <summary>
/// 异常信息的队列
/// </summary>
private static Queue<string> qMsg = null;
/// <summary>
/// 文件大小最大值,单位:Mb
/// </summary>
private static int maxFileSize = ;
/// <summary>
/// 当天创建同一类型的日志文件的个数
/// </summary>
private static int[] createdFileCounts = new int[(int)LogType.End];
/// <summary>
/// 日志文件存放路径
/// </summary>
private static string logFilePath = "";
#endregion #region 属性
/// <summary>
/// 文件大小最大值,单位:Mb。小于0时则不限制
/// </summary>
public static int MaxFileSize
{
get { return maxFileSize; }
set { maxFileSize = value; }
}
/// <summary>
/// 日志文件存放路径
/// </summary>
public static string LogFilePath
{
set { logFilePath = value; }
get
{
if (!String.IsNullOrEmpty(logFilePath))
{
return logFilePath;
}
else
{
return System.Windows.Forms.Application.StartupPath + "\\Log\\" + DateTime.Now.ToString("yyyy-MM-dd");
}
}
}
#endregion #region 构造函数
/// <summary>
/// 静态构造函数
/// </summary>
static LogHelper()
{
qMsg = new Queue<string>();
SetCreatedFileCount();
RunThread();
}
#endregion #region 辅助
/// <summary>
/// 获取日志文件的全路径
/// </summary>
/// <param name="logType"></param>
/// <returns></returns>
private static string GetLogPath(LogType logType, bool isCreateNew)
{
string logPath = LogFilePath;
if (!Directory.Exists(logPath))
{
Directory.CreateDirectory(logPath);
//看成是新的一天,要将昨天的数据清空
for (int i = ; i < createdFileCounts.Length; i++)
{
createdFileCounts[i] = ;
}
}
switch (logType)
{
case LogType.Insert:
logPath = logPath + "\\" + "Insert";
break;
case LogType.Update:
logPath = logPath + "\\" + "Update";
break;
default:
logPath = logPath + "\\" + "All";
break;
}
if (isCreateNew)
{
int num = ++createdFileCounts[(int)logType];
logPath += string.Format("({0}).log", num);
return logPath;
} logPath += ".log";
//createdFileCounts[(int)logType] = 0;
if (!File.Exists(logPath))
{
//File.Create(logPath);
FileStream fs = File.Create(logPath);
fs.Close();
fs.Dispose();
} return logPath;
} /// <summary>
/// 运行线程
/// </summary>
private static void RunThread()
{
ThreadPool.QueueUserWorkItem(u =>
{
while (true)
{
string tmsg = string.Empty;
lock (qMsg)
{
if (qMsg.Count > )
tmsg = qMsg.Dequeue();
} //往日志文件中写错误信息
if (!String.IsNullOrEmpty(tmsg))
{
int index = tmsg.IndexOf("&&");
string logTypeStr = tmsg.Substring(, index);
LogType logType = LogType.All;
if (logTypeStr == string.Format("{0}", LogType.Insert))
{
logType = LogType.Insert;
}
else if (logTypeStr == string.Format("{0}", LogType.Update))
{
logType = LogType.Update;
} //记录所有日志
WriteLog(tmsg.Substring(index + ));
//分开记录日志
if (logType != LogType.All)
{
WriteLog(tmsg.Substring(index + ), logType);
}
} if (qMsg.Count <= )
{
Thread.Sleep();
}
}
});
} /// <summary>
/// 程序刚启动时 检测已创建的日志文件个数
/// </summary>
private static void SetCreatedFileCount()
{
string logPath = LogFilePath;
if (!Directory.Exists(logPath))
{
for (int i = ; i < createdFileCounts.Length; i++ )
{
createdFileCounts[i] = ;
}
}
else
{
DirectoryInfo dirInfo = new DirectoryInfo(logPath);
FileInfo[] fileInfoes = dirInfo.GetFiles("*.log");
foreach (FileInfo fi in fileInfoes)
{
string fileName = Path.GetFileNameWithoutExtension(fi.FullName).ToLower();
if (fileName.Contains('(') && fileName.Contains(')'))
{
fileName = fileName.Substring(, fileName.LastIndexOf('('));
switch (fileName)
{
case "insert":
createdFileCounts[(int)LogType.Insert]++;
break;
case "update":
createdFileCounts[(int)LogType.Update]++;
break;
case "all":
createdFileCounts[(int)LogType.All]++;
break;
default:
break;
}
}
} }
}
#endregion #region 写日志 /// <summary>
/// 写日志
/// </summary>
/// <param name="strLog">日志内容</param>
public static void WriteLog(string strLog)
{
WriteLog(strLog, LogType.All);
} /// <summary>
/// 写日志
/// </summary>
/// <param name="strLog">日志内容</param>
/// <param name="logType">日志类型</param>
public static void WriteLog(string strLog, LogType logType)
{
if (String.IsNullOrEmpty(strLog))
{
return;
}
strLog = strLog.Replace("\n", "\r\n"); FileStream fs = null;
try
{
string logPath = GetLogPath(logType, false);
FileInfo fileInfo = new FileInfo(logPath);
if (MaxFileSize > && fileInfo.Length > ( * * MaxFileSize))
{
fileInfo.MoveTo(GetLogPath(logType, true));
}
fs = File.Open(logPath, FileMode.OpenOrCreate);
//fs = File.OpenWrite(logPath);
byte[] btFile = Encoding.UTF8.GetBytes(strLog);
//设定书写的開始位置为文件的末尾
fs.Position = fs.Length;
//将待写入内容追加到文件末尾
fs.Write(btFile, , btFile.Length);
}
finally
{
if (fs != null)
{
fs.Close();
fs.Dispose();
}
}
} /// <summary>
/// 写入错误日志队列
/// </summary>
/// <param name="msg">错误信息</param>
public static void WriteLogAsync(string strLog, LogType logType)
{
//将错误信息添加到队列中
lock (qMsg)
{
qMsg.Enqueue(string.Format("{0}&&{1}\r\n", logType, strLog));
}
}
#endregion }
使用时,可以直接调用WriteLogAsync函数,将消息添加到队列中,然后在另外的线程中处理队列中的消息。
其中,如果没有给LogFilePath属性赋值,则有一个默认的文件存放路径。MaxFileSize属性是用来限制日志文件大小的,如果小于等于0则表示不限制。如果有限制,当文件大小超过这个最大值后会将原来的文件重命名,然后再创建一个“自己”。例如:正在存放日志的文件名为"All.log",当它满了以后就成为“All(n).log”文件,n为从1开始递增的数字,然后会重新创建一个“All.log”文件接着存放日志。
日志记录类LogHelper的更多相关文章
- 【个人使用.Net类库】(2)Log日志记录类
开发接口程序时,要保证程序稳定运行就要时刻监控接口程序发送和接收的数据,这就需要一个日志记录的类将需要的信息记录在日志文件中,便于自己维护接口程序.(Web系统也是如此,只是对应的日志实现比这个要复杂 ...
- C# 简单日志帮助类LogHelper
调用: LogHelper.Debug(""); LogHelper.Info(""); LogHelper.Error(""); 项目添加 ...
- 【C#通用类】日志记录类
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Tex ...
- C#日志记录类
public class WriteLog { /// <summary> /// 将错误写入文件中 /// </summary> /// <param name=&qu ...
- 日志记录类库log4net的使用总结
log4net是一个开源的日志记录类库,经过配置后可以自动抓取程序中的错误.异常信息,并写入磁盘,也可以在异常发生时执行其他指定的操作,比如:通知某人右键.写入数据库等.这里写个ASP.NET MVC ...
- 利用AOP与ToStringBuilder简化日志记录
刚学spring的时候书上就强调spring的核心就是ioc和aop blablabla...... IOC到处都能看到...AOP么刚开始接触的时候使用在声明式事务上面..当时书上还提到一个用到ao ...
- 将错误日志记录在txt文本里
引言 对于已经部署的系统一旦出错对于我们开发人员来说是比较痛苦的事情,因为我们不能跟踪到错误信息,不能 很快的定位到我们的错误位置在哪,这时候如果能像开发环境一样记录一些堆栈信息就可以了,这时候我们就 ...
- Spring AOP进行日志记录
在java开发中日志的管理有很多种.我一般会使用过滤器,或者是Spring的拦截器进行日志的处理.如果是用过滤器比较简单,只要对所有的.do提交进行拦截,然后获取action的提交路径就可以获取对每个 ...
- Java 基于log4j的日志工具类
对log4j日志类进行了简单封装,使用该封装类的优势在于以下两点: 1.不必在每个类中去创建对象,直接类名 + 方法即可 2.可以很方便的打印出堆栈信息 package com.tradeplatfo ...
随机推荐
- SQL2008-字符转数字CAST和CONVERT
语法 使用CAST: CAST(expression AS data_type) 使用CONVERT: CONVERT(data_type[(length)],expression,[style])例 ...
- IOS成长之路-调用照相机和相册功能
打开相机: //先设定sourceType为相机,然后判断相机是否可用(ipod)没相机,不可用将sourceType设定为相片库 UIImagePickerControllerSourceType ...
- 常用的各种标准下载网站(HB GB GJB MH)
标准分享网 http://www.bzfxw.com/ 标准下载网 http://www.bzxz.net/ 搜标准网 http://www.biaozhunw.com/Index.html 标准 ...
- hdoj 2151 Worm【动态规划】
Worm Time Limit: 1000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)Total Submis ...
- hdoj 2091 空心三角形
空心三角形 Time Limit: 1000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)Total Submi ...
- [OC Foundation框架 - 18] Class
使用Class来创建实例 // 18.通过@"Ball"创建一个Ball实例(不可以使用[[Ball alloc] init]创建) NSString *className = @ ...
- ASP.NET MVC中防止跨站请求攻击(CSRF)
转载 http://kevintsengtw.blogspot.co.nz/2013/01/aspnet-mvc-validateantiforgerytoken.html 在 ASP.NET M ...
- Unity3D4.x之AssetBundle学习笔记
关于AssetBundle AssetBundle可用来将多个资源打包为一个文件,实现动态下载和更新.需要注意的是Unity3D5.x以后对打包方式进行了升级,不用再在依赖关系上伤透脑筋,但是和4.x ...
- SpringMVC 参考文档
原文地址:http://blog.csdn.net/lufeng20/article/details/7598801
- POJ 2778 DNA Sequence (AC自己主动机 + dp)
DNA Sequence 题意:DNA的序列由ACTG四个字母组成,如今给定m个不可行的序列.问随机构成的长度为n的序列中.有多少种序列是可行的(仅仅要包括一个不可行序列便不可行).个数非常大.对10 ...