EventLog.CreateEventSource Método

Definição

Estabelece um aplicativo como capaz de gravar informações de evento em um log específico no sistema.Establishes an application as able to write event information to a particular log on the system.

Sobrecargas

CreateEventSource(EventSourceCreationData)

Estabelece uma origem do evento válido para a gravação de mensagens de evento localizadas, usando as propriedades de configuração especificadas para a origem do evento e o log de eventos correspondente.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)

Estabelece o nome de origem especificado como uma origem de evento válida para gravar entradas em um log no computador local.Establishes the specified source name as a valid event source for writing entries to a log on the local computer. Esse método também pode criar um novo log personalizado no computador local.This method can also create a new custom log on the local computer.

CreateEventSource(String, String, String)
Obsoleto.
Obsoleto.
Obsoleto.

Estabelece o nome de origem especificado como uma origem de evento válida para gravar entradas em um log no computador especificado.Establishes the specified source name as a valid event source for writing entries to a log on the specified computer. Também é possível usar esse método para criar um novo log personalizado no computador especificado.This method can also be used to create a new custom log on the specified computer.

CreateEventSource(EventSourceCreationData)

Estabelece uma origem do evento válido para a gravação de mensagens de evento localizadas, usando as propriedades de configuração especificadas para a origem do evento e o log de eventos correspondente.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);
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
[<System.MonoNotSupported("remote machine is not supported")>]
static member CreateEventSource : System.Diagnostics.EventSourceCreationData -> unit
Public Shared Sub CreateEventSource (sourceData As EventSourceCreationData)

Parâmetros

sourceData
EventSourceCreationData

As propriedades de configuração para a origem do evento e seu log de eventos de destino.The configuration properties for the event source and its target event log.

Atributos
MonoNotSupportedAttribute

Exceções

O nome do computador especificado em sourceData não é válido.The computer name specified in sourceData is not valid.

- ou --or- O nome da origem especificado em sourceData é null.The source name specified in sourceData is null.

- ou --or- O nome do log especificado em sourceData não é válido.The log name specified in sourceData is not valid. Os nomes de log de eventos precisam serem compostos por caracteres imprimíveis e não podem incluir os caracteres “*”, “?” ou “\”.Event log names must consist of printable characters and cannot include the characters '*', '?', or '\'.

- ou --or- O nome do log especificado em sourceData não é válido para a criação de log do usuário.The log name specified in sourceData is not valid for user log creation. Os nomes de log de eventos AppEvent, SysEvent e SecEvent são reservados para uso do sistema.The Event log names AppEvent, SysEvent, and SecEvent are reserved for system use.

- ou --or- O nome do log corresponde a um nome de origem de evento existente.The log name matches an existing event source name.

- ou --or- O nome da origem especificado no sourceData resulta em um caminho de chave do Registro com mais de 254 caracteres.The source name specified in sourceData results in a registry key path longer than 254 characters.

- ou --or- Os primeiros oito caracteres do nome do log especificado em sourceData não são exclusivos.The first 8 characters of the log name specified in sourceData are not unique.

- ou --or- O nome da origem especificado em sourceData já está registrado.The source name specified in sourceData is already registered.

- ou --or- O nome de origem especificado no sourceData corresponde a um nome de log de eventos existente.The source name specified in sourceData matches an existing event log name.

Não foi possível abrir a chave do Registro para o log de eventos.The registry key for the event log could not be opened.

sourceData é null.sourceData is null.

Exemplos

O exemplo a seguir determina se a origem do evento chamada SampleApplicationSource está registrada no computador local.The following example determines whether the event source named SampleApplicationSource is registered on the local computer. Se a origem do evento não existir, o exemplo definirá o arquivo de recurso de mensagem para a origem e criará a nova origem do evento.If the event source does not exist, the example sets the message resource file for the source and creates the new event source. Por fim, o exemplo define o nome de exibição localizado para o log de eventos, usando o valor do identificador de recurso em DisplayNameMsgId e o caminho do arquivo de recurso em 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

O exemplo usa o seguinte arquivo de texto de mensagem, interno à biblioteca de recursos EventLogMsgs.dll.The example uses the following message text file, built into the resource library EventLogMsgs.dll. Um arquivo de texto de mensagem é a origem da qual o arquivo de recurso de mensagem é criado.A message text file is the source from which the message resource file is created. O arquivo de texto da mensagem define os identificadores de recurso e o texto para a categoria, a mensagem de evento e as cadeias de caracteres de inserção de parâmetro.The message text file defines the resource identifiers and text for the category, event message, and parameter insertion strings. Especificamente, o identificador de recurso 5001 é definido para o nome localizado do log de eventos.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  
.  

Comentários

Use essa sobrecarga para configurar uma nova fonte para gravar entradas em um log de eventos no computador local ou em um computador remoto.Use this overload to configure a new source for writing entries to an event log on the local computer or a remote computer. Não é necessário usar esse método para ler de um log de eventos.It is not necessary to use this method to read from an event log.

O CreateEventSource método usa a entrada sourceData Source LogName e as MachineName Propriedades para criar valores de registro no computador de destino para a nova origem e seu log de eventos associado.The 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. Um novo nome de origem não pode corresponder a um nome de origem existente ou a um nome de log de eventos existente no computador de destino.A new source name cannot match an existing source name or an existing event log name on the target computer. Se a LogName propriedade não estiver definida, a origem será registrada para o log de eventos do aplicativo.If the LogName property is not set, the source is registered for the Application event log. Se o MachineName não estiver definido, a origem será registrada no computador local.If the MachineName is not set, the source is registered on the local computer.

Observação

Para criar uma origem de evento no Windows Vista e posterior ou no Windows Server 2003, você deve ter privilégios administrativos.To create an event source in Windows Vista and later or Windows Server 2003, you must have administrative privileges.

O motivo para esse requisito é que todos os logs de eventos, incluindo segurança, devem ser pesquisados para determinar se a origem do evento é exclusiva.The reason for this requirement is that all event logs, including security, must be searched to determine whether the event source is unique. A partir do Windows Vista, os usuários não têm permissão para acessar o log de segurança; Portanto, um SecurityException é lançado.Starting with Windows Vista, users do not have permission to access the security log; therefore, a SecurityException is thrown.

A partir do Windows Vista, o UAC (controle de conta de usuário) determina os privilégios de um usuário.Starting with Windows Vista, User Account Control (UAC) determines the privileges of a user. Se for um membro do grupo Administradores Internos, você receberá dois tokens de acesso do tempo de execução: um token de acesso do usuário padrão e um token de acesso do administrador.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. Por padrão, você está na função de usuário padrão.By default, you are in the standard user role. Para executar o código que acessa o log de segurança, você deve primeiro elevar seus privilégios do usuário padrão para o administrador.To execute the code that accesses the security log, you must first elevate your privileges from standard user to administrator. Você pode fazer isso ao iniciar um aplicativo clicando com o botão direito do mouse no ícone do aplicativo e indicando que deseja executar como administrador.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.

Use WriteEvent e WriteEntry para gravar eventos em um log de eventos.Use WriteEvent and WriteEntry to write events to an event log. Você deve especificar uma origem do evento para gravar eventos; Você deve criar e configurar a origem do evento antes de gravar a primeira entrada com a origem.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.

Crie a nova origem do evento durante a instalação do seu aplicativo.Create the new event source during the installation of your application. Isso permite que o sistema operacional Atualize sua lista de fontes de eventos registradas e suas configurações.This allows time for the operating system to refresh its list of registered event sources and their configuration. Se o sistema operacional não tiver atualizado sua lista de origens de eventos e você tentar gravar um evento com a nova origem, a operação de gravação falhará.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. Você pode configurar uma nova fonte usando um EventLogInstaller , ou usando o CreateEventSource método.You can configure a new source using an EventLogInstaller, or using the CreateEventSource method. Você deve ter direitos administrativos no computador para criar uma nova origem de evento.You must have administrative rights on the computer to create a new event source.

Você pode criar uma origem de evento para um log de eventos existente ou um novo log de eventos.You can create an event source for an existing event log or a new event log. Quando você cria uma nova fonte para um novo log de eventos, o sistema registra a origem desse log, mas o log não é criado até que a primeira entrada seja gravada nele.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.

O sistema operacional armazena os logs de eventos como arquivos.The operating system stores event logs as files. Quando você usa EventLogInstaller ou CreateEventSource para criar um novo log de eventos, o arquivo associado é armazenado no diretório%SystemRoot%\System32\Config no computador especificado.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. O nome do arquivo é definido acrescentando os oito primeiros caracteres da Log propriedade com a extensão de nome de arquivo ". evt".The file name is set by appending the first 8 characters of the Log property with the ".evt" file name extension.

Cada fonte só pode gravar em um log de eventos por vez; no entanto, seu aplicativo pode usar várias fontes para gravar em vários logs de eventos.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. Por exemplo, seu aplicativo pode exigir várias fontes configuradas para diferentes logs de eventos ou arquivos de recurso diferentes.For example, your application might require multiple sources configured for different event logs or different resource files.

Você pode registrar a origem do evento com arquivos de recursos localizados para sua categoria de evento e cadeias de caracteres de mensagem.You can register the event source with localized resource file(s) for your event category and message strings. Seu aplicativo pode gravar entradas de log de eventos usando identificadores de recursos, em vez de especificar a cadeia de caracteres real.Your application can write event log entries using resource identifiers, rather than specifying the actual string. O Visualizador de Eventos usa o identificador de recurso para localizar e exibir a cadeia de caracteres correspondente do arquivo de recursos localizado com base nas configurações de idioma atuais.The Event Viewer uses the resource identifier to find and display the corresponding string from the localized resource file based on current language settings. Você pode registrar um arquivo separado para categorias de evento, mensagens e cadeias de caracteres de inserção de parâmetro, ou pode registrar o mesmo arquivo de recurso para todos os três tipos de cadeias de caracteres.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. Use as CategoryCount CategoryResourceFile Propriedades,, e MessageResourceFile ParameterResourceFile para configurar a origem para gravar entradas localizadas no log de eventos.Use the CategoryCount, CategoryResourceFile, MessageResourceFile, and ParameterResourceFile properties to configure the source to write localized entries to the event log. Se seu aplicativo gravar valores de cadeia de caracteres diretamente no log de eventos, você não precisará definir essas propriedades.If your application writes strings values directly to the event log, you do not need to set these properties.

A origem deve ser configurada para gravar entradas localizadas ou para gravar cadeias de caracteres diretas.The source must be configured either for writing localized entries or for writing direct strings. Se seu aplicativo gravar entradas usando os identificadores de recurso e os valores de cadeia de caracteres, você deverá registrar duas fontes separadas.If your application writes entries using both resource identifiers and string values, you must register two separate sources. Por exemplo, configure uma fonte com arquivos de recursos e, em seguida, use essa origem no WriteEvent método para gravar entradas usando identificadores de recursos no log de eventos.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. Em seguida, crie uma fonte diferente sem arquivos de recursos e use essa origem no WriteEntry método para gravar cadeias de caracteres diretamente no log de eventos usando essa origem.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.

Para alterar os detalhes de configuração de uma origem existente, você deve excluir a origem e, em seguida, criá-la com a nova configuração.To change the configuration details of an existing source, you must delete the source and then create it with the new configuration. Se outros aplicativos ou componentes usarem a origem existente, crie uma nova fonte com a configuração atualizada em vez de excluir a origem existente.If other applications or components use the existing source, create a new source with the updated configuration rather than deleting the existing source.

Observação

Se uma fonte estiver configurada para um log de eventos e você reconfigurá-la para outro log de eventos, você deverá reiniciar o computador para que as alterações entrem em vigor.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.

Confira também

Aplica-se a

CreateEventSource(String, String)

Estabelece o nome de origem especificado como uma origem de evento válida para gravar entradas em um log no computador local.Establishes the specified source name as a valid event source for writing entries to a log on the local computer. Esse método também pode criar um novo log personalizado no computador local.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)

Parâmetros

source
String

O nome de origem com o qual o aplicativo está registrado no computador local.The source name by which the application is registered on the local computer.

logName
String

O nome do log no qual as entradas da fonte são gravadas.The name of the log the source's entries are written to. Os valores possíveis incluem Aplicativo, Sistema ou um log de eventos personalizado.Possible values include Application, System, or a custom event log.

Exceções

source é uma cadeia de caracteres vazia ("") ou null.source is an empty string ("") or null.

- ou --or- logName não é um nome válido de log de eventos.logName is not a valid event log name. Os nomes de log de eventos devem conter caracteres imprimíveis e não podem incluir os caracteres “*”, “?” ou “\”.Event log names must consist of printable characters, and cannot include the characters '*', '?', or '\'.

- ou --or- logName não é válido para a criação de log de usuário.logName is not valid for user log creation. Os nomes de log de eventos AppEvent, SysEvent e SecEvent são reservados para uso do sistema.The event log names AppEvent, SysEvent, and SecEvent are reserved for system use.

- ou --or- O nome do log corresponde a um nome de origem de evento existente.The log name matches an existing event source name.

- ou --or- O nome da origem resulta em um caminho de chave do Registro com mais de 254 caracteres.The source name results in a registry key path longer than 254 characters.

- ou --or- Os 8 primeiros caracteres de logName correspondem aos 8 primeiros caracteres de um log de eventos existente.The first 8 characters of logName match the first 8 characters of an existing event log name.

- ou --or- A fonte não pode ser registrada porque já existe no computador local.The source cannot be registered because it already exists on the local computer.

- ou --or- O nome de origem corresponde a um nome de log de eventos existente.The source name matches an existing event log name.

Não foi possível abrir a chave do Registro do log de eventos no computador local.The registry key for the event log could not be opened on the local computer.

Exemplos

O exemplo a seguir criará a origem MySource se ela ainda não existir e gravará uma entrada no log de eventos 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.Diagnostics
Imports System.Threading

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

Comentários

Use essa sobrecarga para criar um log personalizado ou para criar e registrar um Source em um log existente no computador local.Use this overload to create a custom log or to create and register a Source to an existing log on the local computer.

Se logName for null ou uma cadeia de caracteres vazia ("") quando você chamar CreateEventSource , o log usa como padrão o log do aplicativo.If logName is null or an empty string ("") when you call CreateEventSource, the log defaults to the Application log. Se o log não existir no computador local, o sistema criará um log personalizado e registrará seu aplicativo como um Source para esse log.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.

Observação

Para criar uma origem de evento no Windows Vista e posterior ou no Windows Server 2003, você deve ter privilégios administrativos.To create an event source in Windows Vista and later or Windows Server 2003, you must have administrative privileges.

O motivo para esse requisito é que todos os logs de eventos, incluindo segurança, devem ser pesquisados para determinar se a origem do evento é exclusiva.The reason for this requirement is that all event logs, including security, must be searched to determine whether the event source is unique. A partir do Windows Vista, os usuários não têm permissão para acessar o log de segurança; Portanto, um SecurityException é lançado.Starting with Windows Vista, users do not have permission to access the security log; therefore, a SecurityException is thrown.

No Windows Vista e posterior, UAC (Controle de Conta de Usuário) determina os privilégios de um usuário.In Windows Vista and later, User Account Control (UAC) determines the privileges of a user. Se for um membro do grupo Administradores Internos, você receberá dois tokens de acesso do tempo de execução: um token de acesso do usuário padrão e um token de acesso do administrador.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. Por padrão, você está na função de usuário padrão.By default, you are in the standard user role. Para executar o código que acessa o log de segurança, você deve primeiro elevar seus privilégios do usuário padrão para o administrador.To execute the code that accesses the security log, you must first elevate your privileges from standard user to administrator. Você pode fazer isso ao iniciar um aplicativo clicando com o botão direito do mouse no ícone do aplicativo e indicando que deseja executar como administrador.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.

Você só precisa criar uma origem do evento se estiver gravando no log de eventos.You only need to create an event source if you are writing to the event log. Antes de gravar uma entrada em um log de eventos, você deve registrar a origem do evento no log de eventos como uma fonte de eventos válida.Before writing an entry to an event log, you must register the event source with the event log as a valid source of events. Quando você grava uma entrada de log, o sistema usa o Source para localizar o log apropriado no qual inserir a entrada.When you write a log entry, the system uses the Source to find the appropriate log in which to place your entry. Se você estiver lendo o log de eventos, poderá especificar o Source , ou a Log e MachineName .If you are reading the event log, you can either specify the Source, or a Log and MachineName.

Observação

Não será necessário especificar o MachineName se você estiver se conectando a um log no computador local.You are not required to specify the MachineName if you are connecting to a log on the local computer. Se você não especificar o MachineName ao ler de um log, o computador local (".") será assumido.If you do not specify the MachineName when reading from a log, the local computer (".") is assumed.

Use WriteEvent e WriteEntry para gravar eventos em um log de eventos.Use WriteEvent and WriteEntry to write events to an event log. Você deve especificar uma origem do evento para gravar eventos; Você deve criar e configurar a origem do evento antes de gravar a primeira entrada com a origem.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.

Crie a nova origem do evento durante a instalação do seu aplicativo.Create the new event source during the installation of your application. Isso permite que o sistema operacional Atualize sua lista de fontes de eventos registradas e suas configurações.This allows time for the operating system to refresh its list of registered event sources and their configuration. Se o sistema operacional não tiver atualizado sua lista de origens de eventos e você tentar gravar um evento com a nova origem, a operação de gravação falhará.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. Você pode configurar uma nova fonte usando um EventLogInstaller , ou usando o CreateEventSource método.You can configure a new source using an EventLogInstaller, or using the CreateEventSource method. Você deve ter direitos administrativos no computador para criar uma nova origem de evento.You must have administrative rights on the computer to create a new event source.

Você pode criar uma origem de evento para um log de eventos existente ou um novo log de eventos.You can create an event source for an existing event log or a new event log. Quando você cria uma nova fonte para um novo log de eventos, o sistema registra a origem desse log, mas o log não é criado até que a primeira entrada seja gravada nele.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.

O sistema operacional armazena os logs de eventos como arquivos.The operating system stores event logs as files. Quando você usa EventLogInstaller ou CreateEventSource para criar um novo log de eventos, o arquivo associado é armazenado no diretório%SystemRoot%\System32\Config no computador especificado.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. O nome do arquivo é definido acrescentando os oito primeiros caracteres da Log propriedade com a extensão de nome de arquivo ". evt".The file name is set by appending the first 8 characters of the Log property with the ".evt" file name extension.

A origem deve ser exclusiva no computador local; um novo nome de origem não pode corresponder a um nome de origem existente ou a um nome de log de eventos existente.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. Cada fonte pode gravar em apenas um log de eventos por vez; no entanto, seu aplicativo pode usar várias fontes para gravar em vários logs de eventos.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. Por exemplo, seu aplicativo pode exigir várias fontes configuradas para diferentes logs de eventos ou arquivos de recurso diferentes.For example, your application might require multiple sources configured for different event logs or different resource files.

A origem deve ser configurada para gravar entradas localizadas ou para gravar cadeias de caracteres diretas.The source must be configured either for writing localized entries or for writing direct strings. Se seu aplicativo gravar entradas usando os identificadores de recurso e os valores de cadeia de caracteres, você deverá registrar duas fontes separadas.If your application writes entries using both resource identifiers and string values, you must register two separate sources. Por exemplo, configure uma fonte com arquivos de recursos e, em seguida, use essa origem no WriteEvent método para gravar entradas usando identificadores de recursos no log de eventos.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. Em seguida, crie uma fonte diferente sem arquivos de recursos e use essa origem no WriteEntry método para gravar cadeias de caracteres diretamente no log de eventos usando essa origem.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.

Para alterar os detalhes de configuração de uma origem existente, você deve excluir a origem e, em seguida, criá-la com a nova configuração.To change the configuration details of an existing source, you must delete the source and then create it with the new configuration. Se outros aplicativos ou componentes usarem a origem existente, crie uma nova fonte com a configuração atualizada em vez de excluir a origem existente.If other applications or components use the existing source, create a new source with the updated configuration rather than deleting the existing source.

Observação

Se uma fonte já tiver sido mapeada para um log e você o remapear para um novo log, você deverá reiniciar o computador para que as alterações entrem em vigor.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.

Confira também

Aplica-se a

CreateEventSource(String, String, String)

Cuidado

This method has been deprecated. Please use System.Diagnostics.EventLog.CreateEventSource(EventSourceCreationData sourceData) instead. http://go.microsoft.com/fwlink/?linkid=14202

Cuidado

This method has been deprecated. Please use System.Diagnostics.EventLog.CreateEventSource(EventSourceCreationData sourceData) instead. https://go.microsoft.com/fwlink/?linkid=14202

Cuidado

use CreateEventSource(EventSourceCreationData) instead

Estabelece o nome de origem especificado como uma origem de evento válida para gravar entradas em um log no computador especificado.Establishes the specified source name as a valid event source for writing entries to a log on the specified computer. Também é possível usar esse método para criar um novo log personalizado no computador especificado.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("This method has been deprecated.  Please use System.Diagnostics.EventLog.CreateEventSource(EventSourceCreationData sourceData) instead.  http://go.microsoft.com/fwlink/?linkid=14202")]
public static void CreateEventSource (string source, string logName, string machineName);
[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);
public static void CreateEventSource (string source, string logName, string machineName);
[System.Obsolete("use CreateEventSource(EventSourceCreationData) instead")]
public static void CreateEventSource (string source, string logName, string machineName);
[<System.Obsolete("This method has been deprecated.  Please use System.Diagnostics.EventLog.CreateEventSource(EventSourceCreationData sourceData) instead.  http://go.microsoft.com/fwlink/?linkid=14202")>]
static member CreateEventSource : string * string * string -> unit
[<System.Obsolete("This method has been deprecated.  Please use System.Diagnostics.EventLog.CreateEventSource(EventSourceCreationData sourceData) instead.  https://go.microsoft.com/fwlink/?linkid=14202")>]
static member CreateEventSource : string * string * string -> unit
static member CreateEventSource : string * string * string -> unit
[<System.Obsolete("use CreateEventSource(EventSourceCreationData) instead")>]
static member CreateEventSource : string * string * string -> unit
Public Shared Sub CreateEventSource (source As String, logName As String, machineName As String)

Parâmetros

source
String

A fonte pela qual o aplicativo está registrado no computador especificado.The source by which the application is registered on the specified computer.

logName
String

O nome do log no qual as entradas da fonte são gravadas.The name of the log the source's entries are written to. Os valores possíveis incluem Aplicativo, Sistema ou um log de eventos personalizado.Possible values include Application, System, or a custom event log. Se você não especificar um valor, logName o definirá com o padrão Aplicativo.If you do not specify a value, logName defaults to Application.

machineName
String

O nome do computador que registrará essa origem de evento ou "." para o computador local.The name of the computer to register this event source with, or "." for the local computer.

Atributos

Exceções

machineName não é um nome do computador válido.The machineName is not a valid computer name.

- ou --or- source é uma cadeia de caracteres vazia ("") ou null.source is an empty string ("") or null.

- ou --or- logName não é um nome válido de log de eventos.logName is not a valid event log name. Os nomes de log de eventos devem conter caracteres imprimíveis e não podem incluir os caracteres “*”, “?” ou “\”.Event log names must consist of printable characters, and cannot include the characters '*', '?', or '\'.

- ou --or- logName não é válido para a criação de log de usuário.logName is not valid for user log creation. Os nomes de log de eventos AppEvent, SysEvent e SecEvent são reservados para uso do sistema.The event log names AppEvent, SysEvent, and SecEvent are reserved for system use.

- ou --or- O nome do log corresponde a um nome de origem de evento existente.The log name matches an existing event source name.

- ou --or- O nome da origem resulta em um caminho de chave do Registro com mais de 254 caracteres.The source name results in a registry key path longer than 254 characters.

- ou --or- Os oito primeiros caracteres de logName correspondem aos oito primeiros caracteres de um log de eventos existente no computador especificado.The first 8 characters of logName match the first 8 characters of an existing event log name on the specified computer.

- ou --or- A origem não pode ser registrada porque já existe no computador especificado.The source cannot be registered because it already exists on the specified computer.

- ou --or- O nome da origem corresponde a um nome de origem de evento existente.The source name matches an existing event source name.

Não foi possível abrir a chave do Registro do log de eventos no computador especificado.The registry key for the event log could not be opened on the specified computer.

Exemplos

O exemplo a seguir cria a origem MySource no computador MyServer e grava uma entrada no log de eventos 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.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
End Class

Comentários

Use essa sobrecarga para criar um log personalizado ou para criar e registrar um Source em um log existente no computador especificado.Use this overload to create a custom log or to create and register a Source to an existing log on the specified computer.

Se logName for null ou uma cadeia de caracteres vazia ("") quando você chamar CreateEventSource , o log usa como padrão o log do aplicativo.If logName is null or an empty string ("") when you call CreateEventSource, the log defaults to the Application log. Se o log não existir no computador especificado, o sistema criará um log personalizado e registrará seu aplicativo como um Source para esse log.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.

Você só precisa criar uma origem do evento se estiver gravando no log de eventos.You only need to create an event source if you are writing to the event log. Antes de gravar uma entrada em um log de eventos, você deve registrar a origem do evento no log de eventos como uma fonte de eventos válida.Before writing an entry to an event log, you must register the event source with the event log as a valid source of events. Quando você grava uma entrada de log, o sistema usa o Source para localizar o log apropriado no qual inserir a entrada.When you write a log entry, the system uses the Source to find the appropriate log in which to place your entry. Se você estiver lendo o log de eventos, poderá especificar o Source , ou a Log e MachineName .If you are reading the event log, you can either specify the Source, or a Log and MachineName.

Observação

Para criar uma origem de evento no Windows Vista e posterior ou no Windows Server 2003, você deve ter privilégios administrativos.To create an event source in Windows Vista and later or Windows Server 2003, you must have administrative privileges.

O motivo para esse requisito é que todos os logs de eventos, incluindo segurança, devem ser pesquisados para determinar se a origem do evento é exclusiva.The reason for this requirement is that all event logs, including security, must be searched to determine whether the event source is unique. No Windows Vista e posterior, os usuários não têm permissão para acessar o log de segurança; Portanto, um SecurityException é lançado.In Windows Vista and later, users do not have permission to access the security log; therefore, a SecurityException is thrown.

No Windows Vista e posterior, UAC (Controle de Conta de Usuário) determina os privilégios de um usuário.In Windows Vista and later, User Account Control (UAC) determines the privileges of a user. Se for um membro do grupo Administradores Internos, você receberá dois tokens de acesso do tempo de execução: um token de acesso do usuário padrão e um token de acesso do administrador.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. Por padrão, você está na função de usuário padrão.By default, you are in the standard user role. Para executar o código que acessa o log de segurança, você deve primeiro elevar seus privilégios do usuário padrão para o administrador.To execute the code that accesses the security log, you must first elevate your privileges from standard user to administrator. Você pode fazer isso ao iniciar um aplicativo clicando com o botão direito do mouse no ícone do aplicativo e indicando que deseja executar como administrador.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.

Use WriteEvent e WriteEntry para gravar eventos em um log de eventos.Use WriteEvent and WriteEntry to write events to an event log. Você deve especificar uma origem do evento para gravar eventos; Você deve criar e configurar a origem do evento antes de gravar a primeira entrada com a origem.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.

Crie a nova origem do evento durante a instalação do seu aplicativo.Create the new event source during the installation of your application. Isso permite que o sistema operacional Atualize sua lista de fontes de eventos registradas e suas configurações.This allows time for the operating system to refresh its list of registered event sources and their configuration. Se o sistema operacional não tiver atualizado sua lista de origens de eventos e você tentar gravar um evento com a nova origem, a operação de gravação falhará.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. Você pode configurar uma nova fonte usando um EventLogInstaller , ou usando o CreateEventSource método.You can configure a new source using an EventLogInstaller, or using the CreateEventSource method. Você deve ter direitos administrativos no computador para criar uma nova origem de evento.You must have administrative rights on the computer to create a new event source.

Você pode criar uma origem de evento para um log de eventos existente ou um novo log de eventos.You can create an event source for an existing event log or a new event log. Quando você cria uma nova fonte para um novo log de eventos, o sistema registra a origem desse log, mas o log não é criado até que a primeira entrada seja gravada nele.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.

O sistema operacional armazena os logs de eventos como arquivos.The operating system stores event logs as files. Quando você usa EventLogInstaller ou CreateEventSource para criar um novo log de eventos, o arquivo associado é armazenado no diretório%SystemRoot%\System32\Config no computador especificado.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. O nome do arquivo é definido acrescentando os oito primeiros caracteres da Log propriedade com a extensão de nome de arquivo ". evt".The file name is set by appending the first 8 characters of the Log property with the ".evt" file name extension.

A origem deve ser exclusiva no computador local; um novo nome de origem não pode corresponder a um nome de origem existente ou a um nome de log de eventos existente.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. Cada fonte pode gravar em apenas um log de eventos por vez; no entanto, seu aplicativo pode usar várias fontes para gravar em vários logs de eventos.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. Por exemplo, seu aplicativo pode exigir várias fontes configuradas para diferentes logs de eventos ou arquivos de recurso diferentes.For example, your application might require multiple sources configured for different event logs or different resource files.

A origem deve ser configurada para gravar entradas localizadas ou para gravar cadeias de caracteres diretas.The source must be configured either for writing localized entries or for writing direct strings. Se seu aplicativo gravar entradas usando os identificadores de recurso e os valores de cadeia de caracteres, você deverá registrar duas fontes separadas.If your application writes entries using both resource identifiers and string values, you must register two separate sources. Por exemplo, configure uma fonte com arquivos de recursos e, em seguida, use essa origem no WriteEvent método para gravar entradas usando identificadores de recursos no log de eventos.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. Em seguida, crie uma fonte diferente sem arquivos de recursos e use essa origem no WriteEntry método para gravar cadeias de caracteres diretamente no log de eventos usando essa origem.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.

Para alterar os detalhes de configuração de uma origem existente, você deve excluir a origem e, em seguida, criá-la com a nova configuração.To change the configuration details of an existing source, you must delete the source and then create it with the new configuration. Se outros aplicativos ou componentes usarem a origem existente, crie uma nova fonte com a configuração atualizada em vez de excluir a origem existente.If other applications or components use the existing source, create a new source with the updated configuration rather than deleting the existing source.

Observação

Se uma fonte já tiver sido mapeada para um log e você o remapear para um novo log, você deverá reiniciar o computador para que as alterações entrem em vigor.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.

Confira também

Aplica-se a