Apr 23
Monitoring Your Event Log - The Code
So yesterday we talked about the event log, you could were you so inclined, just keep the event log open and periodically refresh it thereby keeping an ‘eye’ on the event log. However, in the end this is impractical. So what you do is access the event log in code and monitor the events you are interested in, then when one of them fires off you notify yourself via some mechanism that suits you. So how, you ask, might I monitor the event log in code? Well I am glad you asked, lets look at the code after the break.
Dim WithEvents securityLog As New System.Diagnostics.EventLog("Security")
Private Sub frmMain_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
securityLog.EnableRaisingEvents = True 'I know quite complicated, that is really the only line required to start monitoring the logs
End Sub
Private Sub Securitylog_EntryWritten(ByVal sender As Object, ByVal e As System.Diagnostics.EntryWrittenEventArgs) Handles securityLog.EntryWritten
''Security Event Logon
If (e.Entry.EventID = 4624) Then
MessageBox.Show("A Logon Event Happend")
End If
End Sub
So now if you want to monitor a particular event log (security, system, etc) you just create a new System.Diagnostics.EventLog with the name of that log passed in as a string as you seen in the first line. Then you tell that class you want it to raise events as seen in the Form_Load. Then you filter the events using ‘if’ statements and vuala, you are getting your event log events in real time piped into your application.