使用MongoDB替换Log4net记录系统异常日志
由于对系统中日志记录模块使用Log4net 不太满意,最大的原因可能就是觉得它的文本记录模式很不好用,
查看也不方便,当然它也可以使用sqlite、access、系统事件等方式来记录,但是总觉得不是那么尽如人意,
因此想到使用MongoDB来完成这一工作,测试环境为win7、vs2010、.net framework 4.0 详细记录如下:
1. 首先在官方网站下载最新版本的MongoDB http://www.mongodb.org/downloads
在下载列表里选择适合你的版本,由于服务器是Windows Server 2008 R2 64位, 因此选择了Windows 64 bit版本。
2. MongoDB的安装
MongoDB的安装非常简单,首先将下载后的压缩包解压至任意目录,假定为d:\mongodb,在cmd窗口中进入d:\mongodb\bin目录,
输入:
mongod --dbpath d:\mongodb\data --logpath d:\mongodb\logs\mongodb.log --logappend --directoryperdb
--bind_ip 127.0.0.1 --port 6111 --install
然后执行,正常情况如下图,如出现安装错误,请检查文件权限并手工建立 dbpath目录与logpath目录:
再执行 net start "MongoDB" 即可启动服务。
有关于安装参数的说明:
--dbpath 是数据文件所在目录
--logpath 是日志文件所在文件路径,此参数必须为文件,不能为文件目录,否则会导致安装失败
以上两个参数必须设置
--logappend 日志以追加的方式写入
--directoryperdb 为每个数据库建立单独的目录
--bind_ip 绑定服务器IP,此参数为安全起见建议使用127.0.0.1,因为如果不设置的话,远程是可以连接的
--port 端口号
--install 以服务形式安装
如果需要删除 MongoDB 服务请使用 mongod --remove
3. MongoDB C#客户端的选择
客户端的选择原则自然是以谁强大、开源、更新快就选谁,因此选择 mongodb-csharp, git地址为:
https://github.com/samus/mongodb-csharp
下载后可以使用vs2010或者是vs2008打开程序,并生成我们所需要的 MongoDB.dll,我们的程序中将会引用它
此外,在mongodb-csharp程序中我们还可以找到分别用C#和VB.NET制作的两个Sample,可以帮助我们理解一些基本操作,示例程序注释说明如下:

//定义MongoDB配置生成器
var config = new MongoConfigurationBuilder();
// 设置映射关系
config.Mapping(mapping =>
{
mapping.DefaultProfile(profile =>
{
profile.SubClassesAre(t => t.IsSubclassOf(typeof(MyClass)));
});
mapping.Map<MyClass>();
mapping.Map<SubClass>();
});
//设置访问字符串,相当于SQL SERVER的连接字符串
config.ConnectionString("Server=127.0.0.1:6111");
//实例化一个Mongo操作类,用于完成对MongoDB的操作
using (Mongo mongo = new Mongo(config.BuildConfiguration()))
{
//连接
mongo.Connect();
try
{
//选择要使用的database,如果没有会自动建立
var db = mongo.GetDatabase("TestDb");
//获取TestDb所有表中类型为MyClass的记录集合
var collection = db.GetCollection<MyClass>();
MyClass square = new MyClass()
{
Corners = 4,
Name = "Square"
};
MyClass circle = new MyClass()
{
Corners = 0,
Name = "Circle"
};
SubClass sub = new SubClass()
{
Name = "SubClass",
Corners = 6,
Ratio = 3.43
};
collection.Save(square);
collection.Save(circle);
collection.Save(sub);
//使用Linq方式进行读取
var superclass = (from item in db.GetCollection<MyClass>("MyClass").Linq()
where item.Corners > 1
select item.Corners).ToList();
var subclass = (from item in db.GetCollection<SubClass>("MyClass").Linq()
where item.Ratio > 1
select item.Corners).ToList();
Console.WriteLine("Count by LINQ on typed collection: {0}", collection.Linq().Count(x => x.Corners > 1));
Console.WriteLine("Count by LINQ on typed collection2: {0}", db.GetCollection<SubClass>().Linq().Count(x => x.Corners > 1));
//Console.WriteLine("Count by LINQ on typed collection3: {0}", db.GetCollection<SubClass>().Count(new { Corners = Op.GreaterThan(1) }));
Console.WriteLine("Count on typed collection: {0}", collection.Count(new { Corners = Op.GreaterThan(1) }));
明白了这些基础之后,开发日志功能也就很容易了,代码如下:
/// <summary>
/// 记录日志
/// </summary>
/// <param name="ex">出错的信息</param>
public static void LogRecord(Exception ex)
{
using (var mongoDBLog = new Mongo(ConfigurationManager.AppSettings["mongoDBConfig"]))
{
try
{
mongoDBLog.Connect();
var dbLog = mongoDBLog.GetDatabase("Logs");//以天为单位进行建表,Logs为日志实体类
var collection = dbLog.GetCollection<Logs>(DateTime.Now.Date.ToString("yyyy-MM-dd"));
Logs log = new Logs
{
errorTime =DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"),
errorURL = HttpContext.Current.Request.Url.ToString(),
accessIP = HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"],
errorCode = System.Runtime.InteropServices.Marshal.GetHRForException(ex).ToString(),
errorObject = ex.Source,
errorStackTrace = ex.StackTrace,
errorMessage = ex.Message,
errorHelpLink = ex.HelpLink,
errorMethod = (ex.TargetSite==null?string.Empty:ex.TargetSite.ToString())
};
collection.Save(log);
}
catch (Exception mongoDBLogException)
{//此处需要处理当MongoDB无法连接时的一些操作
}
finally
{
mongoDBLog.Disconnect();
}
}
最后再需要一个按日期分页显示日志的功能即可,代码如下:
/// <summary>
/// 按日期分页显示日志
/// </summary>
/// <param name="date"></param>
/// <param name="pageSize"></param>
/// <param name="pageNum"></param>
/// <returns></returns>
public static ResultSet ShowLogs(string date, int pageSize, int pageNum)
{
long resultCount = 0;
IList docResultSet = new List<Logs>();
using (var mongoDBLog = new Mongo(ConfigurationManager.AppSettings["mongoDBConfig"]))
{
try
{
mongoDBLog.Connect();
var dbLog = mongoDBLog.GetDatabase("Logs");
var collection = dbLog.GetCollection<Logs>(date);
resultCount = collection.Count();
var queryResultSet = from p in (collection.Linq().Skip(pageSize * (pageNum-1)).Take(pageSize))
orderby p.errorTime descending
select p;
docResultSet = queryResultSet.ToList<Logs>();
}
catch (Exception mongoDBLogException)
{//此处需要处理当MongoDB无法连接时的一些操作
}
finally
{
mongoDBLog.Disconnect();
}
}
return new ResultSet { resultCount=resultCount,result=docResultSet};
}
}
public class ResultSet
{
public ResultSet()
{
}
public long resultCount
{
get;
set;
}
public IList result
{
get;
set;
}
}
最终效果图如下:
希望对大家有帮助:)
发表评论
请问你的xml配置?可否也显示一下