概要
cscの作法、調べてみた。
Securityのイベントログをリアルタイム監視してみた。
環境
windows10
写真
サンプルコード
using System;
using System.Collections.Generic;
using System.Diagnostics.Eventing.Reader;
using System.Windows.Forms;
using System.Drawing;
public partial class MainForm: Form {
private EventLogWatcher _watcher = null;
private TextBox _logTextBox;
public MainForm() {
Text = "セキュリティログ リアルタイム監視";
Size = new Size(600, 400);
_logTextBox = new TextBox {
Multiline = true,
Dock = DockStyle.Fill,
ScrollBars = ScrollBars.Vertical,
ReadOnly = true,
Font = new Font("Consolas", 10)
};
Controls.Add(_logTextBox);
}
protected override void OnShown(EventArgs e) {
base.OnShown(e);
StartMonitoring();
}
private void StartMonitoring() {
int[] targetEventIds = new int[] {
4624, 4625, 4672, 4648, 4720, 4732, 1102, 4719
};
List<string> idQueries = new List<string>();
foreach (int id in targetEventIds)
{
idQueries.Add("EventID=" + id);
}
string idQuery = string.Join(" or ", idQueries.ToArray());
string queryString = "*[System[" + idQuery + "]]";
EventLogQuery eventsQuery = new EventLogQuery("Security", PathType.LogName, queryString);
try
{
_watcher = new EventLogWatcher(eventsQuery);
_watcher.EventRecordWritten += new EventHandler<EventRecordWrittenEventArgs>(OnEventRecordWritten);
_watcher.Enabled = true;
MessageBox.Show("Securityログのリアルタイム監視を開始しました。", "情報", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
catch (EventLogNotFoundException)
{
MessageBox.Show("エラー: 'Security' ログチャネルが見つかりません。\n「管理者として実行」されているか確認してください。", "エラー", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
catch (Exception ex)
{
MessageBox.Show("エラーが発生しました: " + ex.Message, "エラー", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void OnEventRecordWritten(object sender, EventRecordWrittenEventArgs e) {
if (e.EventRecord != null)
{
EventRecord record = e.EventRecord;
string logMessage = string.Format("[{0}] ID: {1} - {2}\r\n", record.TimeCreated, record.Id, record.TaskDisplayName);
if (this.InvokeRequired)
{
this.BeginInvoke(new Action(() => UpdateLogText(logMessage)));
}
else
{
UpdateLogText(logMessage);
}
}
}
private void UpdateLogText(string message) {
if (_logTextBox != null && !_logTextBox.IsDisposed)
{
_logTextBox.AppendText(message);
}
}
protected override void OnFormClosing(FormClosingEventArgs e) {
if (_watcher != null)
{
_watcher.Enabled = false;
_watcher.Dispose();
}
base.OnFormClosing(e);
}
[STAThread]
public static void Main() {
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new MainForm());
}
}
以上。
