Edit

Share via


EventLog.WriteEvent Method

Definition

Writes a localized event entry to the event log.

Overloads

WriteEvent(String, EventInstance, Object[])

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

WriteEvent(EventInstance, Object[])

Writes a localized entry 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(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[])

Source:
EventLog.cs
Source:
EventLog.cs

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

public:
 static void WriteEvent(System::String ^ source, System::Diagnostics::EventInstance ^ instance, ... cli::array <System::Object ^> ^ values);
public static void WriteEvent (string source, System.Diagnostics.EventInstance instance, params object[] values);
static member WriteEvent : string * System.Diagnostics.EventInstance * obj[] -> unit
Public Shared Sub WriteEvent (source As String, instance As EventInstance, ParamArray values As Object())

Parameters

source
String

The name of the event source registered for the application on the specified computer.

instance
EventInstance

An EventInstance instance that represents a localized event log entry.

values
Object[]

An array of strings to merge into the message text of the event log entry.

Exceptions

The source value is an empty string ("").

-or-

The source value is null.

-or-

instance.InstanceId is less than zero or greater than UInt16.MaxValue.

-or-

values has more than 256 elements.

-or-

One of the values elements is longer than 32766 bytes.

-or-

The source name results in a registry key path longer than 254 characters.

instance is null.

The registry key for the event log could not be opened.

The operating system reported an error when writing the event entry to the event log. A Windows error code is not available.

Examples

The following example writes an informational event entry and a warning event entry to an existing event log. The event message text is specified using a resource identifier in a resource file. The example assumes the corresponding resource file has been registered for the source.

String^ sourceName = "SampleApplicationSource";
if ( EventLog::SourceExists( sourceName ) )
{
   
   // Define an informational event and a warning event.
   // The message identifiers correspond to the message text in the
   // message resource file defined for the source.
   EventInstance ^ myInfoEvent = gcnew EventInstance( InformationMsgId,0,EventLogEntryType::Information );
   EventInstance ^ myWarningEvent = gcnew EventInstance( WarningMsgId,0,EventLogEntryType::Warning );
   
   // Insert the method name into the event log message.
   array<String^>^insertStrings = {"EventLogSamples.WriteEventSample2"};
   
   // Write the events to the event log.
   EventLog::WriteEvent( sourceName, myInfoEvent, 0 );
   
   // Append binary data to the warning event entry.
   array<Byte>^binaryData = {7,8,9,10};
   EventLog::WriteEvent( sourceName, myWarningEvent, binaryData, insertStrings );
}
else
{
   Console::WriteLine( "Warning - event source {0} not registered", sourceName );
}

string sourceName = "SampleApplicationSource";
if(EventLog.SourceExists(sourceName))
{

    // Define an informational event and a warning event.

    // The message identifiers correspond to the message text in the
    // message resource file defined for the source.
    EventInstance myInfoEvent = new EventInstance(InformationMsgId, 0, EventLogEntryType.Information);
    EventInstance myWarningEvent = new EventInstance(WarningMsgId, 0, EventLogEntryType.Warning);

    // Insert the method name into the event log message.
    string [] insertStrings = {"EventLogSamples.WriteEventSample2"};

    // Write the events to the event log.

    EventLog.WriteEvent(sourceName, myInfoEvent);

    // Append binary data to the warning event entry.
    byte [] binaryData = { 7, 8, 9, 10 };
    EventLog.WriteEvent(sourceName, myWarningEvent, binaryData, insertStrings);
}
else
{
    Console.WriteLine("Warning - event source {0} not registered",
        sourceName);
}
           Dim sourceName As String = "SampleApplicationSource"
           If EventLog.SourceExists(sourceName)
  
               ' Define an informational event and a warning event.

               ' The message identifiers correspond to the message text in the
               ' message resource file defined for the source.
               Dim myInfoEvent As EventInstance = new EventInstance(InformationMsgId, 0, EventLogEntryType.Information)
               Dim myWarningEvent As EventInstance = new EventInstance(WarningMsgId, 0, EventLogEntryType.Warning)

               ' Insert the method name into the event log message.
               Dim insertStrings() As String = {"EventLogSamples.WriteEventSample2"}
           
               ' Write the events to the event log.

               EventLog.WriteEvent(sourceName, myInfoEvent, insertStrings)

               ' Append binary data to the warning event entry.
               Dim binaryData() As Byte = { 7, 8, 9, 10 }
               EventLog.WriteEvent(sourceName, myWarningEvent, binaryData, insertStrings)
           Else 
               Console.WriteLine("Warning - event source {0} not registered", _
                   sourceName)
           End If

The example uses the following message text file, built into the resource library EventLogMsgs.dll. A message text file is the source from which the message resource file is created. The message text file defines the resource identifiers and text for the category, event message, and parameter insertion strings.

; // EventLogMsgs.mc
; // ********************************************************

; // Use the following commands to build this file:

; //   mc -s EventLogMsgs.mc
; //   rc EventLogMsgs.rc
; //   link /DLL /SUBSYSTEM:WINDOWS /NOENTRY /MACHINE:x86 EventLogMsgs.Res
; // ********************************************************

; // - Event categories -
; // Categories must be numbered consecutively starting at 1.
; // ********************************************************

MessageId=0x1
Severity=Success
SymbolicName=INSTALL_CATEGORY
Language=English
Installation
.

MessageId=0x2
Severity=Success
SymbolicName=QUERY_CATEGORY
Language=English
Database Query
.

MessageId=0x3
Severity=Success
SymbolicName=REFRESH_CATEGORY
Language=English
Data Refresh
.

; // - Event messages -
; // *********************************

MessageId = 1000
Severity = Success
Facility = Application
SymbolicName = AUDIT_SUCCESS_MESSAGE_ID_1000
Language=English
My application message text, in English, for message id 1000, called from %1.
.

MessageId = 1001
Severity = Warning
Facility = Application
SymbolicName = AUDIT_FAILED_MESSAGE_ID_1001
Language=English
My application message text, in English, for message id 1001, called from %1.
.

MessageId = 1002
Severity = Success
Facility = Application
SymbolicName = GENERIC_INFO_MESSAGE_ID_1002
Language=English
My generic information message in English, for message id 1002.
.

MessageId = 1003
Severity = Warning
Facility = Application
SymbolicName = GENERIC_WARNING_MESSAGE_ID_1003
Language=English
My generic warning message in English, for message id 1003, called from %1.
.

MessageId = 1004
Severity = Success
Facility = Application
SymbolicName = UPDATE_CYCLE_COMPLETE_MESSAGE_ID_1004
Language=English
The update cycle is complete for %%5002.
.

MessageId = 1005
Severity = Warning
Facility = Application
SymbolicName = SERVER_CONNECTION_DOWN_MESSAGE_ID_1005
Language=English
The refresh operation did not complete because the connection to server %1 could not be established.
.

; // - Event log display name -
; // ********************************************************

MessageId = 5001
Severity = Success
Facility = Application
SymbolicName = EVENT_LOG_DISPLAY_NAME_MSGID
Language=English
Sample Event Log
.

; // - Event message parameters -
; //   Language independent insertion strings
; // ********************************************************

MessageId = 5002
Severity = Success
Facility = Application
SymbolicName = EVENT_LOG_SERVICE_NAME_MSGID
Language=English
SVC_UPDATE.EXE
.

Remarks

Use this method to write a localized entry to the event log, using a source already registered as an event source for the appropriate log. You specify the event properties with resource identifiers rather than string values. The Event Viewer uses the resource identifiers to display the corresponding strings from the localized resource file for the source. You must register the source with the corresponding resource file before you write events using resource identifiers.

The input instance instance specifies the event message and properties. Set the InstanceId of the instance input for the defined message in the source message resource file. You can optionally set the CategoryId and EntryType of the instance input to define the category and event type of your event entry. You can also specify an array of language-independent strings to insert into the localized message text. Set values to null if the event message does not contain formatting placeholders for replacement strings.

The specified source must be registered for an event log before using WriteEvent. The specified source must be configured for writing localized entries to the log; the source must at minimum have a message resource file defined.

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 has not refreshed its list of event sources, and you attempt to write an event with the new source, the write operation will fail. You can configure a new source using an EventLogInstaller, or using the CreateEventSource method. You must have administrative rights on the computer to create a new event source.

The source must be configured either for writing localized entries or for writing direct strings. Use the WriteEntry method if your application writes string values directly to the event log.

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.

See also

Applies to

WriteEvent(EventInstance, Object[])

Source:
EventLog.cs
Source:
EventLog.cs

Writes a localized entry to the event log.

public:
 void WriteEvent(System::Diagnostics::EventInstance ^ instance, ... cli::array <System::Object ^> ^ values);
public void WriteEvent (System.Diagnostics.EventInstance instance, params object[] values);
[System.Runtime.InteropServices.ComVisible(false)]
public void WriteEvent (System.Diagnostics.EventInstance instance, params object[] values);
member this.WriteEvent : System.Diagnostics.EventInstance * obj[] -> unit
[<System.Runtime.InteropServices.ComVisible(false)>]
member this.WriteEvent : System.Diagnostics.EventInstance * obj[] -> unit
Public Sub WriteEvent (instance As EventInstance, ParamArray values As Object())

Parameters

instance
EventInstance

An EventInstance instance that represents a localized event log entry.

values
Object[]

An array of strings to merge into the message text of the event log entry.

Attributes

Exceptions

The Source property of the EventLog has not been set.

-or-

The method attempted to register a new event source, but the computer name in MachineName is not valid.

-or-

The source is already registered for a different event log.

-or-

instance.InstanceId is less than zero or greater than UInt16.MaxValue.

-or-

values has more than 256 elements.

-or-

One of the values elements is longer than 32766 bytes.

-or-

The source name results in a registry key path longer than 254 characters.

instance is null.

The registry key for the event log could not be opened.

The operating system reported an error when writing the event entry to the event log. A Windows error code is not available.

Examples

The following example writes two audit entries to the event log myNewLog. The example creates a new event source and a new event log if they do not exist on the local computer. The event message text is specified using a resource identifier in a resource file.

// Create the event source if it does not exist.
String^ sourceName = "SampleApplicationSource";
if (  !EventLog::SourceExists( sourceName ) )
{
   
   // Call a local method to register the event log source
   // for the event log "myNewLog."  Use the resource file
   // EventLogMsgs.dll in the current directory for message text.
   String^ messageFile = String::Format( "{0}\\{1}", System::Environment::CurrentDirectory, "EventLogMsgs.dll" );
   CreateEventSourceSample1( messageFile );
}

// Get the event log corresponding to the existing source.
String^ myLogName = EventLog::LogNameFromSourceName( sourceName, "." );
EventLog^ myEventLog = gcnew EventLog( myLogName,".",sourceName );

// Define two audit events.
// The message identifiers correspond to the message text in the
// message resource file defined for the source.
EventInstance ^ myAuditSuccessEvent = gcnew EventInstance( AuditSuccessMsgId,0,EventLogEntryType::SuccessAudit );
EventInstance ^ myAuditFailEvent = gcnew EventInstance( AuditFailedMsgId,0,EventLogEntryType::FailureAudit );

// Insert the method name into the event log message.
array<String^>^insertStrings = {"EventLogSamples.WriteEventSample1"};

// Write the events to the event log.
myEventLog->WriteEvent( myAuditSuccessEvent, insertStrings );

// Append binary data to the audit failure event entry.
array<Byte>^binaryData = {3,4,5,6};
myEventLog->WriteEvent( myAuditFailEvent, binaryData, insertStrings );

// Create the event source if it does not exist.
string sourceName = "SampleApplicationSource";
if(!EventLog.SourceExists(sourceName))
{
    // Call a local method to register the event log source
    // for the event log "myNewLog."  Use the resource file
    // EventLogMsgs.dll in the current directory for message text.

    string messageFile =  String.Format("{0}\\{1}",
        System.Environment.CurrentDirectory,
        "EventLogMsgs.dll");

    CreateEventSourceSample1(messageFile);
}

// Get the event log corresponding to the existing source.
string myLogName = EventLog.LogNameFromSourceName(sourceName,".");

EventLog myEventLog = new EventLog(myLogName, ".", sourceName);

// Define two audit events.

// The message identifiers correspond to the message text in the
// message resource file defined for the source.
EventInstance myAuditSuccessEvent = new EventInstance(AuditSuccessMsgId, 0, EventLogEntryType.SuccessAudit);
EventInstance myAuditFailEvent = new EventInstance(AuditFailedMsgId, 0, EventLogEntryType.FailureAudit);

// Insert the method name into the event log message.
string [] insertStrings = {"EventLogSamples.WriteEventSample1"};

// Write the events to the event log.

myEventLog.WriteEvent(myAuditSuccessEvent, insertStrings);

// Append binary data to the audit failure event entry.
byte [] binaryData = { 3, 4, 5, 6 };
myEventLog.WriteEvent(myAuditFailEvent, binaryData, insertStrings);

           Dim sourceName As String = "SampleApplicationSource"

           ' Create the event source if it does not exist.
           If Not EventLog.SourceExists(sourceName)
  
               ' Call a local method to register the event log source
               ' for the event log "myNewLog."  Use the resource file
               ' EventLogMsgs.dll in the current directory for message text.

               Dim messageFile As String =  String.Format("{0}\\{1}", _
                   System.Environment.CurrentDirectory, _
                   "EventLogMsgs.dll")

               CreateEventSourceSample1(messageFile)
           End If 

           ' Get the event log corresponding to the existing source.
           Dim myLogName As String = EventLog.LogNameFromSourceName(sourceName,".")
       
           Dim myEventLog As EventLog = new EventLog(myLogName, ".", sourceName)

           ' Define two audit events.
           Dim myAuditSuccessEvent As EventInstance = new EventInstance(AuditSuccessMsgId, 0, EventLogEntryType.SuccessAudit)
           Dim myAuditFailEvent As EventInstance = new EventInstance(AuditFailedMsgId, 0, EventLogEntryType.FailureAudit)

           ' Insert the method name into the event log message.
           Dim insertStrings() As String = {"EventLogSamples.WriteEventSample1"}
           
           ' Write the events to the event log.

           myEventLog.WriteEvent(myAuditSuccessEvent, insertStrings)

           ' Append binary data to the audit failure event entry.
           Dim binaryData() As Byte = { 7, 8, 9, 10 }
           myEventLog.WriteEvent(myAuditFailEvent, binaryData, insertStrings)

The example uses the following message text file, built into the resource library EventLogMsgs.dll. A message text file is the source from which the message resource file is created. The message text file defines the resource identifiers and text for the category, event message, and parameter insertion strings.

; // EventLogMsgs.mc
; // ********************************************************

; // Use the following commands to build this file:

; //   mc -s EventLogMsgs.mc
; //   rc EventLogMsgs.rc
; //   link /DLL /SUBSYSTEM:WINDOWS /NOENTRY /MACHINE:x86 EventLogMsgs.Res
; // ********************************************************

; // - Event categories -
; // Categories must be numbered consecutively starting at 1.
; // ********************************************************

MessageId=0x1
Severity=Success
SymbolicName=INSTALL_CATEGORY
Language=English
Installation
.

MessageId=0x2
Severity=Success
SymbolicName=QUERY_CATEGORY
Language=English
Database Query
.

MessageId=0x3
Severity=Success
SymbolicName=REFRESH_CATEGORY
Language=English
Data Refresh
.

; // - Event messages -
; // *********************************

MessageId = 1000
Severity = Success
Facility = Application
SymbolicName = AUDIT_SUCCESS_MESSAGE_ID_1000
Language=English
My application message text, in English, for message id 1000, called from %1.
.

MessageId = 1001
Severity = Warning
Facility = Application
SymbolicName = AUDIT_FAILED_MESSAGE_ID_1001
Language=English
My application message text, in English, for message id 1001, called from %1.
.

MessageId = 1002
Severity = Success
Facility = Application
SymbolicName = GENERIC_INFO_MESSAGE_ID_1002
Language=English
My generic information message in English, for message id 1002.
.

MessageId = 1003
Severity = Warning
Facility = Application
SymbolicName = GENERIC_WARNING_MESSAGE_ID_1003
Language=English
My generic warning message in English, for message id 1003, called from %1.
.

MessageId = 1004
Severity = Success
Facility = Application
SymbolicName = UPDATE_CYCLE_COMPLETE_MESSAGE_ID_1004
Language=English
The update cycle is complete for %%5002.
.

MessageId = 1005
Severity = Warning
Facility = Application
SymbolicName = SERVER_CONNECTION_DOWN_MESSAGE_ID_1005
Language=English
The refresh operation did not complete because the connection to server %1 could not be established.
.

; // - Event log display name -
; // ********************************************************

MessageId = 5001
Severity = Success
Facility = Application
SymbolicName = EVENT_LOG_DISPLAY_NAME_MSGID
Language=English
Sample Event Log
.

; // - Event message parameters -
; //   Language independent insertion strings
; // ********************************************************

MessageId = 5002
Severity = Success
Facility = Application
SymbolicName = EVENT_LOG_SERVICE_NAME_MSGID
Language=English
SVC_UPDATE.EXE
.

Remarks

Use this method to write a localized entry to the event log. You specify the event properties with resource identifiers rather than string values. The Event Viewer uses the resource identifiers to display the corresponding strings from the localized resource file for the Source. You must register the source with the corresponding resource file before you write events using resource identifiers.

The input instance instance specifies the event message and properties. Set the InstanceId of the instance input for the defined message in the source message resource file. You can optionally set the CategoryId and EntryType of the instance input to define the category and event type of your event entry. You can also specify an array of language-independent strings to insert into the localized message text. Set values to null if the event message does not contain formatting placeholders for replacement strings.

You must set the Source property on your EventLog component before using WriteEvent. The specified source must be configured for writing localized entries to the log; the source must at minimum have a message resource file defined.

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 has not refreshed its list of event sources, and you attempt to write an event with the new source, the write operation will fail. You can configure a new source using an EventLogInstaller, or using the CreateEventSource method. You must have administrative rights on the computer to create a new event source.

The source must be configured either for writing localized entries or for writing direct strings. Use the WriteEntry method if your application writes string values directly to the event log.

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.

Note

If you write an entry to a remote computer, the value of the message string might not be what you expect if the remote computer is not running the .NET Framework. Also, the message string cannot contain %n, where n is an integer value (for example, %1), because the event viewer treats it as an insertion string. Because an Internet Protocol, version 6 (IPv6) address can contain this character sequence, you cannot log an event message that contains an IPv6 address.

See also

Applies to

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

Source:
EventLog.cs
Source:
EventLog.cs

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

public:
 void WriteEvent(System::Diagnostics::EventInstance ^ instance, cli::array <System::Byte> ^ data, ... cli::array <System::Object ^> ^ values);
public void WriteEvent (System.Diagnostics.EventInstance instance, byte[] data, params object[] values);
[System.Runtime.InteropServices.ComVisible(false)]
public void WriteEvent (System.Diagnostics.EventInstance instance, byte[] data, params object[] values);
member this.WriteEvent : System.Diagnostics.EventInstance * byte[] * obj[] -> unit
[<System.Runtime.InteropServices.ComVisible(false)>]
member this.WriteEvent : System.Diagnostics.EventInstance * byte[] * obj[] -> unit
Public Sub WriteEvent (instance As EventInstance, data As Byte(), ParamArray values As Object())

Parameters

instance
EventInstance

An EventInstance instance that represents a localized event log entry.

data
Byte[]

An array of bytes that holds the binary data associated with the entry.

values
Object[]

An array of strings to merge into the message text of the event log entry.

Attributes

Exceptions

The Source property of the EventLog has not been set.

-or-

The method attempted to register a new event source, but the computer name in MachineName is not valid.

-or-

The source is already registered for a different event log.

-or-

instance.InstanceId is less than zero or greater than UInt16.MaxValue.

-or-

values has more than 256 elements.

-or-

One of the values elements is longer than 32766 bytes.

-or-

The source name results in a registry key path longer than 254 characters.

instance is null.

The registry key for the event log could not be opened.

The operating system reported an error when writing the event entry to the event log. A Windows error code is not available.

Examples

The following example writes two audit entries to the event log myNewLog. The example creates a new event source and a new event log if they do not exist on the local computer. The event message text is specified using a resource identifier in a resource file.

// Create the event source if it does not exist.
String^ sourceName = "SampleApplicationSource";
if (  !EventLog::SourceExists( sourceName ) )
{
   
   // Call a local method to register the event log source
   // for the event log "myNewLog."  Use the resource file
   // EventLogMsgs.dll in the current directory for message text.
   String^ messageFile = String::Format( "{0}\\{1}", System::Environment::CurrentDirectory, "EventLogMsgs.dll" );
   CreateEventSourceSample1( messageFile );
}

// Get the event log corresponding to the existing source.
String^ myLogName = EventLog::LogNameFromSourceName( sourceName, "." );
EventLog^ myEventLog = gcnew EventLog( myLogName,".",sourceName );

// Define two audit events.
// The message identifiers correspond to the message text in the
// message resource file defined for the source.
EventInstance ^ myAuditSuccessEvent = gcnew EventInstance( AuditSuccessMsgId,0,EventLogEntryType::SuccessAudit );
EventInstance ^ myAuditFailEvent = gcnew EventInstance( AuditFailedMsgId,0,EventLogEntryType::FailureAudit );

// Insert the method name into the event log message.
array<String^>^insertStrings = {"EventLogSamples.WriteEventSample1"};

// Write the events to the event log.
myEventLog->WriteEvent( myAuditSuccessEvent, insertStrings );

// Append binary data to the audit failure event entry.
array<Byte>^binaryData = {3,4,5,6};
myEventLog->WriteEvent( myAuditFailEvent, binaryData, insertStrings );

// Create the event source if it does not exist.
string sourceName = "SampleApplicationSource";
if(!EventLog.SourceExists(sourceName))
{
    // Call a local method to register the event log source
    // for the event log "myNewLog."  Use the resource file
    // EventLogMsgs.dll in the current directory for message text.

    string messageFile =  String.Format("{0}\\{1}",
        System.Environment.CurrentDirectory,
        "EventLogMsgs.dll");

    CreateEventSourceSample1(messageFile);
}

// Get the event log corresponding to the existing source.
string myLogName = EventLog.LogNameFromSourceName(sourceName,".");

EventLog myEventLog = new EventLog(myLogName, ".", sourceName);

// Define two audit events.

// The message identifiers correspond to the message text in the
// message resource file defined for the source.
EventInstance myAuditSuccessEvent = new EventInstance(AuditSuccessMsgId, 0, EventLogEntryType.SuccessAudit);
EventInstance myAuditFailEvent = new EventInstance(AuditFailedMsgId, 0, EventLogEntryType.FailureAudit);

// Insert the method name into the event log message.
string [] insertStrings = {"EventLogSamples.WriteEventSample1"};

// Write the events to the event log.

myEventLog.WriteEvent(myAuditSuccessEvent, insertStrings);

// Append binary data to the audit failure event entry.
byte [] binaryData = { 3, 4, 5, 6 };
myEventLog.WriteEvent(myAuditFailEvent, binaryData, insertStrings);

           Dim sourceName As String = "SampleApplicationSource"

           ' Create the event source if it does not exist.
           If Not EventLog.SourceExists(sourceName)
  
               ' Call a local method to register the event log source
               ' for the event log "myNewLog."  Use the resource file
               ' EventLogMsgs.dll in the current directory for message text.

               Dim messageFile As String =  String.Format("{0}\\{1}", _
                   System.Environment.CurrentDirectory, _
                   "EventLogMsgs.dll")

               CreateEventSourceSample1(messageFile)
           End If 

           ' Get the event log corresponding to the existing source.
           Dim myLogName As String = EventLog.LogNameFromSourceName(sourceName,".")
       
           Dim myEventLog As EventLog = new EventLog(myLogName, ".", sourceName)

           ' Define two audit events.
           Dim myAuditSuccessEvent As EventInstance = new EventInstance(AuditSuccessMsgId, 0, EventLogEntryType.SuccessAudit)
           Dim myAuditFailEvent As EventInstance = new EventInstance(AuditFailedMsgId, 0, EventLogEntryType.FailureAudit)

           ' Insert the method name into the event log message.
           Dim insertStrings() As String = {"EventLogSamples.WriteEventSample1"}
           
           ' Write the events to the event log.

           myEventLog.WriteEvent(myAuditSuccessEvent, insertStrings)

           ' Append binary data to the audit failure event entry.
           Dim binaryData() As Byte = { 7, 8, 9, 10 }
           myEventLog.WriteEvent(myAuditFailEvent, binaryData, insertStrings)

The example uses the following message text file, built into the resource library EventLogMsgs.dll. A message text file is the source from which the message resource file is created. The message text file defines the resource identifiers and text for the category, event message, and parameter insertion strings.

; // EventLogMsgs.mc
; // ********************************************************

; // Use the following commands to build this file:

; //   mc -s EventLogMsgs.mc
; //   rc EventLogMsgs.rc
; //   link /DLL /SUBSYSTEM:WINDOWS /NOENTRY /MACHINE:x86 EventLogMsgs.Res
; // ********************************************************

; // - Event categories -
; // Categories must be numbered consecutively starting at 1.
; // ********************************************************

MessageId=0x1
Severity=Success
SymbolicName=INSTALL_CATEGORY
Language=English
Installation
.

MessageId=0x2
Severity=Success
SymbolicName=QUERY_CATEGORY
Language=English
Database Query
.

MessageId=0x3
Severity=Success
SymbolicName=REFRESH_CATEGORY
Language=English
Data Refresh
.

; // - Event messages -
; // *********************************

MessageId = 1000
Severity = Success
Facility = Application
SymbolicName = AUDIT_SUCCESS_MESSAGE_ID_1000
Language=English
My application message text, in English, for message id 1000, called from %1.
.

MessageId = 1001
Severity = Warning
Facility = Application
SymbolicName = AUDIT_FAILED_MESSAGE_ID_1001
Language=English
My application message text, in English, for message id 1001, called from %1.
.

MessageId = 1002
Severity = Success
Facility = Application
SymbolicName = GENERIC_INFO_MESSAGE_ID_1002
Language=English
My generic information message in English, for message id 1002.
.

MessageId = 1003
Severity = Warning
Facility = Application
SymbolicName = GENERIC_WARNING_MESSAGE_ID_1003
Language=English
My generic warning message in English, for message id 1003, called from %1.
.

MessageId = 1004
Severity = Success
Facility = Application
SymbolicName = UPDATE_CYCLE_COMPLETE_MESSAGE_ID_1004
Language=English
The update cycle is complete for %%5002.
.

MessageId = 1005
Severity = Warning
Facility = Application
SymbolicName = SERVER_CONNECTION_DOWN_MESSAGE_ID_1005
Language=English
The refresh operation did not complete because the connection to server %1 could not be established.
.

; // - Event log display name -
; // ********************************************************

MessageId = 5001
Severity = Success
Facility = Application
SymbolicName = EVENT_LOG_DISPLAY_NAME_MSGID
Language=English
Sample Event Log
.

; // - Event message parameters -
; //   Language independent insertion strings
; // ********************************************************

MessageId = 5002
Severity = Success
Facility = Application
SymbolicName = EVENT_LOG_SERVICE_NAME_MSGID
Language=English
SVC_UPDATE.EXE
.

Remarks

Use this method to write a localized entry with additional event-specific data to the event log. You specify the event properties with resource identifiers rather than string values. The Event Viewer uses the resource identifiers to display the corresponding strings from the localized resource file for the Source. You must register the source with the corresponding resource file before you write events using resource identifiers.

The input instance instance specifies the event message and properties. Set the InstanceId of the instance input for the defined message in the source message resource file. You can optionally set the CategoryId and EntryType of the instance input to define the category and event type of your event entry. You can also specify an array of language-independent strings to insert into the localized message text. Set values to null if the event message does not contain formatting placeholders for replacement strings.

Specify binary data with an event when it is necessary to provide additional details for the event. For example, use the data parameter to include information on a specific error. The Event Viewer does not interpret the associated event data; it displays the data in a combined hexadecimal and text format. Use event-specific data sparingly; include it only if you are sure it will be useful. You can also use event-specific data to store information the application can process independently of the Event Viewer. For example, you could write a viewer specifically for your events, or write a program that scans the event log and creates reports that include information from the event-specific data.

You must set the Source property on your EventLog component before component before using WriteEvent. The specified source must be configured for writing localized entries to the log; the source must at minimum have a message resource file defined.

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 has not refreshed its list of event sources, and you attempt to write an event with the new source, the write operation will fail. You can configure a new source using an EventLogInstaller, or using the CreateEventSource method. You must have administrative rights on the computer to create a new event source.

Note

If you do not specify a MachineName for your EventLog instance before you call WriteEvent, the local computer (".") is assumed.

The source must be configured either for writing localized entries or for writing direct strings. Use the WriteEntry method if your application writes string values directly to the event log.

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.

Note

If you write an entry to a remote computer, the value of the message string might not be what you expect if the remote computer is not running the .NET Framework. Also, the message string cannot contain %n, where n is an integer value (for example, %1), because the event viewer treats it as an insertion string. Because an Internet Protocol, version 6 (IPv6) address can contain this character sequence, you cannot log an event message that contains an IPv6 address.

See also

Applies to

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

Source:
EventLog.cs
Source:
EventLog.cs

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

public:
 static void WriteEvent(System::String ^ source, System::Diagnostics::EventInstance ^ instance, cli::array <System::Byte> ^ data, ... cli::array <System::Object ^> ^ values);
public static void WriteEvent (string source, System.Diagnostics.EventInstance instance, byte[] data, params object[] values);
static member WriteEvent : string * System.Diagnostics.EventInstance * byte[] * obj[] -> unit
Public Shared Sub WriteEvent (source As String, instance As EventInstance, data As Byte(), ParamArray values As Object())

Parameters

source
String

The name of the event source registered for the application on the specified computer.

instance
EventInstance

An EventInstance instance that represents a localized event log entry.

data
Byte[]

An array of bytes that holds the binary data associated with the entry.

values
Object[]

An array of strings to merge into the message text of the event log entry.

Exceptions

The source value is an empty string ("").

-or-

The source value is null.

-or-

instance.InstanceId is less than zero or greater than UInt16.MaxValue.

-or-

values has more than 256 elements.

-or-

One of the values elements is longer than 32766 bytes.

-or-

The source name results in a registry key path longer than 254 characters.

instance is null.

The registry key for the event log could not be opened.

The operating system reported an error when writing the event entry to the event log. A Windows error code is not available.

Examples

The following example writes an informational event entry and a warning event entry to an existing event log. The event message text is specified using a resource identifier in a resource file. The example assumes the corresponding resource file has been registered for the source.

String^ sourceName = "SampleApplicationSource";
if ( EventLog::SourceExists( sourceName ) )
{
   
   // Define an informational event and a warning event.
   // The message identifiers correspond to the message text in the
   // message resource file defined for the source.
   EventInstance ^ myInfoEvent = gcnew EventInstance( InformationMsgId,0,EventLogEntryType::Information );
   EventInstance ^ myWarningEvent = gcnew EventInstance( WarningMsgId,0,EventLogEntryType::Warning );
   
   // Insert the method name into the event log message.
   array<String^>^insertStrings = {"EventLogSamples.WriteEventSample2"};
   
   // Write the events to the event log.
   EventLog::WriteEvent( sourceName, myInfoEvent, 0 );
   
   // Append binary data to the warning event entry.
   array<Byte>^binaryData = {7,8,9,10};
   EventLog::WriteEvent( sourceName, myWarningEvent, binaryData, insertStrings );
}
else
{
   Console::WriteLine( "Warning - event source {0} not registered", sourceName );
}

string sourceName = "SampleApplicationSource";
if(EventLog.SourceExists(sourceName))
{

    // Define an informational event and a warning event.

    // The message identifiers correspond to the message text in the
    // message resource file defined for the source.
    EventInstance myInfoEvent = new EventInstance(InformationMsgId, 0, EventLogEntryType.Information);
    EventInstance myWarningEvent = new EventInstance(WarningMsgId, 0, EventLogEntryType.Warning);

    // Insert the method name into the event log message.
    string [] insertStrings = {"EventLogSamples.WriteEventSample2"};

    // Write the events to the event log.

    EventLog.WriteEvent(sourceName, myInfoEvent);

    // Append binary data to the warning event entry.
    byte [] binaryData = { 7, 8, 9, 10 };
    EventLog.WriteEvent(sourceName, myWarningEvent, binaryData, insertStrings);
}
else
{
    Console.WriteLine("Warning - event source {0} not registered",
        sourceName);
}
           Dim sourceName As String = "SampleApplicationSource"
           If EventLog.SourceExists(sourceName)
  
               ' Define an informational event and a warning event.

               ' The message identifiers correspond to the message text in the
               ' message resource file defined for the source.
               Dim myInfoEvent As EventInstance = new EventInstance(InformationMsgId, 0, EventLogEntryType.Information)
               Dim myWarningEvent As EventInstance = new EventInstance(WarningMsgId, 0, EventLogEntryType.Warning)

               ' Insert the method name into the event log message.
               Dim insertStrings() As String = {"EventLogSamples.WriteEventSample2"}
           
               ' Write the events to the event log.

               EventLog.WriteEvent(sourceName, myInfoEvent, insertStrings)

               ' Append binary data to the warning event entry.
               Dim binaryData() As Byte = { 7, 8, 9, 10 }
               EventLog.WriteEvent(sourceName, myWarningEvent, binaryData, insertStrings)
           Else 
               Console.WriteLine("Warning - event source {0} not registered", _
                   sourceName)
           End If

The example uses the following message text file, built into the resource library EventLogMsgs.dll. A message text file is the source from which the message resource file is created. The message text file defines the resource identifiers and text for the category, event message, and parameter insertion strings.

; // EventLogMsgs.mc
; // ********************************************************

; // Use the following commands to build this file:

; //   mc -s EventLogMsgs.mc
; //   rc EventLogMsgs.rc
; //   link /DLL /SUBSYSTEM:WINDOWS /NOENTRY /MACHINE:x86 EventLogMsgs.Res
; // ********************************************************

; // - Event categories -
; // Categories must be numbered consecutively starting at 1.
; // ********************************************************

MessageId=0x1
Severity=Success
SymbolicName=INSTALL_CATEGORY
Language=English
Installation
.

MessageId=0x2
Severity=Success
SymbolicName=QUERY_CATEGORY
Language=English
Database Query
.

MessageId=0x3
Severity=Success
SymbolicName=REFRESH_CATEGORY
Language=English
Data Refresh
.

; // - Event messages -
; // *********************************

MessageId = 1000
Severity = Success
Facility = Application
SymbolicName = AUDIT_SUCCESS_MESSAGE_ID_1000
Language=English
My application message text, in English, for message id 1000, called from %1.
.

MessageId = 1001
Severity = Warning
Facility = Application
SymbolicName = AUDIT_FAILED_MESSAGE_ID_1001
Language=English
My application message text, in English, for message id 1001, called from %1.
.

MessageId = 1002
Severity = Success
Facility = Application
SymbolicName = GENERIC_INFO_MESSAGE_ID_1002
Language=English
My generic information message in English, for message id 1002.
.

MessageId = 1003
Severity = Warning
Facility = Application
SymbolicName = GENERIC_WARNING_MESSAGE_ID_1003
Language=English
My generic warning message in English, for message id 1003, called from %1.
.

MessageId = 1004
Severity = Success
Facility = Application
SymbolicName = UPDATE_CYCLE_COMPLETE_MESSAGE_ID_1004
Language=English
The update cycle is complete for %%5002.
.

MessageId = 1005
Severity = Warning
Facility = Application
SymbolicName = SERVER_CONNECTION_DOWN_MESSAGE_ID_1005
Language=English
The refresh operation did not complete because the connection to server %1 could not be established.
.

; // - Event log display name -
; // ********************************************************

MessageId = 5001
Severity = Success
Facility = Application
SymbolicName = EVENT_LOG_DISPLAY_NAME_MSGID
Language=English
Sample Event Log
.

; // - Event message parameters -
; //   Language independent insertion strings
; // ********************************************************

MessageId = 5002
Severity = Success
Facility = Application
SymbolicName = EVENT_LOG_SERVICE_NAME_MSGID
Language=English
SVC_UPDATE.EXE
.

Remarks

Use this method to write a localized entry with additional event-specific data to the event log, using a source already registered as an event source for the appropriate log. You specify the event properties with resource identifiers rather than string values. The Event Viewer uses the resource identifiers to display the corresponding strings from the localized resource file for the source. You must register the source with the corresponding resource file before you write events using resource identifiers.

The input instance instance specifies the event message and properties. Set the InstanceId of the instance input for the defined message in the source message resource file. You can optionally set the CategoryId and EntryType of the instance input to define the category and event type of your event entry. You can also specify an array of language-independent strings to insert into the localized message text. Set values to null if the event message does not contain formatting placeholders for replacement strings.

Specify binary data with an event when it is necessary to provide additional details for the event. For example, use the data parameter to include information on a specific error. The Event Viewer does not interpret the associated event data; it displays the data in a combined hexadecimal and text format. Use event-specific data sparingly; include it only if you are sure it will be useful. You can also use event-specific data to store information the application can process independently of the Event Viewer. For example, you could write a viewer specifically for your events, or write a program that scans the event log and creates reports that include information from the event-specific data.

The specified source must be registered for an event log before using WriteEvent. The specified source must be configured for writing localized entries to the log; the source must at minimum have a message resource file defined.

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 has not refreshed its list of event sources, and you attempt to write an event with the new source, the write operation will fail. You can configure a new source using an EventLogInstaller, or using the CreateEventSource method. You must have administrative rights on the computer to create a new event source.

The source must be configured either for writing localized entries or for writing direct strings. Use the WriteEntry method if your application writes string values directly to the event log.

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.

See also

Applies to