按日期限制事件日志
本文关键字:事件 日志 日期 | 更新日期: 2023-09-27 18:07:01
我正在抓取事件日志,然后在数据网格中显示它们,但是对于大日志需要永远返回,所以我想限制过去24小时的日志,但我不确定如何做到这一点。我希望在遍历每个条目之前限制集合,因为那样做仍然需要很长时间。任何帮助都是非常感激的!!
namespace SysTools
{
public partial class LogViewer : Form
{
DataTable eventLog = new DataTable();
DataSet dataset1 = new DataSet();
private EventLog unhandledLogs;
public LogViewer(EventLog logs)
{
unhandledLogs = logs;
InitializeComponent();
}
private void LogViewer_Load(object sender, EventArgs e)
{
String currentLog = unhandledLogs.Log;
DataTable dataTable1 = new DataTable();
DataColumn column;
column = new DataColumn();
column.DataType = System.Type.GetType("System.String");
column.ColumnName = "Level";
dataTable1.Columns.Add(column);
column = new DataColumn();
column.DataType = System.Type.GetType("System.String");
column.ColumnName = "Category";
dataTable1.Columns.Add(column);
column = new DataColumn();
column.DataType = System.Type.GetType("System.DateTime");
column.ColumnName = "DateTime";
dataTable1.Columns.Add(column);
column = new DataColumn();
column.DataType = System.Type.GetType("System.String");
column.ColumnName = "Message";
dataTable1.Columns.Add(column);
dataTable1.Rows.Clear();
DateTime systemtime = new DateTime();
Int32 count = unhandledLogs.Entries.Count;
for (int currLogIndex = 0; currLogIndex <= unhandledLogs.Entries.Count; currLogIndex++)
{
DataRow drnew = dataTable1.NewRow();
try
{
EventLogEntry currLogEntrys = unhandledLogs.Entries[currLogIndex];
EventLogEntry currLogEntry = currLogEntrys;
string entrytype = currLogEntrys.EntryType.ToString();
drnew["Level"] = entrytype;
drnew["Category"] = currLogEntry.Source;
drnew["DateTime"] = currLogEntry.TimeGenerated;
drnew["Message"] = currLogEntry.Message;
dataTable1.Rows.Add(drnew);
}
catch { }
}
dataGridView1.DataSource = dataTable1;
dataTable1.DefaultView.Sort = ("DateTime asc");
}
}
}
看一下EventLogQuery和EventLogReader类。在下面的例子中,我从应用程序事件日志中读取过去24小时的日志,并将它们放入一个列表中。您可以轻松地根据自己的日志和需求进行调整。
注意,我正在做一些比较hack的事情来将日期转换为预期的格式(您应该改进它),但是看看我如何创建查询,然后只处理检索到的记录。
public void GetEvents()
{
string FormattedDateTime = string.Format("{0}-{1}-{2}T{3}:{4}:{5}.000000000Z",
DateTime.Now.Year,
DateTime.Now.Month.ToString("D2"),
DateTime.Now.AddDays(-1).Day.ToString("D2"),
DateTime.Now.Hour.ToString("D2"),
DateTime.Now.Minute.ToString("D2"),
DateTime.Now.Second.ToString("D2"));
string LogSource = @"Application";
string Query = "*[System[TimeCreated[@SystemTime >= '" + FormattedDateTime + "']]]";
var QueryResult = new EventLogQuery(LogSource, PathType.LogName, Query);
var Reader = new System.Diagnostics.Eventing.Reader.EventLogReader(QueryResult);
List<EventRecord> Events = new List<EventRecord>();
bool Reading = true;
while (Reading)
{
EventRecord Rec = Reader.ReadEvent();
if (Rec == null)
Reading = false;
Events.Add(Rec);
// You could add to your own collection here instead of adding to a list
}
}