日志记录类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 ...
随机推荐
- SAP:建表时如果有QUAN、CURR类型的字段不能激活的问题
建表时如有一个QUAN类型的字段,那么就要给字段设置Reference field,参考的字段的Data Type要是UNIT, 并设置对应的Reference table,也就是参考字段所在的tab ...
- python 递归函数
在函数内部,可以调用其他函数.如果一个函数在内部调用自身本身,这个函数就是递归函数. 举个例子,我们来计算阶乘n! = 1 x 2 x 3 x ... x n,用函数fact(n)表示,可以看出: f ...
- 用Modelsim仿真QuartusII综合后网表时库的添加方法(转)
这两天做综合后仿真,发现FPGA器件库又不会加了,无奈上网找方法.说起来不好意思,很早就接触Modelsim这个仿真软件了,可是没有好好琢磨.把这两天找的方法贴出来,再加上自己的理解,以后忘了可以上博 ...
- React Native学习笔记-1:JSC profiler is not supported.(转载)
运行react-native中Example下的UIEXPLORER Project 遇到虾面报错: 2016-03-21 14:12:18.941 [trace][tid:com.facebook. ...
- Arrays 类操作 Java 的数组排序
使用 Arrays 类操作 Java 中的数组 Arrays 类是 Java 中提供的一个工具类,在 java.util 包中.该类中包含了一些方法用来直接操作数组,比如可直接实现数组的排序.搜索等( ...
- FormsAuthentication.GetRedirectUrl 方法
https://msdn.microsoft.com/zh-cn/library/8a22t5t3(v=vs.80) FormsAuthentication.GetRedirectUrl 方法 .NE ...
- 使用Zipalign工具优化Android APK应用记录
生成的Android应用APK文件最好进行优化,因为APK包的本质是一个zip压缩文档,经过优化能使包内未压缩的数据有序的排列,从而减少应用程序运行时的内存消耗.我们可以使用Zipalign工具进行A ...
- Andropid自己定义组件-坐标具体解释
在做一个view背景特效的时候被坐标的各个获取方法搞晕了,几篇抄来抄去的博客也没弄非常清楚. 如今把整个总结一下. 事实上仅仅要把以下这张图看明确就没问题了. watermark/2/text/aHR ...
- html5中viewport使用
html5中viewport使用 转载自:http://www.maoegg.com/the-usage-of-viewport-in-html5/ 用html5开发移动应用时往往会遇到手机的分辨率或 ...
- SOAP 及其安全控制--转载
原文地址:http://my.oschina.net/huangyong/blog/287791 目录[-] 1. 基于用户令牌的身份认证 2. 基于数字签名的身份认证 3. SOAP 消息的加密与解 ...