您的位置:首页 > 数据库 > Mongodb

(最新修正版2011-7-25)使用MongoDB替换Log4net记录系统异常日志(转)

2011-12-09 13:11 621 查看
http://www.cnblogs.com/skyaspnet/archive/2011/03/22/1989969.html

自上次修改后日志系统已经稳定运行了23天

说明: 日志系统运行了一段时间以后,出现了几次mongodb服务无法启动的问题,删除data目录下的mongod.lock后才能成功重启服务,

初步判断资源发生了死锁,因此将 using (Mongo mongo =new Mongo(config.BuildConfiguration())) 写法修改为 try catch 形式,

修改之后系统正常运行十天,但是在6月29日再次发现mongodb服务无法正常启动的问题,再次将 Mongo类中插入记录的方法改为使用 mongo.Insert,

重新更新至服务器,效果有待进一步观察,希望遇到并成功解决这个问题的朋友能一起交流讨论这个问题,谢谢!

PS: 1. 更改了Mongodb数据库字符串连接方式,由 Server=127.0.0.1:6111 更改为 mongodb://127.0.0.1:6111

2. 升级Mongodb版本,由Windows 64位 1.8.0版本升级为Windows 64位 1.8.2 (版本升级可能也解决了存在的BUG)

由于对系统中日志记录模块使用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目录:

View Code

//定义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>
publicstaticvoid LogRecord(Exception ex)
{
Mongo mongoDBLog =null;
try
{
mongoDBLog =new Mongo(ConfigurationManager.AppSettings["mongoDBConfig"]);
mongoDBLog.Connect();
var dbLog = mongoDBLog.GetDatabase("USTALogs");

var collection = dbLog.GetCollection<USTALogs>(DateTime.Now.Date.ToString("yyyy-MM-dd"));

USTALogs ustaLogs =new USTALogs
{
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.Insert(ustaLogs);
}
catch (Exception mongoDBLogException)
{
//do something
}
finally
{
if (mongoDBLog !=null)
{
mongoDBLog.Disconnect();
mongoDBLog.Dispose();
}
}
}
复制代码

最后再需要一个按日期分页显示日志的功能即可,代码如下:

///<summary>
/// 按日期分页显示日志
///</summary>
///<param name="date"></param>
///<param name="pageSize"></param>
///<param name="pageNum"></param>
///<returns></returns>
publicstatic ResultSet ShowLogs(string date, int pageSize, int pageNum)
{
long resultCount =0;

IList docResultSet =new List<USTALogs>();

Mongo mongoDBLog =null;

try
{
mongoDBLog =new Mongo(ConfigurationManager.AppSettings["mongoDBConfig"]);
mongoDBLog.Connect();

var dbLog = mongoDBLog.GetDatabase("USTALogs");

var collection = dbLog.GetCollection<USTALogs>(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<USTALogs>();

}
catch (Exception mongoDBLogException)
{
          //do something
}
finally
{
if (mongoDBLog !=null)
{
mongoDBLog.Disconnect();
mongoDBLog.Dispose();
}
}

returnnew ResultSet { resultCount = resultCount, result = docResultSet };
}

}

#region 查询结果集实体类
///<summary>
/// 查询结果集实体类
///</summary>
publicclass ResultSet
{
public ResultSet()
{

}

publiclong resultCount
{
get;
set;
}

public IList result
{
get;
set;
}
}
#endregion

#region 日志实体类
///<summary>
/// 日志实体类
///</summary>
publicclass USTALogs
{

public USTALogs()
{

}

publicstring errorURL
{
get;
set;
}

publicstring accessIP
{
get;
set;
}

publicstring errorCode
{
get;
set;
}

publicstring errorObject
{
get;
set;
}

publicstring errorStackTrace
{
get;
set;
}

publicstring errorMethod
{
get;
set;
}

publicstring errorMessage
{
get;
set;
}

publicstring errorHelpLink
{
get;
set;
}

publicstring errorTime
{
get;
set;
}
}
#endregion
复制代码

最终效果图如下:



希望对大家有帮助:)
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: