记录大数据量的日志时,可以使用队列来进行日志的记录。
数据库:MongoDB数据库【驱动:1.7】
具体实现方法:
//日志实体类
public class LogModel
{
/// <summary>
/// 创建日志模型
/// </summary>
/// <param name="LogId">日志id</param>
/// <param name="LogType">日子类型</param>
/// <param name="LogTime">日志记录时间</param>
/// <param name="LogContent">日志内容</param>
/// <returns></returns>
public static LogModel Create(int LogId, string LogType,
DateTime LogTime, string LogContent)
{
LogModel log = new LogModel();
log.LogId = LogId;
log.LogType = LogType;
log.LogTime = DateTime.Now.AddHours(8);
log.LogContent = LogContent;
return log;
}
//日志id
public int LogId { get; set; }
//日志类型
public string LogType { get; set; }
//日志写入时间
public DateTime LogTime { get; set; }
//日志内容
public string LogContent { get; set; }
}
static void Main(string[] args)
{
Console.WriteLine("请输入日志条数:");
int num = int.Parse(Console.ReadLine());
LogWrite(num);
}
private static Queue<LogModel> logQueue = new Queue<LogModel>();
/// <summary>
/// 写日志
/// </summary>
/// <param name="logNum">写入日志条数</param>
public static void LogWrite(int logNum)
{
string Msg = string.Empty;
logNum = logNum * 10;
//日志开始写入时间
DateTime dtstart = DateTime.Now;
Msg = "开始写入时间" + dtstart;
Console.WriteLine(Msg);
LogInQueue(logNum);
Console.WriteLine("日志写入结束");
Console.ReadKey();
}
public static void LogInQueue(int num)
{
for (int i = 1; i <= num; i++)
{
LogModel logmodel = CreateLog(i);
WriteQueue(logmodel);
}
}
/// <summary>
/// 日志写入(基于队列)
/// </summary>
/// <param name="model">日志模型</param>
public static void WriteQueue(LogModel model)
{
AddQueue(model);
//写入数据库:如果队列已满则写入数据库【此时队列的最大容量设置为10】
if (logQueue.Count >= 10)
{
DoSaveQueueData();
}
}
/// <summary>
/// 把日志模型加入队列
/// </summary>
/// <param name="model"></param>
public static void AddQueue(LogModel model)
{
lock (logQueue)
{
logQueue.Enqueue(model);
}
}
/// <summary>
/// 把队列中的数据写入数据库
/// </summary>
/// <param name="model"></param>
public static void DoSaveQueueData()
{
Task taskSave = new Task(() =>
{
SaveQueue();
});
taskSave.Start();
}
/// <summary>
/// 将日志写入数据库
/// </summary>
public static void SaveQueue()
{
lock (logQueue)
{
for (int i = 0; i < 10; i++)
{
if (logQueue.Count > 0)
{
Write(logQueue.Dequeue());
}
}
}
}
/// <summary>
/// 日志写入
/// </summary>
/// <param name="model">日志模型</param>
public static void Write(LogModel model)
{
//数据库连接地址
string connectionString = "mongodb://127.0.0.1:27017";
//数据库名称
string dbName = "testdb";
//表名
string tableName = "logtable";
if (model != null)
{
try
{
MongoDBHelper.Insert(connectionString, dbName, tableName, model);
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
}
}
/// <summary>
/// 制造日志数据
/// </summary>
/// <param name="i"></param>
/// <returns></returns>
public static LogModel CreateLog(int i)
{
LogModel logmodel = LogModel.Create(i,"Error",DateTime.Now,"Exception:空异常");
return logmodel;
}
最后结果: