Colaboraciones en el Guille

Lectura y escritura en el log de eventos de Windows

[Como utilizar el System.Diagnostics para acceder (lectura/escritura) al los de eventos del Windows]

 

Fecha: 29/Nov/2005 (29-11-2005)
Autor: Walter Damian Mompo - wdmompo@fibertel.com.ar

 


En este artículo veremos como las formas de acceso al log de eventos de Windows, tanto lectura como escritura del mismo, a través del namespace System.Diagnostics.

Antes que nada, tanto para la lectura como para la grabación, importar el siguiente namespace:

Imports System.Diagnostics

 

Grabar en el EventLog:

Para el ejemplo se utilizó un TextBox (txtEventLog) y un Button (btnGrabar), y se codificó en el evento Click del Button.

Primero hay que saber las siguientes propiedades del evento:
Source: de esta manera identificaremos de donde viene la información.
Log: define en que carpeta del log quedará la información, estas pueden ser Application, Security, System o alguna definida por el usuario.

Pasando al código, lo primero que hay que hacer, es verificar si existe el log, de no ser así, crearlo, en source ponemos el nombre de la aplicación y elegimos la carpeta Application para log.

If Not EventLog.SourceExists(Application.ProductName) Then
    EventLog.CreateEventSource(Application.ProductName, "Application")
End If

Instanciamos la clase EventLog

Dim eLog As EventLog = New EventLog

Le indicamos el source que queremos utilizar y verificamos si el mismo está siendo utilizado por otra aplicación

eLog.Source = Application.ProductName
If eLog.Log <> "Application" Then
    MsgBox("El source está siendo usado por otra aplicación.")
    Exit Sub
End If

Y para finalizar, escribimos en el EventLog

eLog.WriteEntry(txtEventLog.Text, EventLogEntryType.Information)

Los tipos de EventLogEntryType son Error, FailureAudit, Information, SuccessAudit y Warning.

 

Leer del EventLog:

Para el ejemplo se utilizó un TextBox (txtEventLog), un Button (btnLeer) y una ProgressBar (ProgressBar1), y se codificó en el evento Click del Button.

En este caso encontramos una nueva propiedad:
MachineName: identificaremos la PC de donde se leerá el EventLog.

Primero verificaremos la existencia del Log y el Source

If Not EventLog.Exists("Application", ".") Then
    MsgBox("El log no existe")
    Exit Sub
End If
If Not EventLog.SourceExists(Application.ProductName, ".") Then
    MsgBox("El log no existe")
    Exit Sub
End If

Instanciamos EventLog y le seteamos las propiedades Log y MachineName

Dim eLog As EventLog = New EventLog
eLog.Log = "Application"
eLog.MachineName = "."

Instanciamos la clase EventLogEntry

Dim elEntry As EventLogEntry

Y por último recorremos las EventLogEntry, filtrando por Source, y mostramos los mensajes

Dim lEntryActual As Long = 0
For Each elEntry In eLog.Entries
    lEntryActual += 1
    txtEventLog.Text = lEntryActual.ToString & " / " & eLog.Entries.Count.ToString
    txtEventLog.Refresh()
    ProgressBar1.Maximum = eLog.Entries.Count
    ProgressBar1.Value = lEntryActual
    If elEntry.Source = Application.ProductName Then
        MsgBox(elEntry.Message)
    End If
Next

 

Código completo del ejemplo:

Imports System
Imports System.Diagnostics

Public Class frmEventLog
    Inherits System.Windows.Forms.Form

#Region " Windows Form Designer generated code "

    Public Sub New()
        MyBase.New()

        'This call is required by the Windows Form Designer.
        InitializeComponent()

        'Add any initialization after the InitializeComponent() call

    End Sub

    'Form overrides dispose to clean up the component list.
    Protected Overloads Overrides Sub Dispose(ByVal disposing As Boolean)
        If disposing Then
            If Not (components Is Nothing) Then
                components.Dispose()
            End If
        End If
        MyBase.Dispose(disposing)
    End Sub

    'Required by the Windows Form Designer
    Private components As System.ComponentModel.IContainer

    'NOTE: The following procedure is required by the Windows Form Designer
    'It can be modified using the Windows Form Designer.  
    'Do not modify it using the code editor.
    Friend WithEvents txtEventLog As System.Windows.Forms.TextBox
    Friend WithEvents btnGrabar As System.Windows.Forms.Button
    Friend WithEvents btnLeer As System.Windows.Forms.Button
    Friend WithEvents ProgressBar1 As System.Windows.Forms.ProgressBar
    <System.Diagnostics.DebuggerStepThrough()> Private Sub InitializeComponent()
        Me.txtEventLog = New System.Windows.Forms.TextBox
        Me.btnGrabar = New System.Windows.Forms.Button
        Me.btnLeer = New System.Windows.Forms.Button
        Me.ProgressBar1 = New System.Windows.Forms.ProgressBar
        Me.SuspendLayout()
        '
        'txtEventLog
        '
        Me.txtEventLog.Location = New System.Drawing.Point(8, 8)
        Me.txtEventLog.Multiline = True
        Me.txtEventLog.Name = "txtEventLog"
        Me.txtEventLog.Size = New System.Drawing.Size(616, 88)
        Me.txtEventLog.TabIndex = 0
        Me.txtEventLog.Text = ""
        '
        'btnGrabar
        '
        Me.btnGrabar.Location = New System.Drawing.Point(8, 104)
        Me.btnGrabar.Name = "btnGrabar"
        Me.btnGrabar.TabIndex = 1
        Me.btnGrabar.Text = "&Grabar"
        '
        'btnLeer
        '
        Me.btnLeer.Location = New System.Drawing.Point(96, 96)
        Me.btnLeer.Name = "btnLeer"
        Me.btnLeer.TabIndex = 2
        Me.btnLeer.Text = "&Leer"
        '
        'ProgressBar1
        '
        Me.ProgressBar1.Location = New System.Drawing.Point(176, 104)
        Me.ProgressBar1.Name = "ProgressBar1"
        Me.ProgressBar1.Size = New System.Drawing.Size(448, 23)
        Me.ProgressBar1.TabIndex = 3
        '
        'frmEventLog
        '
        Me.AutoScaleBaseSize = New System.Drawing.Size(5, 13)
        Me.ClientSize = New System.Drawing.Size(632, 136)
        Me.Controls.Add(Me.ProgressBar1)
        Me.Controls.Add(Me.btnLeer)
        Me.Controls.Add(Me.btnGrabar)
        Me.Controls.Add(Me.txtEventLog)
        Me.Name = "frmEventLog"
        Me.Text = "EventLog"
        Me.ResumeLayout(False)

    End Sub

#End Region

    Private Sub btnGrabar_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnGrabar.Click
        If Not EventLog.SourceExists(Application.ProductName) Then
            EventLog.CreateEventSource(Application.ProductName, "Application")
        End If
        Dim eLog As EventLog = New EventLog
        eLog.Source = Application.ProductName
        If eLog.Log <> "Application" Then
            MsgBox("El source está siendo usado por otra aplicación.")
            Exit Sub
        End If
        eLog.WriteEntry(txtEventLog.Text, EventLogEntryType.Information)
    End Sub

    Private Sub btnLeer_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnLeer.Click
        If Not EventLog.Exists("Application", ".") Then
            MsgBox("El log no existe")
            Exit Sub
        End If
        If Not EventLog.SourceExists(Application.ProductName, ".") Then
            MsgBox("El log no existe")
            Exit Sub
        End If
        Dim eLog As EventLog = New EventLog
        eLog.Log = "Application"
        eLog.MachineName = "."
        Dim elEntry As EventLogEntry
        Dim lEntryActual As Long = 0
        For Each elEntry In eLog.Entries
            lEntryActual += 1
            txtEventLog.Text = lEntryActual.ToString & " / " & eLog.Entries.Count.ToString
            txtEventLog.Refresh()
            ProgressBar1.Maximum = eLog.Entries.Count
            ProgressBar1.Value = lEntryActual
            If elEntry.Source = Application.ProductName Then
                MsgBox(elEntry.Message)
            End If
        Next
    End Sub
End Class

Espacios de nombres usados en el código de este artículo:

System.Diagnostics


ir al índice principal del Guille