Breyta

Deila með


EventLog Class

Definition

Provides interaction with Windows event logs.

public ref class EventLog : System::ComponentModel::Component, System::ComponentModel::ISupportInitialize
public class EventLog : System.ComponentModel.Component, System.ComponentModel.ISupportInitialize
type EventLog = class
    inherit Component
    interface ISupportInitialize
Public Class EventLog
Inherits Component
Implements ISupportInitialize
Inheritance
Implements

Examples

The following example creates the event source MySource if it doesn't already exist, and writes an entry to the event log MyNewLog.

Note

Starting with Windows Vista, you must run this application as an administrator.

#using <System.dll>

using namespace System;
using namespace System::Diagnostics;
using namespace System::Threading;
int main()
{
   
   // Create the source, if it does not already exist.
   if (  !EventLog::SourceExists( "MySource" ) )
   {
      //An event log source should not be created and immediately used.
      //There is a latency time to enable the source, it should be created
      //prior to executing the application that uses the source.
      //Execute this sample a second time to use the new source.
      EventLog::CreateEventSource( "MySource", "MyNewLog" );
      Console::WriteLine( "CreatingEventSource" );
      // The source is created.  Exit the application to allow it to be registered.
      return 0;
   }

   
   // Create an EventLog instance and assign its source.
   EventLog^ myLog = gcnew EventLog;
   myLog->Source = "MySource";
   
   // Write an informational entry to the event log.    
   myLog->WriteEntry( "Writing to event log." );
}
using System;
using System.Diagnostics;
using System.Threading;

class MySample{

    public static void Main(){

        // Create the source, if it does not already exist.
        if(!EventLog.SourceExists("MySource"))
        {
             //An event log source should not be created and immediately used.
             //There is a latency time to enable the source, it should be created
             //prior to executing the application that uses the source.
             //Execute this sample a second time to use the new source.
            EventLog.CreateEventSource("MySource", "MyNewLog");
            Console.WriteLine("CreatedEventSource");
            Console.WriteLine("Exiting, execute the application a second time to use the source.");
            // The source is created.  Exit the application to allow it to be registered.
            return;
        }

        // Create an EventLog instance and assign its source.
        EventLog myLog = new EventLog();
        myLog.Source = "MySource";

        // Write an informational entry to the event log.
        myLog.WriteEntry("Writing to event log.");
    }
}
Option Explicit
Option Strict

Imports System.Diagnostics
Imports System.Threading

Class MySample
    Public Shared Sub Main()
        
        If Not EventLog.SourceExists("MySource") Then
            ' Create the source, if it does not already exist.
            ' An event log source should not be created and immediately used.
            ' There is a latency time to enable the source, it should be created
            ' prior to executing the application that uses the source.
            ' Execute this sample a second time to use the new source.
            EventLog.CreateEventSource("MySource", "MyNewLog")
            Console.WriteLine("CreatingEventSource")
            'The source is created.  Exit the application to allow it to be registered.
            Return
        End If
        
        ' Create an EventLog instance and assign its source.
        Dim myLog As New EventLog()
        myLog.Source = "MySource"
        
        ' Write an informational entry to the event log.    
        myLog.WriteEntry("Writing to event log.")
    End Sub
End Class

Remarks

EventLog lets you access or customize Windows event logs, which record information about important software or hardware events. Using EventLog, you can read from existing logs, write entries to logs, create or delete event sources, delete logs, and respond to log entries. You can also create new logs when creating an event source.

Important

This type implements the IDisposable interface. When you have finished using the type, you should dispose of it either directly or indirectly. To dispose of the type directly, call its Dispose method in a try/catch block. To dispose of it indirectly, use a language construct such as using (in C#) or Using (in Visual Basic). For more information, see the "Using an Object that Implements IDisposable" section in the IDisposable interface topic.

In addition to providing access to individual event logs and their entries, the EventLog class lets you access the collection of all event logs. You can use the static members of EventLog to delete logs, get log lists, create or delete a source, or determine if a computer already contains a particular source.

There are three default event logs: Application, System, and Security. A Security log is read-only. Other applications and services you install, such as Active Directory, might have additional event logs.

There are security considerations when using the EventLog class. EventLog requires EventLogPermission permissions for specific actions in the .NET Framework 2.0 and later versions, or full trust in the .NET Framework 1.0 and 1.1. We recommend that EventLogPermission not be granted to partially trusted code. You should never pass any event log object, including EventLogEntryCollection and EventLogEntry objects, to less trusted code. For example, creating an EventLog object, writing an entry, and then passing the EventLog object to partially trusted code can create a security issue, because the ability to read and write to the event log allows code to perform actions such as issuing event log messages in the name of another application.

Starting with Windows Vista, User Account Control (UAC) determines the credentials of a user. If you are a member of the Built-in Administrators group, you are assigned two run-time access tokens: a standard user access token and an administrator access token. By default, you are in the standard user role. To run the code that accesses the Security log, you must first elevate your credentials from standard user to administrator. You can do this when you start an application by opening the shortcut menu for the application (if you're using a mouse, right-click the application icon) and indicating that you want to run as an administrator.

You can use EventLog to create custom event logs that you can view through the server's Event Viewer. Use the RegisterDisplayName method to display a localized name for your event log in the Event Viewer. Use the ModifyOverflowPolicy method to configure the behavior of your event log when it reaches its maximum log size.

To read from an event log, specify the log name (Log property) and server computer name (MachineName property for the event log. If you don't specify the server computer name, the local computer, ".", is assumed. It's not necessary to specify the event source (Source property), because a source is required only for writing to logs. The Entries property is automatically populated with the event log's list of entries.

To write to an event log, specify or create an event source (Source property). You must have administrative credentials on the computer to create a new event source. The event source registers your application with the event log as a valid source of entries. You can use the event source to write to only one log at a time. The Source property can be any random string, but the name must be distinct from other sources on the computer. The event source is typically the name of the application or another identifying string. Trying to create a duplicate Source value throws an exception. However, a single event log can be associated with multiple sources.

If the event source for the event log associated with the EventLog instance doesn't exist, a new event source is created. To create an event source in Windows Vista and later or Windows Server 2003, you must have administrative credentials.

This requirement is because all event logs, including Security logs, must be searched to determine whether the event source is unique. Starting with Windows Vista, users do not have permission to access the Security log; therefore, a SecurityException is thrown.

Important

Creating or deleting an event source requires synchronization of the underlying code by using a named mutex. If a highly privileged application locks the named mutex, trying to create or delete an event source causes the application to stop responding until the lock is released. To help prevent this problem, never grant UnmanagedCode permission to untrusted code. In addition, UnmanagedCode permission potentially allows other permissions to be bypassed and should only be granted to highly trusted code.

Applications and services should write to the Application log or to a custom log. Device drivers should write to the System log. If you do not explicitly set the Log property, the event log defaults to the Application log.

Note

There is nothing to protect an application from writing as any registered source. If an application is granted Write permission, it can write events for any valid source registered on the computer.

Use the WriteEvent and WriteEntry methods to write events to an event log. You must specify an event source to write events; you must create and configure the event source before writing the first entry with the source.

Create the new event source during the installation of your application. This allows time for the operating system to refresh its list of registered event sources and their configuration. If the operating system hasn't refreshed its list of event sources, and you try to write an event with the new source, the write operation will fail. You can configure a new source by using an EventLogInstaller object or the CreateEventSource method. You must have administrative credentials on the computer to create a new event source.

Each source can write to only one event log at a time; however, your application can use multiple sources to write to multiple event logs. For example, your application might require multiple sources configured for different event logs or different resource files. To change the configuration details of an existing source, you must delete the source and then create it with the new configuration. If other applications or components use the existing source, create a new source with the updated configuration instead of deleting the existing source.

You can register the event source with localized resources for your event category and message strings. Your application can write event log entries by using resource identifiers instead of specifying the actual string values. Refer to the EventLogInstaller and EventSourceCreationData classes for more information about configuring your source with resource files.

If your application writes string values directly to the event log, you do not have to set the resource file properties for the source. The source must be configured either for writing localized entries or for writing direct strings. If your application writes entries using both resource identifiers and string values, you must register two separate sources. For example, configure one source with resource files, and then use that source in the WriteEvent method to write entries using resource identifiers to the event log. Then create a different source without resource files, and use that source in the WriteEntry method to write strings directly to the event log using that source.

When writing events, you must at least specify either a message string or the resource identifier for a message string. Other event properties are optional. Examples of optional event settings include the following:

  • You can set the EventLogEntryType to specify the icon that the Event Viewer displays for the entry.

  • You can specify a category identifier for the event, if your application uses categories for filtering the events.

  • You can attach binary data to your event entry if you want to associate additional information with a given event.

Important

Event logging consumes disk space, processor time, and other system resources. It is important to log only essential information. We recommend that you place event log calls in an error path, rather than in the main code path, so they don't adversely affect performance.

For a list of initial property values for an instance of EventLog, see the EventLog constructor.

Constructors

EventLog()

Initializes a new instance of the EventLog class. Does not associate the instance with any log.

EventLog(String, String, String)

Initializes a new instance of the EventLog class. Associates the instance with a log on the specified computer and creates or assigns the specified source to the EventLog.

EventLog(String, String)

Initializes a new instance of the EventLog class. Associates the instance with a log on the specified computer.

EventLog(String)

Initializes a new instance of the EventLog class. Associates the instance with a log on the local computer.

Properties

CanRaiseEvents

Gets a value indicating whether the component can raise an event.

(Inherited from Component)
Container

Gets the IContainer that contains the Component.

(Inherited from Component)
DesignMode

Gets a value that indicates whether the Component is currently in design mode.

(Inherited from Component)
EnableRaisingEvents

Gets or sets a value indicating whether the EventLog receives EntryWritten event notifications.

Entries

Gets the contents of the event log.

Events

Gets the list of event handlers that are attached to this Component.

(Inherited from Component)
Log

Gets or sets the name of the log to read from or write to.

LogDisplayName

Gets the event log's friendly name.

MachineName

Gets or sets the name of the computer on which to read or write events.

MaximumKilobytes

Gets or sets the maximum event log size in kilobytes.

MinimumRetentionDays

Gets the number of days to retain entries in the event log.

OverflowAction

Gets the configured behavior for storing new entries when the event log reaches its maximum log file size.

Site

Gets or sets the ISite of the Component.

(Inherited from Component)
Source

Gets or sets the source name to register and use when writing to the event log.

SynchronizingObject

Gets or sets the object used to marshal the event handler calls issued as a result of an EventLog entry written event.

Methods

BeginInit()

Begins the initialization of an EventLog used on a form or used by another component. The initialization occurs at runtime.

Clear()

Removes all entries from the event log.

Close()

Closes the event log and releases read and write handles.

CreateEventSource(EventSourceCreationData)

Establishes a valid event source for writing localized event messages, using the specified configuration properties for the event source and the corresponding event log.

CreateEventSource(String, String, String)
Obsolete.
Obsolete.
Obsolete.

Establishes the specified source name as a valid event source for writing entries to a log on the specified computer. This method can also be used to create a new custom log on the specified computer.

CreateEventSource(String, String)

Establishes the specified source name as a valid event source for writing entries to a log on the local computer. This method can also create a new custom log on the local computer.

CreateObjRef(Type)

Creates an object that contains all the relevant information required to generate a proxy used to communicate with a remote object.

(Inherited from MarshalByRefObject)
Delete(String, String)

Removes an event log from the specified computer.

Delete(String)

Removes an event log from the local computer.

DeleteEventSource(String, String)

Removes the application's event source registration from the specified computer.

DeleteEventSource(String)

Removes the event source registration from the event log of the local computer.

Dispose()

Releases all resources used by the Component.

(Inherited from Component)
Dispose(Boolean)

Releases the unmanaged resources used by the EventLog, and optionally releases the managed resources.

EndInit()

Ends the initialization of an EventLog used on a form or by another component. The initialization occurs at runtime.

Equals(Object)

Determines whether the specified object is equal to the current object.

(Inherited from Object)
Exists(String, String)

Determines whether the log exists on the specified computer.

Exists(String)

Determines whether the log exists on the local computer.

GetEventLogs()

Searches for all event logs on the local computer and creates an array of EventLog objects that contain the list.

GetEventLogs(String)

Searches for all event logs on the given computer and creates an array of EventLog objects that contain the list.

GetHashCode()

Serves as the default hash function.

(Inherited from Object)
GetLifetimeService()
Obsolete.

Retrieves the current lifetime service object that controls the lifetime policy for this instance.

(Inherited from MarshalByRefObject)
GetService(Type)

Returns an object that represents a service provided by the Component or by its Container.

(Inherited from Component)
GetType()

Gets the Type of the current instance.

(Inherited from Object)
InitializeLifetimeService()
Obsolete.

Obtains a lifetime service object to control the lifetime policy for this instance.

(Inherited from MarshalByRefObject)
LogNameFromSourceName(String, String)

Gets the name of the log to which the specified source is registered.

MemberwiseClone()

Creates a shallow copy of the current Object.

(Inherited from Object)
MemberwiseClone(Boolean)

Creates a shallow copy of the current MarshalByRefObject object.

(Inherited from MarshalByRefObject)
ModifyOverflowPolicy(OverflowAction, Int32)

Changes the configured behavior for writing new entries when the event log reaches its maximum file size.

RegisterDisplayName(String, Int64)

Specifies the localized name of the event log, which is displayed in the server Event Viewer.

SourceExists(String, String)

Determines whether an event source is registered on a specified computer.

SourceExists(String)

Determines whether an event source is registered on the local computer.

ToString()

Returns a String containing the name of the Component, if any. This method should not be overridden.

(Inherited from Component)
WriteEntry(String, EventLogEntryType, Int32, Int16, Byte[])

Writes an entry with the given message text, application-defined event identifier, and application-defined category to the event log, and appends binary data to the message.

WriteEntry(String, EventLogEntryType, Int32, Int16)

Writes an entry with the given message text, application-defined event identifier, and application-defined category to the event log.

WriteEntry(String, EventLogEntryType, Int32)

Writes an entry with the given message text and application-defined event identifier to the event log.

WriteEntry(String, EventLogEntryType)

Writes an error, warning, information, success audit, or failure audit entry with the given message text to the event log.

WriteEntry(String, String, EventLogEntryType, Int32, Int16, Byte[])

Writes an entry with the given message text, application-defined event identifier, and application-defined category to the event log (using the specified registered event source) and appends binary data to the message.

WriteEntry(String, String, EventLogEntryType, Int32, Int16)

Writes an entry with the given message text, application-defined event identifier, and application-defined category to the event log, using the specified registered event source. The category can be used by the Event Viewer to filter events in the log.

WriteEntry(String, String, EventLogEntryType, Int32)

Writes an entry with the given message text and application-defined event identifier to the event log, using the specified registered event source.

WriteEntry(String, String, EventLogEntryType)

Writes an error, warning, information, success audit, or failure audit entry with the given message text to the event log, using the specified registered event source.

WriteEntry(String, String)

Writes an information type entry with the given message text to the event log, using the specified registered event source.

WriteEntry(String)

Writes an information type entry, with the given message text, to the event log.

WriteEvent(EventInstance, Byte[], Object[])

Writes an event log entry with the given event data, message replacement strings, and associated binary data.

WriteEvent(EventInstance, Object[])

Writes a localized entry to the event log.

WriteEvent(String, EventInstance, Byte[], Object[])

Writes an event log entry with the given event data, message replacement strings, and associated binary data, and using the specified registered event source.

WriteEvent(String, EventInstance, Object[])

Writes an event log entry with the given event data and message replacement strings, using the specified registered event source.

Events

Disposed

Occurs when the component is disposed by a call to the Dispose() method.

(Inherited from Component)
EntryWritten

Occurs when an entry is written to an event log on the local computer.

Applies to

See also