Plateforme Level Extreme
Abonnement
Profil corporatif
Produits & Services
Support
Légal
English
Pulling out event viewer logs
Message
De
29/04/2015 18:19:51
 
 
À
Tous
Information générale
Forum:
ASP.NET
Catégorie:
Autre
Titre:
Pulling out event viewer logs
Versions des environnements
Environment:
VB 9.0
OS:
Windows 8.1
Network:
Windows 2008 Server
Database:
MS SQL Server
Application:
Web
Divers
Thread ID:
01619242
Message ID:
01619242
Vues:
36
Here is a class to pull out event viewer logs. You can adjust as needed to fit your own needs. The entry point would need to be adjust as the class is supposed to be used under the framework. It will either add each event into a table or return the entire content as a string. The class uses loInsertRow to insert into a framework class. You can easily adjust that part as well for your own needs.

This allows you to display on your Web site, for example, all the events, either in one big list or in a relational way, to provide real time event viewer view on your Web site. That needs to have a robot which would run in the background to populate the table. This allows to avoid going or asking someone to go on RDP directly, which we should not do anyway on a production server, and to bypass various limits such as maximum number of events in the Event Viewer log as this goes into a table so you can keep them all.
Imports System.Diagnostics.Eventing.Reader
Imports System.Text

Public Enum LogAttribute
    Application = 1
    System = 2
End Enum

Public Class EventLogManager

    Public cDomain As String = ""
    Public cMessage As String = ""
    Public cPassword As String = ""
    Public cQuerystring As String = ""
    Public cResult As String = ""
    Public cServer As String = ""
    Public cSource As String = ""
    Public cUsername As String = ""
    Public lBookmark As Boolean = True
    Public lActivityID As Boolean = True
    Public lComputer As Boolean = True
    Public lKeyword As Boolean = True
    Public lKeywordDisplayName As Boolean = True
    Public lLevel As Boolean = True
    Public lLevelCritical As Boolean = True
    Public lLevelDisplayName As Boolean = True
    Public lLevelError As Boolean = True
    Public lLevelInformation As Boolean = False
    Public lLevelWarning As Boolean = True
    Public lLogError As Boolean = True
    Public lOpCode As Boolean = True
    Public lOpCodeDisplayName As Boolean = True
    Public lProcessID As Boolean = True
    Public lProperty As Boolean = True
    Public lProviderID As Boolean = True
    Public lQualifier As Boolean = True
    Public lRecordID As Boolean = True
    Public lRelatedActivityID As Boolean = True
    Public lSource As Boolean = True
    Public lTransferToTable As Boolean = False
    Public lTask As Boolean = True
    Public lTaskDisplayName As Boolean = False
    Public lThreadID As Boolean = True
    Public lTimeCreated As Boolean = True
    Public lUserID As Boolean = False
    Public lVersion As Boolean = True
    Public nEventID As Integer = 0
    Public nHour As Integer = 24
    Public nLog As LogAttribute
    Public nNoServer As Integer = 0
    Public nRecordID As Integer = 0
    Public nType As EventLogEntryType = EventLogEntryType.Information
    Private cUnableToConnectToServer As String = ""
    Private cYouNeedToDefineTheCLogProperty As String = ""
    Private cYouNeedToDefineTheNHourProperty As String = ""
    Private cYouNeedToDefineTheNNoServerProperty As String = ""
    Private nLanguage As Integer = 1
    Private oApp As App = Nothing
    Private oProcess As LXProcess = Nothing

    ' This is when we access the class in a desktop mode
    Sub New(ByVal toApplication As App)
        oApp = toApplication
        nLanguage = oApp.nLanguage
        Init()
    End Sub

    ' This is when we access the class in a Web or Web Service mode
    Sub New(ByVal toProcess As LXProcess)
        oProcess = toProcess
        oApp = oProcess.oApp
        nLanguage = oProcess.nLanguage
        Init()
    End Sub

    ' Save the log attribute being used
    Friend Sub New(ByVal tnLog As LogAttribute)
        nLog = tnLog
    End Sub

    ' Initialization
    Private Function Init() As Boolean

        ' Based on the language
        Select Case nLanguage

            ' English
            Case 1
                cUnableToConnectToServer = "Unable to connect to server ##Server##."
                cYouNeedToDefineTheCLogProperty = "You need to define the cLog property."
                cYouNeedToDefineTheNHourProperty = "You need to define the nHour or nRecordID property."
                cYouNeedToDefineTheNNoServerProperty = "You need to define the nNoServer property."

                ' French
            Case 2
                cUnableToConnectToServer = "Impossible de connecter au serveur  ##Server##."
                cYouNeedToDefineTheCLogProperty = "Vous devez définir la propriété cLog."
                cYouNeedToDefineTheNHourProperty = "Vous devez définir la propriété nHour ou nRecordID."
                cYouNeedToDefineTheNNoServerProperty = "Vous devez définir la propriété nNoServer ou nRecordID."

                ' Spanish
            Case 3
                cUnableToConnectToServer = "Unable to connect to server ##Server##."
                cYouNeedToDefineTheCLogProperty = "You need to define the cLog property."
                cYouNeedToDefineTheNHourProperty = "You need to define the nHour or nRecordID property."
                cYouNeedToDefineTheNNoServerProperty = "You need to define the nNoServer property."

                ' Portuguese
            Case 4
                cUnableToConnectToServer = "Unable to connect to server ##Server##."
                cYouNeedToDefineTheCLogProperty = "You need to define the cLog property."
                cYouNeedToDefineTheNHourProperty = "You need to define the nHour or nRecordID property."
                cYouNeedToDefineTheNNoServerProperty = "You need to define the nNoServer property."

        End Select

        Return True
    End Function

    ' Add an entry in the log
    Public Function Add() As Boolean
        Dim lcLog As String = ""
        Dim loEventLog As EventLog = New EventLog()

        ' Reset the values
        cMessage = ""

        ' Based on the log
        Select Case nLog

            ' Application
            Case 1
                lcLog = "Application"

                ' System
            Case 2
                lcLog = "System"

        End Select

        ' If the event log does not exist
        If Not EventLog.SourceExists(cSource) Then

            ' Create log 
            EventLog.CreateEventSource(cSource, lcLog)

        End If

        ' Write to the log 
        EventLog.WriteEntry(cSource, cMessage, nType, nEventID)

        Return True
    End Function

    ' Retrieve events from the log
    Public Function RetrieveEvent() As Boolean
        Dim lcDomain As String = ""
        Dim lcLevel As String = ""
        Dim lcLog As String = ""
        Dim lcMessage As String = ""
        Dim lcPassword As String = ""
        Dim lcQueryString As String = ""
        Dim lcServer As String = ""
        Dim lcUsername As String = ""
        Dim lcWhere As String = ""
        Dim llSuccess As Boolean = False
        Dim lnLevel As Integer = 0
        Dim lnNoEventViewerLevel As Integer = 0
        Dim lnRecordID As Integer = 0
        Dim lnTimeFrame As Double = 0
        Dim loEventLogQuery As EventLogQuery = Nothing
        Dim loEventLogReader As EventLogReader = Nothing
        Dim loEventLogRecord As EventLogRecord = Nothing
        Dim loEventLogSession As EventLogSession = Nothing
        Dim loEventRecord As EventRecord = Nothing
        Dim loInsertRow As InsertRow = Nothing
        Dim loSecurity As Security = Nothing
        Dim loStringBuilder As StringBuilder = New StringBuilder

        ' Get the proper definition as per the current scope
        If oProcess Is Nothing Then
            loInsertRow = New InsertRow(oApp)
            loSecurity = New Security(oApp)
        Else
            loInsertRow = New InsertRow(oProcess)
            loSecurity = New Security(oProcess)
        End If

        ' Reset the values
        cMessage = ""
        cQuerystring = ""
        cResult = ""

        ' Initialization
        lcDomain = Trim(cDomain)
        lcPassword = Trim(cPassword)
        lcServer = Trim(cServer)
        lcUsername = Trim(cUsername)
        lnRecordID = nRecordID
        lnTimeFrame = nHour

        ' Based on the log
        Select Case nLog

            ' Application
            Case 1
                lcLog = "Application"

                ' System
            Case 2
                lcLog = "System"

        End Select

        ' If the cLog property has not been defined
        If lcLog.Length = 0 Then
            cMessage = cYouNeedToDefineTheCLogProperty
            Return False
        End If

        ' If the nHour property has not been defined
        If lnTimeFrame = 0 Then

            ' If the nRecordID property has not been defined
            If lnRecordID = 0 Then
                cMessage = cYouNeedToDefineTheNHourProperty
                Return False
            End If

        End If

        ' If we transfer to table
        If lTransferToTable Then

            ' If the nNoServer has not been defined
            If nNoServer = 0 Then
                cMessage = cYouNeedToDefineTheNNoServerProperty
                Return False
            End If

        End If

        ' If we need the critical messages
        If lLevelCritical Then
            lcLevel = "Level=1"
        End If

        ' If we need the error messages
        If lLevelError Then

            ' If we have a level
            If lcLevel.Length > 0 Then
                lcLevel = lcLevel + " or "
            End If

            lcLevel = lcLevel + "Level=2"
        End If

        ' If we need the warning messages
        If lLevelWarning Then

            ' If we have a level
            If lcLevel.Length > 0 Then
                lcLevel = lcLevel + " or "
            End If

            lcLevel = lcLevel + "Level=3"
        End If

        ' If we need the information messages
        If lLevelInformation Then

            ' If we have a level
            If lcLevel.Length > 0 Then
                lcLevel = lcLevel + " or "
            End If

            lcLevel = lcLevel + "Level=0"
        End If

        ' If the nHour property has been defined
        If lnTimeFrame > 0 Then
            lnTimeFrame = lnTimeFrame * 60 * 60
            lnTimeFrame = lnTimeFrame * 1000
            lcWhere = "        *[System[(" + lcLevel + ") and TimeCreated[timediff(@SystemTime) <= " + lnTimeFrame.ToString + "]]]" + oApp.cCR
        Else
            lcWhere = "        *[System[(" + lcLevel + ") and EventRecordID>" + lnRecordID.ToString + "]]" + oApp.cCR
        End If

        ' Initialization
        lcQueryString = "<QueryList>" + oApp.cCR + _
         "  <Query Id=""0"" Path=""" + lcLog + """>" + oApp.cCR + _
         "    <Select Path=""" + lcLog + """>" + oApp.cCR + _
         lcWhere + _
             "    </Select>" + oApp.cCR + _
         "  </Query>" + oApp.cCR + _
         "</QueryList>"

        Try

            ' If we have a username
            If lcUsername.Length > 0 Then

                ' If we cannot execute the method
                loSecurity.cString = lcPassword
                If Not loSecurity.GetSecureString() Then
                    cMessage = loSecurity.cMessage
                    Return False
                End If

                loEventLogSession = New EventLogSession(lcServer, lcDomain, lcUsername, loSecurity.oSecureString, SessionAuthentication.[Default])
            End If

            loEventLogQuery = New EventLogQuery(lcLog, PathType.LogName, lcQueryString)
            loEventLogQuery.ReverseDirection = True

            ' If we have a username
            If lcUsername.Length > 0 Then
                loEventLogQuery.Session = loEventLogSession
            End If

            Try
                loEventLogReader = New EventLogReader(loEventLogQuery)

                ' Initialization
                loEventRecord = loEventLogReader.ReadEvent()

                ' For each record
                While Not loEventRecord Is Nothing

                    ' Cast the EventRecord object as an EventLogRecord object to access the EventLogRecord class properties
                    loEventLogRecord = CType(loEventRecord, EventLogRecord)

                    ' Initialization
                    lnLevel = Val(loEventRecord.Level.ToString)

                    ' If we transfer into a table
                    If lTransferToTable Then

                        ' Based on the level
                        Select Case lnLevel

                            ' Information
                            Case 0
                                lnNoEventViewerLevel = 1

                                ' Critical
                            Case 1
                                lnNoEventViewerLevel = 4

                                ' Error
                            Case 2
                                lnNoEventViewerLevel = 2

                                ' Warning
                            Case 3
                                lnNoEventViewerLevel = 3

                        End Select

                        ' Insert a record in EventViewer
                        loInsertRow.cTable = "EventViewer"
                        loInsertRow.ParameterAdd("NoServer", nNoServer)
                        loInsertRow.ParameterAdd("NoEventViewerLog", nLog)
                        loInsertRow.ParameterAdd("NoEventViewerLevel", lnNoEventViewerLevel)
                        loInsertRow.ParameterAdd("ID", loEventRecord.Id)
                        loInsertRow.ParameterAdd("Source", loEventRecord.ProviderName)
                        loInsertRow.ParameterAdd("Description", loEventRecord.FormatDescription())

                        ' If we need the Activity ID
                        If lActivityID Then
                            loInsertRow.ParameterAdd("ActivityID", loEventRecord.ActivityId.ToString)
                        End If

                        ' If we need the Bookmark
                        If lBookmark Then
                            loInsertRow.ParameterAdd("Bookmark", loEventRecord.Bookmark.ToString)
                        End If

                        ' If we need the Keywords
                        If lKeyword Then
                            loInsertRow.ParameterAdd("Keyword", loEventRecord.Keywords)
                        End If

                        ' If we need the Keywords display name
                        If lKeywordDisplayName Then
                            loInsertRow.ParameterAdd("KeywordDisplayName", loEventRecord.KeywordsDisplayNames.ToString)
                        End If

                        ' If we need the Level display name
                        If lLevelDisplayName Then
                            loInsertRow.ParameterAdd("LevelDisplayName", loEventRecord.LevelDisplayName)
                        End If

                        ' If we need the Computer
                        If lComputer Then
                            loInsertRow.ParameterAdd("Computer", loEventRecord.MachineName)
                        End If

                        ' If we need the Op code
                        If lOpCode Then
                            loInsertRow.ParameterAdd("OpCode", loEventRecord.Opcode)
                        End If

                        ' If we need the Op code display name
                        If lOpCodeDisplayName Then
                            loInsertRow.ParameterAdd("OpCodeDisplayName", loEventRecord.OpcodeDisplayName)
                        End If

                        ' If we need the Process ID
                        If lProcessID Then
                            loInsertRow.ParameterAdd("ProcessID", loEventRecord.ProcessId)
                        End If

                        ' If we need the Properties
                        If lProperty Then
                            loInsertRow.ParameterAdd("Property", loEventRecord.Properties.ToString)
                        End If

                        ' If we need the Provider ID
                        If lProviderID Then
                            loInsertRow.ParameterAdd("ProviderID", loEventRecord.ProviderId.ToString)
                        End If

                        ' If we need the Qualifiers
                        If lQualifier Then
                            loInsertRow.ParameterAdd("Qualifier", loEventRecord.Qualifiers)
                        End If

                        ' If we need the Record ID
                        If lRecordID Then
                            loInsertRow.ParameterAdd("RecordID", loEventRecord.RecordId)
                        End If

                        ' If we need the Related activity ID
                        If lRelatedActivityID Then
                            loInsertRow.ParameterAdd("RelatedActivityID", loEventRecord.RelatedActivityId.ToString)
                        End If

                        ' If we need the Task
                        If lTask Then
                            loInsertRow.ParameterAdd("Task", loEventRecord.Task)
                        End If

                        ' If we need the Task display name
                        If lTaskDisplayName Then
                            loInsertRow.ParameterAdd("TaskDisplayName", loEventRecord.TaskDisplayName)
                        End If

                        ' If we need the Thread ID
                        If lThreadID Then
                            loInsertRow.ParameterAdd("ThreadID", loEventRecord.ThreadId)
                        End If

                        ' If we need the Time created
                        If lTimeCreated Then
                            loInsertRow.ParameterAdd("TimeCreated", loEventRecord.TimeCreated)
                        End If

                        ' If we need the User ID
                        If lUserID Then
                            loInsertRow.ParameterAdd("UserID", loEventRecord.UserId.ToString)
                        End If

                        ' If we need the Version
                        If lVersion Then
                            loInsertRow.ParameterAdd("Version", loEventRecord.Version.ToString)
                        End If

                        If Not loInsertRow.InsertRow() Then
                            Return False
                        End If

                    Else

                        ' Initialization
                        loStringBuilder.Append("Event ID: " + loEventRecord.Id.ToString + oApp.cCR)
                        loStringBuilder.Append("Publisher: " + loEventRecord.ProviderName + oApp.cCR)
                        loStringBuilder.Append("Description: " + loEventRecord.FormatDescription() + oApp.cCR)

                        ' If we need the Activity ID
                        If lActivityID Then
                            loStringBuilder.Append("Activity ID: " + loEventRecord.ActivityId.ToString + oApp.cCR)
                        End If

                        ' If we need the Bookmark
                        If lBookmark Then
                            loStringBuilder.Append("Bookmark: " + loEventRecord.Bookmark.ToString + oApp.cCR)
                        End If

                        ' If we need the Keywords
                        If lKeyword Then
                            loStringBuilder.Append("Keywords: " + loEventRecord.Keywords.ToString + oApp.cCR)
                        End If

                        ' If we need the Keywords display name
                        If lKeywordDisplayName Then
                            loStringBuilder.Append("Keywords display name: " + loEventRecord.KeywordsDisplayNames.ToString + oApp.cCR)
                        End If

                        ' If we need the Level
                        If lLevel Then
                            loStringBuilder.Append("Level: " + lnLevel.ToString + oApp.cCR)
                        End If

                        ' If we need the Level display name
                        If lLevelDisplayName Then
                            loStringBuilder.Append("Level display name: " + loEventRecord.LevelDisplayName + oApp.cCR)
                        End If

                        ' If we need the Computer
                        If lComputer Then
                            loStringBuilder.Append("Computer: " + loEventRecord.MachineName + oApp.cCR)
                        End If

                        ' If we need the Op code
                        If lOpCode Then
                            loStringBuilder.Append("Op code: " + loEventRecord.Opcode.ToString + oApp.cCR)
                        End If

                        ' If we need the Op code display name
                        If lOpCodeDisplayName Then
                            loStringBuilder.Append("Op code display name: " + loEventRecord.OpcodeDisplayName + oApp.cCR)
                        End If

                        ' If we need the Process ID
                        If lProcessID Then
                            loStringBuilder.Append("Process ID: " + loEventRecord.ProcessId.ToString + oApp.cCR)
                        End If

                        ' If we need the Properties
                        If lProperty Then
                            loStringBuilder.Append("Properties: " + loEventRecord.Properties.ToString + oApp.cCR)
                        End If

                        ' If we need the Provider ID
                        If lProviderID Then
                            loStringBuilder.Append("Provider ID: " + loEventRecord.ProviderId.ToString + oApp.cCR)
                        End If

                        ' If we need the Qualifiers
                        If lQualifier Then
                            loStringBuilder.Append("Qualifiers: " + loEventRecord.Qualifiers.ToString + oApp.cCR)
                        End If

                        ' If we need the Record ID
                        If lRecordID Then
                            loStringBuilder.Append("Record ID: " + loEventRecord.RecordId.ToString + oApp.cCR)
                        End If

                        ' If we need the Related activity ID
                        If lRelatedActivityID Then
                            loStringBuilder.Append("Related activity ID: " + loEventRecord.RelatedActivityId.ToString + oApp.cCR)
                        End If

                        ' If we need the Task
                        If lTask Then
                            loStringBuilder.Append("Task: " + loEventRecord.Task.ToString + oApp.cCR)
                        End If

                        ' If we need the Task display name
                        If lTaskDisplayName Then
                            loStringBuilder.Append("Task display name: " + loEventRecord.TaskDisplayName + oApp.cCR)
                        End If

                        ' If we need the Thread ID
                        If lThreadID Then
                            loStringBuilder.Append("Thread ID: " + loEventRecord.ThreadId.ToString + oApp.cCR)
                        End If

                        ' If we need the Time created
                        If lTimeCreated Then
                            loStringBuilder.Append("Time created: " + oApp.WritTime(loEventRecord.TimeCreated) + oApp.cCR)
                        End If

                        ' If we need the User ID
                        If lUserID Then
                            loStringBuilder.Append("User ID: " + loEventRecord.UserId.ToString + oApp.cCR)
                        End If

                        ' If we need the Version
                        If lVersion Then
                            loStringBuilder.Append("Version: " + loEventRecord.Version.ToString + oApp.cCR)
                        End If

                    End If

                    loEventRecord = loEventLogReader.ReadEvent()

                    loStringBuilder.Append(oApp.cCR)
                End While

                llSuccess = True
            Catch loException As Exception
                lcMessage = cUnableToConnectToServer
                lcMessage = oApp.StrTran(lcMessage, "##Server##", lcServer)

                ' If we log the error
                If lLogError Then

                    ' Get the proper definition as per the current scope
                    If oProcess Is Nothing Then
                        oApp.ErrorSetup(loException, lcMessage)
                    Else
                        oProcess.ErrorSetup(loException, lcMessage)
                    End If

                End If

                cMessage = lcMessage
            End Try

        Catch loException As Exception

            ' If we log the error
            If lLogError Then

                ' Get the proper definition as per the current scope
                If oProcess Is Nothing Then
                    oApp.ErrorSetup(loException)
                Else
                    oProcess.ErrorSetup(loException)
                End If

            End If

            cMessage = loException.Message
        End Try

        ' Reset the values
        cDomain = ""
        cPassword = ""
        cServer = ""
        cUsername = ""
        lActivityID = True
        lBookmark = True
        lComputer = True
        lKeyword = True
        lKeywordDisplayName = True
        lLevel = True
        lLevelCritical = True
        lLevelDisplayName = True
        lLevelError = True
        lLevelInformation = False
        lLevelWarning = True
        lOpCode = True
        lOpCodeDisplayName = True
        lProcessID = True
        lProperty = True
        lProviderID = True
        lSource = True
        lQualifier = True
        lRecordID = True
        lRelatedActivityID = True
        lTask = True
        lTaskDisplayName = False
        lThreadID = True
        lTimeCreated = True
        lTransferToTable = False
        lUserID = False
        lVersion = True
        nHour = 24
        nNoServer = 0
        nRecordID = 0

        ' Initialization
        cResult = loStringBuilder.ToString
        cQuerystring = lcQueryString

        Return llSuccess
    End Function

End Class
I have defined my robot to always query from the most recent record I have in the table. So, I will never get the same record.

You can call it like this:
        Dim loEventLogManager As Framework.EventLogManager = New Framework.EventLogManager(oApp)

            loEventLogManager.nLog = Framework.LogAttribute.Application

            ' If we do have a record ID
            If lnRecordID > 0 Then
                loEventLogManager.nRecordID = lnRecordID
                loEventLogManager.nHour = 0
            Else
                loEventLogManager.nHour = 24 * 14
            End If

            loEventLogManager.lActivityID = True
            loEventLogManager.lBookmark = True
            loEventLogManager.lComputer = True
            loEventLogManager.lKeyword = True
            loEventLogManager.lKeywordDisplayName = True
            loEventLogManager.lLevel = True
            loEventLogManager.lLevelDisplayName = True
            loEventLogManager.lOpCode = True
            loEventLogManager.lOpCodeDisplayName = True
            loEventLogManager.lProcessID = True
            loEventLogManager.lProperty = True
            loEventLogManager.lProviderID = True
            loEventLogManager.lQualifier = True
            loEventLogManager.lRecordID = True
            loEventLogManager.lRelatedActivityID = True
            loEventLogManager.lTask = True
            loEventLogManager.lTaskDisplayName = True
            loEventLogManager.lThreadID = True
            loEventLogManager.lTimeCreated = True
            loEventLogManager.lUserID = True
            loEventLogManager.lVersion = True
            loEventLogManager.cUsername = lcUsername
            loEventLogManager.cPassword = lcPassword
            loEventLogManager.cServer = loRow("Title")
            loEventLogManager.lTransferToTable = True
            loEventLogManager.nNoServer = loRow("Numero")
            If Not loEventLogManager.RetrieveEvent() Then
            End If
I am not sure if this related to our UAT environment or if this is subject to happen on a regular basis, but this section of code will not be able to connect to the remote server on occasional basis. My robot runs every minute and once every 15 minutes, I have some unable to connect to various servers:
            Try
                loEventLogReader = New EventLogReader(loEventLogQuery)
So, it looks I would need to simply ignore those failures and collect the data on the next loop, whenever this is the case. If someone see something to enhance that would avoid that situation, you may let me know.
Michel Fournier
Level Extreme Inc.
Designer, architect, owner of the Level Extreme Platform
Subscribe to the site at https://www.levelextreme.com/Home/DataEntry?Activator=55&NoStore=303
Subscription benefits https://www.levelextreme.com/Home/ViewPage?Activator=7&ID=52
Suivant
Répondre
Fil
Voir

Click here to load this message in the networking platform