日志记录类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 ...
随机推荐
- Hadoop项目开发环境搭建(Eclipse\MyEclipse + Maven)
写在前面的话 可详细参考,一定得去看 HBase 开发环境搭建(Eclipse\MyEclipse + Maven) Zookeeper项目开发环境搭建(Eclipse\MyEclipse + Mav ...
- Java之字节输入流和输出流
package IODemo; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOEx ...
- Mysql安装详解
1.MySQL三种安装方式 Rpm包安装 免编译二进制包安装 源码编译安装 1.1.安装环境 Red Hat Enterprise Linux Server release 6.4 2.安装介绍 2. ...
- 射频识别技术漫谈(1)——概念、分类
现代社会智能卡已经渗透到生活的方方面面,公交卡.考勤卡.身份证.手机卡等等数不胜数. 智能卡按使用时是否和读卡器接触可分为接触式智能卡和非接触式智能卡,接触式智能卡上有6-8个触点,使用时插在卡 ...
- placeholder 兼容IE9以下版本 包含pasword
<!doctype html> <html lang="en"> <head> <meta charset="UTF-8&quo ...
- Windows 窗体启动和关闭的事件顺序
本文系转载学习. 对于关注对 Windows 窗体应用程序中引发的每个事件按次序进行处理的开发人员来说,事件引发的顺序特别重要.当某种情况需要小心处理事件时(如重绘窗体的某些部分时),必须知道事件在运 ...
- Windows 环境下基于 Redis 的 Celery 任务调度模块的实现
搭建环境: Windows-x64 10 Celery 3.1.23 Celery-with-redis 3.0 Redis-win32-win64 2.4.5 实现步骤: 1.安装 Redis ...
- 实例:ABAP Tree Control 使用与ALV Grid对象关联
Tree Control 是最常用的Windows控件之一,在其他语言中成为"Tree View"等,ABAP的 Tree Contiol 能实现类似的功能. 本文主要介绍一下内容 ...
- web项目设计中框架的数据流
这张图虽然简单,但是很好的说明了一个web框架,需要实现那些模块. 图片来自 <Go Web编程>
- Windows ICS 服务无法启动问题解决
防火墙打不开肯定是"windows Firewall"服务没有启动.ICS服务启动不了能够通过下面方法解决: 1.找到本地连接,单击左键--属性--共享--勾选(√)--确定,如以 ...