EventLog.CreateEventSource EventLog.CreateEventSource EventLog.CreateEventSource EventLog.CreateEventSource Method

定義

建立能夠將事件資訊寫入系統上的特定記錄檔的應用程式。Establishes an application as able to write event information to a particular log on the system.

多載

CreateEventSource(EventSourceCreationData) CreateEventSource(EventSourceCreationData) CreateEventSource(EventSourceCreationData) 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) CreateEventSource(String, String) CreateEventSource(String, String) 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.

CreateEventSource(String, String, String) CreateEventSource(String, String, String) CreateEventSource(String, String, String) CreateEventSource(String, String, String)

建立指定的來源名稱做為有效的事件來源,以便將項目寫入指定之電腦上的記錄檔。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(EventSourceCreationData) CreateEventSource(EventSourceCreationData) CreateEventSource(EventSourceCreationData) 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.

public:
 static void CreateEventSource(System::Diagnostics::EventSourceCreationData ^ sourceData);
[System.MonoNotSupported("remote machine is not supported")]
public static void CreateEventSource (System.Diagnostics.EventSourceCreationData sourceData);
static member CreateEventSource : System.Diagnostics.EventSourceCreationData -> unit
Public Shared Sub CreateEventSource (sourceData As EventSourceCreationData)

參數

sourceData
EventSourceCreationData EventSourceCreationData EventSourceCreationData EventSourceCreationData

事件來源及其目標事件記錄檔的組態屬性。The configuration properties for the event source and its target event log.

例外狀況

sourceData 中指定的電腦名稱無效。The computer name specified in sourceData is not valid.

-或--or- sourceData 中所指定的來源名稱為 nullThe source name specified in sourceData is null.

-或--or- sourceData 中指定的記錄檔名稱無效。The log name specified in sourceData is not valid. 事件記錄檔名稱必須由可列印字元組成,不得包括字元 '*'、'?' 或 '\'。Event log names must consist of printable characters and cannot include the characters '*', '?', or '\'.

-或--or- sourceData 中指定的記錄檔名稱無效,無法建立使用者記錄檔。The log name specified in sourceData is not valid for user log creation. 事件記錄檔名稱 AppEvent、SysEvent 和 SecEvent 會保留供系統使用。The Event log names AppEvent, SysEvent, and SecEvent are reserved for system use.

-或--or- 此記錄檔名稱符合現有的事件來源名稱。The log name matches an existing event source name.

-或--or- 指定 sourceData 來源名稱產生的登錄機碼路徑長度超過 254 個字元。The source name specified in sourceData results in a registry key path longer than 254 characters.

-或--or- sourceData 中指定的記錄檔名稱的前 8 個字元不是唯一的。The first 8 characters of the log name specified in sourceData are not unique.

-或--or- 已經登錄 sourceData 中指定的來源名稱。The source name specified in sourceData is already registered.

-或--or- sourceData 中指定的來源名稱符合現有的事件記錄檔名稱。The source name specified in sourceData matches an existing event log name.

無法開啟事件記錄檔的登錄機碼。The registry key for the event log could not be opened.

範例

下列範例會判斷名SampleApplicationSource為的事件來源是否已在本機電腦上註冊。The following example determines whether the event source named SampleApplicationSource is registered on the local computer. 如果事件來源不存在, 此範例會設定來源的訊息資源檔, 並建立新的事件來源。If the event source does not exist, the example sets the message resource file for the source and creates the new event source. 最後, 此範例會使用中DisplayNameMsgId的資源識別碼值和中messageFile的資源檔路徑, 設定事件記錄檔的當地語系化顯示名稱。Finally, the example sets the localized display name for the event log, using the resource identifier value in DisplayNameMsgId and the resource file path in messageFile.

void CreateEventSourceSample1( String^ messageFile )
{
   String^ myLogName;
   String^ sourceName = "SampleApplicationSource";
   
   // Create the event source if it does not exist.
   if (  !EventLog::SourceExists( sourceName ) )
   {
      
      // Create a new event source for the custom event log
      // named "myNewLog."  
      myLogName = "myNewLog";
      EventSourceCreationData ^ mySourceData = gcnew EventSourceCreationData( sourceName,myLogName );
      
      // Set the message resource file that the event source references.
      // All event resource identifiers correspond to text in this file.
      if (  !System::IO::File::Exists( messageFile ) )
      {
         Console::WriteLine( "Input message resource file does not exist - {0}", messageFile );
         messageFile = "";
      }
      else
      {
         
         // Set the specified file as the resource
         // file for message text, category text, and 
         // message parameter strings.  
         mySourceData->MessageResourceFile = messageFile;
         mySourceData->CategoryResourceFile = messageFile;
         mySourceData->CategoryCount = CategoryCount;
         mySourceData->ParameterResourceFile = messageFile;
         Console::WriteLine( "Event source message resource file set to {0}", messageFile );
      }

      Console::WriteLine( "Registering new source for event log." );
      EventLog::CreateEventSource( mySourceData );
   }
   else
   {
      
      // Get the event log corresponding to the existing source.
      myLogName = EventLog::LogNameFromSourceName( sourceName, "." );
   }

   
   // Register the localized name of the event log.
   // For example, the actual name of the event log is "myNewLog," but
   // the event log name displayed in the Event Viewer might be
   // "Sample Application Log" or some other application-specific
   // text.
   EventLog^ myEventLog = gcnew EventLog( myLogName,".",sourceName );
   if ( messageFile->Length > 0 )
   {
      myEventLog->RegisterDisplayName( messageFile, DisplayNameMsgId );
   }   
}
static void CreateEventSourceSample1(string messageFile)
{
    string myLogName;
    string sourceName = "SampleApplicationSource";

    // Create the event source if it does not exist.
    if(!EventLog.SourceExists(sourceName))
    {
        // Create a new event source for the custom event log
        // named "myNewLog."  

        myLogName = "myNewLog";
        EventSourceCreationData mySourceData = new EventSourceCreationData(sourceName, myLogName);

        // Set the message resource file that the event source references.
        // All event resource identifiers correspond to text in this file.
        if (!System.IO.File.Exists(messageFile))
        {
            Console.WriteLine("Input message resource file does not exist - {0}", 
                messageFile);
            messageFile = "";
        }
        else 
        {
            // Set the specified file as the resource
            // file for message text, category text, and 
            // message parameter strings.  

            mySourceData.MessageResourceFile = messageFile;
            mySourceData.CategoryResourceFile = messageFile;
            mySourceData.CategoryCount = CategoryCount;
            mySourceData.ParameterResourceFile = messageFile;

            Console.WriteLine("Event source message resource file set to {0}", 
                messageFile);
        }

        Console.WriteLine("Registering new source for event log.");
        EventLog.CreateEventSource(mySourceData);
    }
    else
    {
        // Get the event log corresponding to the existing source.
        myLogName = EventLog.LogNameFromSourceName(sourceName,".");
    }

    // Register the localized name of the event log.
    // For example, the actual name of the event log is "myNewLog," but
    // the event log name displayed in the Event Viewer might be
    // "Sample Application Log" or some other application-specific
    // text.
    EventLog myEventLog = new EventLog(myLogName, ".", sourceName);
    
    if (messageFile.Length > 0)
    {
        myEventLog.RegisterDisplayName(messageFile, DisplayNameMsgId);
    }
}
Public Shared Sub CreateEventSourceSample1(ByVal messageFile As String)

    Dim myLogName As String
    Dim sourceName As String = "SampleApplicationSource"

    ' Create the event source if it does not exist.
    If Not EventLog.SourceExists(sourceName)
    
        ' Create a new event source for the custom event log
        ' named "myNewLog."  

        myLogName = "myNewLog"
        Dim mySourceData As EventSourceCreationData = New EventSourceCreationData(sourceName, myLogName)

        ' Set the message resource file that the event source references.
        ' All event resource identifiers correspond to text in this file.
        If Not System.IO.File.Exists(messageFile)

            Console.WriteLine("Input message resource file does not exist - {0}", _
                messageFile)
            messageFile = ""
        Else 
            ' Set the specified file as the resource
            ' file for message text, category text and 
            ' message parameters strings.

            mySourceData.MessageResourceFile = messageFile
            mySourceData.CategoryResourceFile = messageFile
            mySourceData.CategoryCount = CategoryCount
            mySourceData.ParameterResourceFile = messageFile

            Console.WriteLine("Event source message resource file set to {0}", _
                messageFile)
        End If

        Console.WriteLine("Registering new source for event log.")
        EventLog.CreateEventSource(mySourceData)
    Else
        ' Get the event log corresponding to the existing source.
        myLogName = EventLog.LogNameFromSourceName(sourceName,".")
    End If

    ' Register the localized name of the event log.
    ' For example, the actual name of the event log is "myNewLog," but
    ' the event log name displayed in the Event Viewer might be
    ' "Sample Application Log" or some other application-specific
    ' text.
    Dim myEventLog As EventLog = New EventLog(myLogName, ".", sourceName)
    
    If messageFile.Length > 0
        myEventLog.RegisterDisplayName(messageFile, DisplayNameMsgId)
    End If
End Sub

此範例會使用內建于資源連結庫 EventLogMsgs 的下列郵件內文檔案。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. 具體而言, 資源識別碼5001是針對事件記錄檔的當地語系化名稱所定義。Specifically, resource identifier 5001 is defined for the localized name of the event log.

; // 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  
.  

備註

使用這個多載來設定新的來源, 以便將專案寫入本機電腦或遠端電腦上的事件記錄檔。Use this overload to configure a new source for writing entries to an event log on the local computer or a remote computer. 您不需要使用這個方法來讀取事件記錄檔。It is not necessary to use this method to read from an event log.

CreateEventSource方法會使用輸入sourceData Source LogName和屬性,在目的電腦上建立新來源及其關聯事件記錄檔的登錄值。MachineNameThe CreateEventSource method uses the input sourceDataSource, LogName and MachineName properties to create registry values on the target computer for the new source and its associated event log. 新的來源名稱不能符合目的電腦上現有的來源名稱或現有的事件記錄檔名稱。A new source name cannot match an existing source name or an existing event log name on the target computer. 如果未設定屬性, 則會為應用程式事件記錄檔註冊來源。 LogNameIf the LogName property is not set, the source is registered for the Application event log. MachineName如果未設定, 則會在本機電腦上註冊來源。If the MachineName is not set, the source is registered on the local computer.

注意

若要在 Windows Vista 和更新版本或 Windows Server 2003 中建立事件來源, 您必須具有系統管理許可權。To create an event source in Windows Vista and later or Windows Server 2003, you must have administrative privileges.

這項需求的原因是必須搜尋所有事件記錄檔 (包括安全性), 以判斷事件來源是否為唯一的。The reason for this requirement is that all event logs, including security, must be searched to determine whether the event source is unique. 從 Windows Vista 開始, 使用者沒有存取安全性記錄檔的許可權;因此, SecurityException會擲回。Starting with Windows Vista, users do not have permission to access the security log; therefore, a SecurityException is thrown.

從 Windows Vista 開始, 使用者帳戶控制 (UAC) 會判斷使用者的許可權。Starting with Windows Vista, User Account Control (UAC) determines the privileges of a user. 如果您是內建 Administrators 群組的成員,系統會將兩個執行階段存取語彙基元 (Token) 指派給您:標準使用者存取語彙基元及管理員存取語彙基元。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 execute the code that accesses the security log, you must first elevate your privileges from standard user to administrator. 您可以在啟動應用程式時,以滑鼠右鍵按一下應用程式圖示,並指出您想要以系統管理員身分執行,藉此提高為系統管理員權限。You can do this when you start an application by right-clicking the application icon and indicating that you want to run as an administrator.

使用WriteEventWriteEntry將事件寫入事件記錄檔。Use WriteEvent and WriteEntry 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 has not refreshed its list of event sources, and you attempt to write an event with the new source, the write operation will fail. 您可以使用EventLogInstaller來設定新的來源, 或CreateEventSource使用方法。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.

您可以為現有的事件記錄檔或新的事件記錄檔建立事件來源。You can create an event source for an existing event log or a new event log. 當您建立新事件記錄檔的新來源時, 系統會註冊該記錄檔的來源, 但在寫入第一個專案之前, 不會建立記錄檔。When you create a new source for a new event log, the system registers the source for that log, but the log is not created until the first entry is written to it.

作業系統會將事件記錄檔儲存為檔案。The operating system stores event logs as files. 當您使用EventLogInstallerCreateEventSource建立新的事件記錄檔時, 相關聯的檔案會儲存在指定電腦上的%SystemRoot%\System32\Config 目錄中。When you use EventLogInstaller or CreateEventSource to create a new event log, the associated file is stored in the %SystemRoot%\System32\Config directory on the specified computer. 檔案名的設定方式是將Log屬性的前8個字元附加為 ".evt" 副檔名。The file name is set by appending the first 8 characters of the Log property with the ".evt" file name extension.

每個來源一次只能寫入一個事件記錄檔;不過, 您的應用程式可以使用多個來源寫入多個事件記錄檔。Each source can only 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.

您可以為事件類別目錄和訊息字串註冊具有當地語系化資源檔的事件來源。You can register the event source with localized resource file(s) for your event category and message strings. 您的應用程式可以使用資源識別碼來寫入事件記錄檔專案, 而不是指定實際的字串。Your application can write event log entries using resource identifiers, rather than specifying the actual string. 事件檢視器會使用資源識別碼, 根據目前的語言設定, 從當地語系化的資源檔中尋找和顯示對應的字串。The Event Viewer uses the resource identifier to find and display the corresponding string from the localized resource file based on current language settings. 您可以為事件類別目錄、訊息和參數插入字串註冊個別的檔案, 也可以為這三種字串類型註冊相同的資源檔。You can register a separate file for event categories, messages and parameter insertion strings, or you can register the same resource file for all three types of strings. CategoryCount使用、 CategoryResourceFileMessageResourceFile和屬性來設定來源,以將當地語系化的專案寫入事件記錄檔。ParameterResourceFileUse the CategoryCount, CategoryResourceFile, MessageResourceFile, and ParameterResourceFile properties to configure the source to write localized entries to the event log. 如果您的應用程式將字串值直接寫入事件記錄檔, 您就不需要設定這些屬性。If your application writes strings values directly to the event log, you do not need to set these properties.

來源必須設定為寫入當地語系化的專案或撰寫直接字串。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. 例如, 設定一個具有資源檔的來源, 然後在WriteEvent方法中使用該來源, 將使用資源識別碼的專案寫入事件記錄檔。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. 然後建立不含資源檔的不同來源, 然後在WriteEntry方法中使用該來源, 將字串直接寫入至使用該來源的事件記錄檔。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.

若要變更現有來源的設定詳細資料, 您必須刪除來源, 然後使用新的設定加以建立。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 rather than deleting the existing source.

注意

如果已針對事件記錄檔設定來源, 並針對另一個事件記錄檔重新設定它, 您必須重新開機電腦, 變更才會生效。If a source is configured for an event log, and you reconfigure it for another event log, you must restart the computer for the changes to take effect.

安全性

EventLogPermission
用於管理電腦上的事件記錄檔資訊。for administering event log information on the computer. 相關聯的列舉:AdministerAssociated enumeration: Administer

另請參閱

CreateEventSource(String, String) CreateEventSource(String, String) CreateEventSource(String, String) 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.

public:
 static void CreateEventSource(System::String ^ source, System::String ^ logName);
public static void CreateEventSource (string source, string logName);
static member CreateEventSource : string * string -> unit
Public Shared Sub CreateEventSource (source As String, logName As String)

參數

source
String String String String

應用程式登錄在本機電腦上的來源名稱。The source name by which the application is registered on the local computer.

logName
String String String String

寫入來源項目的記錄檔名稱。The name of the log the source's entries are written to. 可能的值包括應用程式、系統或自訂事件記錄檔。Possible values include Application, System, or a custom event log.

例外狀況

source 為空字串 ("") 或 nullsource is an empty string ("") or null.

-或--or- logName 不是有效的名稱。logName is not a valid event log name. 事件記錄檔名稱必須由可列印字元組成,不得包括字元 '*'、'?' 或 '\'。Event log names must consist of printable characters, and cannot include the characters '*', '?', or '\'.

-或--or- logName 不適用於建立使用者記錄。logName is not valid for user log creation. 事件記錄檔名稱 AppEvent、SysEvent 和 SecEvent 會保留供系統使用。The event log names AppEvent, SysEvent, and SecEvent are reserved for system use.

-或--or- 此記錄檔名稱符合現有的事件來源名稱。The log name matches an existing event source name.

-或--or- 來源名稱產生的登錄機碼路徑長度超過 254 個字元。The source name results in a registry key path longer than 254 characters.

-或--or- logName 的前 8 個字元符合現有事件記錄檔名稱的前 8 個字元。The first 8 characters of logName match the first 8 characters of an existing event log name.

-或--or- 來源因為已經存在於本機電腦上而無法登錄。The source cannot be registered because it already exists on the local computer.

-或--or- 來源名稱符合現有的事件記錄檔名稱。The source name matches an existing event log name.

無法在目標電腦上開啟事件記錄檔的登錄機碼。The registry key for the event log could not be opened on the local computer.

範例

下列範例會建立來源MySource (如果尚未存在), 並將專案寫入事件記錄MyNewLog檔。The following example creates the source MySource if it does not already exist, and writes an entry to the event log MyNewLog.

#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
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 'Main 
End Class 'MySample

備註

使用這個多載來建立自訂記錄檔, 或建立並Source註冊至本機電腦上的現有記錄檔。Use this overload to create a custom log or to create and register a Source to an existing log on the local computer.

如果logNamenull 呼叫CreateEventSource時為或空字串 (""), 則記錄檔會預設為應用程式記錄檔。If logName is null or an empty string ("") when you call CreateEventSource, the log defaults to the Application log. 如果記錄檔不存在於本機電腦上, 系統就會建立自訂記錄檔, 並將您的Source應用程式註冊為該記錄檔的。If the log does not exist on the local computer, the system creates a custom log and registers your application as a Source for that log.

注意

若要在 Windows Vista 和更新版本或 Windows Server 2003 中建立事件來源, 您必須具有系統管理許可權。To create an event source in Windows Vista and later or Windows Server 2003, you must have administrative privileges.

這項需求的原因是必須搜尋所有事件記錄檔 (包括安全性), 以判斷事件來源是否為唯一的。The reason for this requirement is that all event logs, including security, must be searched to determine whether the event source is unique. 從 Windows Vista 開始, 使用者沒有存取安全性記錄檔的許可權;因此, SecurityException會擲回。Starting with Windows Vista, users do not have permission to access the security log; therefore, a SecurityException is thrown.

在 Windows Vista (含) 以後版本中,使用者帳戶控制 (UAC) 會判斷使用者的權限。In Windows Vista and later, User Account Control (UAC) determines the privileges of a user. 如果您是內建 Administrators 群組的成員,系統會將兩個執行階段存取語彙基元 (Token) 指派給您:標準使用者存取語彙基元及管理員存取語彙基元。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 execute the code that accesses the security log, you must first elevate your privileges from standard user to administrator. 您可以在啟動應用程式時,以滑鼠右鍵按一下應用程式圖示,並指出您想要以系統管理員身分執行,藉此提高為系統管理員權限。You can do this when you start an application by right-clicking the application icon and indicating that you want to run as an administrator.

如果您要寫入事件記錄檔, 您只需要建立事件來源。You only need to create an event source if you are writing to the event log. 將專案寫入事件記錄檔之前, 您必須以事件記錄檔註冊事件來源, 做為事件的有效來源。Before writing an entry to an event log, you must register the event source with the event log as a valid source of events. 當您撰寫記錄專案時, 系統會使用Source來尋找適當的記錄, 以放置您的專案。When you write a log entry, the system uses the Source to find the appropriate log in which to place your entry. 如果您要讀取事件記錄檔, 您可以指定SourceLogMachineNameIf you are reading the event log, you can either specify the Source, or a Log and MachineName.

注意

MachineName如果您要連接到本機電腦上的記錄檔, 則不需要指定。You are not required to specify the MachineName if you are connecting to a log on the local computer. 如果您在讀取記錄檔MachineName時未指定, 則會假設使用本機電腦 (".")。If you do not specify the MachineName when reading from a log, the local computer (".") is assumed.

使用WriteEventWriteEntry將事件寫入事件記錄檔。Use WriteEvent and WriteEntry 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 has not refreshed its list of event sources, and you attempt to write an event with the new source, the write operation will fail. 您可以使用EventLogInstaller來設定新的來源, 或CreateEventSource使用方法。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.

您可以為現有的事件記錄檔或新的事件記錄檔建立事件來源。You can create an event source for an existing event log or a new event log. 當您建立新事件記錄檔的新來源時, 系統會註冊該記錄檔的來源, 但在寫入第一個專案之前, 不會建立記錄檔。When you create a new source for a new event log, the system registers the source for that log, but the log is not created until the first entry is written to it.

作業系統會將事件記錄檔儲存為檔案。The operating system stores event logs as files. 當您使用EventLogInstallerCreateEventSource建立新的事件記錄檔時, 相關聯的檔案會儲存在指定電腦上的%SystemRoot%\System32\Config 目錄中。When you use EventLogInstaller or CreateEventSource to create a new event log, the associated file is stored in the %SystemRoot%\System32\Config directory on the specified computer. 檔案名的設定方式是將Log屬性的前8個字元附加為 ".evt" 副檔名。The file name is set by appending the first 8 characters of the Log property with the ".evt" file name extension.

來源在本機電腦上必須是唯一的;新的來源名稱不能符合現有的來源名稱或現有的事件記錄檔名稱。The source must be unique on the local computer; a new source name cannot match an existing source name or an existing event log name. 每個來源一次只能寫入一個事件記錄檔;不過, 您的應用程式可以使用多個來源寫入多個事件記錄檔。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.

來源必須設定為寫入當地語系化的專案或撰寫直接字串。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. 例如, 設定一個具有資源檔的來源, 然後在WriteEvent方法中使用該來源, 將使用資源識別碼的專案寫入事件記錄檔。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. 然後建立不含資源檔的不同來源, 然後在WriteEntry方法中使用該來源, 將字串直接寫入至使用該來源的事件記錄檔。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.

若要變更現有來源的設定詳細資料, 您必須刪除來源, 然後使用新的設定加以建立。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 rather than deleting the existing source.

注意

如果來源已經對應到記錄檔, 而且您將它重新對應到新的記錄檔, 您必須重新開機電腦, 變更才會生效。If a source has already been mapped to a log and you remap it to a new log, you must restart the computer for the changes to take effect.

安全性

EventLogPermission
用於管理電腦上的事件記錄檔資訊。for administering event log information on the computer. 相關聯的列舉:AdministerAssociated enumeration: Administer

另請參閱

CreateEventSource(String, String, String) CreateEventSource(String, String, String) CreateEventSource(String, String, String) CreateEventSource(String, String, String)

警告

此 API 現已淘汰。

建立指定的來源名稱做為有效的事件來源,以便將項目寫入指定之電腦上的記錄檔。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.

public:
 static void CreateEventSource(System::String ^ source, System::String ^ logName, System::String ^ machineName);
[System.Obsolete("use CreateEventSource(EventSourceCreationData) instead")]
[System.Obsolete("This method has been deprecated.  Please use System.Diagnostics.EventLog.CreateEventSource(EventSourceCreationData sourceData) instead.  http://go.microsoft.com/fwlink/?linkid=14202")]
[System.Obsolete("This method has been deprecated.  Please use System.Diagnostics.EventLog.CreateEventSource(EventSourceCreationData sourceData) instead.  https://go.microsoft.com/fwlink/?linkid=14202")]
public static void CreateEventSource (string source, string logName, string machineName);
static member CreateEventSource : string * string * string -> unit
Public Shared Sub CreateEventSource (source As String, logName As String, machineName As String)

參數

source
String String String String

將應用程式註冊在指定電腦上的來源。The source by which the application is registered on the specified computer.

logName
String String String String

寫入來源項目的記錄檔名稱。The name of the log the source's entries are written to. 可能的值包括應用程式、系統或自訂事件記錄檔。Possible values include Application, System, or a custom event log. 如果您未指定值,logName 會預設為應用程式。If you do not specify a value, logName defaults to Application.

machineName
String String String String

要註冊這個事件來源的電腦名稱,或者表示本機電腦的 "."。The name of the computer to register this event source with, or "." for the local computer.

例外狀況

machineName 不是有效的電腦名稱。The machineName is not a valid computer name.

-或--or- source 為空字串 ("") 或 nullsource is an empty string ("") or null.

-或--or- logName 不是有效的名稱。logName is not a valid event log name. 事件記錄檔名稱必須由可列印字元組成,不得包括字元 '*'、'?' 或 '\'。Event log names must consist of printable characters, and cannot include the characters '*', '?', or '\'.

-或--or- logName 不適用於建立使用者記錄。logName is not valid for user log creation. 事件記錄檔名稱 AppEvent、SysEvent 和 SecEvent 會保留供系統使用。The event log names AppEvent, SysEvent, and SecEvent are reserved for system use.

-或--or- 此記錄檔名稱符合現有的事件來源名稱。The log name matches an existing event source name.

-或--or- 來源名稱產生的登錄機碼路徑長度超過 254 個字元。The source name results in a registry key path longer than 254 characters.

-或--or- logName 的前 8 個字元符合指定電腦上現有事件記錄檔名稱的前 8 個字元。The first 8 characters of logName match the first 8 characters of an existing event log name on the specified computer.

-或--or- 來源因為已經存在於指定的電腦上而無法登錄。The source cannot be registered because it already exists on the specified computer.

-或--or- 來源名稱符合現有的事件來源名稱。The source name matches an existing event source name.

無法在目標電腦上開啟事件記錄檔的登錄機碼。The registry key for the event log could not be opened on the specified computer.

範例

下列範例會在電腦MySource MyServer上建立來源, 並將專案寫入事件記錄MyNewLog檔。The following example creates the source MySource on the computer MyServer, and writes an entry to the event log MyNewLog.

#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", "MyServer" ) )
   {
      EventLog::CreateEventSource( "MySource", "MyNewLog", "MyServer" );
      Console::WriteLine( "CreatingEventSource" );
   }

   
   // 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." );
   Console::WriteLine( "Message written 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", "MyServer"))
        {
            // 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", "MyServer");
            Console.WriteLine("CreatingEventSource");
            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.");
        
        Console.WriteLine("Message written to event log.");                                                                        
    }
}
   
Imports System
Imports System.Diagnostics
Imports System.Threading

Class MySample
    Public Shared Sub Main()
        ' Create the source, if it does not already exist.
        If Not EventLog.SourceExists("MySource", "MyServer") Then
            EventLog.CreateEventSource("MySource", "MyNewLog", "MyServer")
            Console.WriteLine("CreatingEventSource")
        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.")
        
        Console.WriteLine("Message written to event log.")
    End Sub ' Main
End Class ' MySample

備註

使用這個多載來建立自訂記錄檔, 或建立並Source註冊到指定電腦上的現有記錄檔。Use this overload to create a custom log or to create and register a Source to an existing log on the specified computer.

如果logNamenull 呼叫CreateEventSource時為或空字串 (""), 則記錄檔會預設為應用程式記錄檔。If logName is null or an empty string ("") when you call CreateEventSource, the log defaults to the Application log. 如果記錄檔不存在於指定的電腦上, 系統就會建立自訂記錄檔, 並將您Source的應用程式註冊為該記錄檔的。If the log does not exist on the specified computer, the system creates a custom log and registers your application as a Source for that log.

如果您要寫入事件記錄檔, 您只需要建立事件來源。You only need to create an event source if you are writing to the event log. 將專案寫入事件記錄檔之前, 您必須以事件記錄檔註冊事件來源, 做為事件的有效來源。Before writing an entry to an event log, you must register the event source with the event log as a valid source of events. 當您撰寫記錄專案時, 系統會使用Source來尋找適當的記錄, 以放置您的專案。When you write a log entry, the system uses the Source to find the appropriate log in which to place your entry. 如果您要讀取事件記錄檔, 您可以指定SourceLogMachineNameIf you are reading the event log, you can either specify the Source, or a Log and MachineName.

注意

若要在 Windows Vista 和更新版本或 Windows Server 2003 中建立事件來源, 您必須具有系統管理許可權。To create an event source in Windows Vista and later or Windows Server 2003, you must have administrative privileges.

這項需求的原因是必須搜尋所有事件記錄檔 (包括安全性), 以判斷事件來源是否為唯一的。The reason for this requirement is that all event logs, including security, must be searched to determine whether the event source is unique. 在 Windows Vista 和更新版本中, 使用者沒有存取安全性記錄檔的許可權;因此, SecurityException會擲回。In Windows Vista and later, users do not have permission to access the security log; therefore, a SecurityException is thrown.

在 Windows Vista (含) 以後版本中,使用者帳戶控制 (UAC) 會判斷使用者的權限。In Windows Vista and later, User Account Control (UAC) determines the privileges of a user. 如果您是內建 Administrators 群組的成員,系統會將兩個執行階段存取語彙基元 (Token) 指派給您:標準使用者存取語彙基元及管理員存取語彙基元。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 execute the code that accesses the security log, you must first elevate your privileges from standard user to administrator. 您可以在啟動應用程式時,以滑鼠右鍵按一下應用程式圖示,並指出您想要以系統管理員身分執行,藉此提高為系統管理員權限。You can do this when you start an application by right-clicking the application icon and indicating that you want to run as an administrator.

使用WriteEventWriteEntry將事件寫入事件記錄檔。Use WriteEvent and WriteEntry 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 has not refreshed its list of event sources, and you attempt to write an event with the new source, the write operation will fail. 您可以使用EventLogInstaller來設定新的來源, 或CreateEventSource使用方法。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.

您可以為現有的事件記錄檔或新的事件記錄檔建立事件來源。You can create an event source for an existing event log or a new event log. 當您建立新事件記錄檔的新來源時, 系統會註冊該記錄檔的來源, 但在寫入第一個專案之前, 不會建立記錄檔。When you create a new source for a new event log, the system registers the source for that log, but the log is not created until the first entry is written to it.

作業系統會將事件記錄檔儲存為檔案。The operating system stores event logs as files. 當您使用EventLogInstallerCreateEventSource建立新的事件記錄檔時, 相關聯的檔案會儲存在指定電腦上的%SystemRoot%\System32\Config 目錄中。When you use EventLogInstaller or CreateEventSource to create a new event log, the associated file is stored in the %SystemRoot%\System32\Config directory on the specified computer. 檔案名的設定方式是將Log屬性的前8個字元附加為 ".evt" 副檔名。The file name is set by appending the first 8 characters of the Log property with the ".evt" file name extension.

來源在本機電腦上必須是唯一的;新的來源名稱不能符合現有的來源名稱或現有的事件記錄檔名稱。The source must be unique on the local computer; a new source name cannot match an existing source name or an existing event log name. 每個來源一次只能寫入一個事件記錄檔;不過, 您的應用程式可以使用多個來源寫入多個事件記錄檔。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.

來源必須設定為寫入當地語系化的專案或撰寫直接字串。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. 例如, 設定一個具有資源檔的來源, 然後在WriteEvent方法中使用該來源, 將使用資源識別碼的專案寫入事件記錄檔。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. 然後建立不含資源檔的不同來源, 然後在WriteEntry方法中使用該來源, 將字串直接寫入至使用該來源的事件記錄檔。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.

若要變更現有來源的設定詳細資料, 您必須刪除來源, 然後使用新的設定加以建立。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 rather than deleting the existing source.

注意

如果來源已經對應到記錄檔, 而且您將它重新對應到新的記錄檔, 您必須重新開機電腦, 變更才會生效。If a source has already been mapped to a log and you remap it to a new log, you must restart the computer for the changes to take effect.

安全性

EventLogPermission
用於管理電腦上的事件記錄檔資訊。for administering event log information on the computer. 相關聯的列舉:AdministerAssociated enumeration: Administer

另請參閱

適用於