按日期限制事件日志
Posted
技术标签:
【中文标题】按日期限制事件日志【英文标题】:Limit EventLogs by Date 【发布时间】:2014-07-27 22:17:54 【问题描述】:我正在抓取事件日志,然后将它们显示在数据网格中,但是对于大型日志,它需要永远返回,所以我想将日志限制在最后 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");
【问题讨论】:
【参考方案1】:查看EventLogQuery 和EventLogReader 类。在下面的示例中,我正在从应用程序事件日志中读取过去 24 小时的日志,并将它们放入一个列表中。您可以轻松适应自己的日志和需求。
请注意,我正在做一些适当的事情来将日期转换为预期的格式(您应该改进它),但请查看我是如何创建查询然后只处理检索到的记录的。
public void GetEvents()
string FormattedDateTime = string.Format("0-1-2T3: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
【讨论】:
如果还需要在查询中添加提供者名称,如何修改查询?以上是关于按日期限制事件日志的主要内容,如果未能解决你的问题,请参考以下文章