EventLog Конструкторы

Определение

Инициализирует новый экземпляр класса EventLog.

Перегрузки

Имя Описание
EventLog()

Инициализирует новый экземпляр класса EventLog. Не связывает экземпляр с любым журналом.

EventLog(String)

Инициализирует новый экземпляр класса EventLog. Связывает экземпляр с журналом на локальном компьютере.

EventLog(String, String)

Инициализирует новый экземпляр класса EventLog. Связывает экземпляр с журналом на указанном компьютере.

EventLog(String, String, String)

Инициализирует новый экземпляр класса EventLog. Связывает экземпляр с журналом на указанном компьютере и создает или назначает указанный источник указанному источнику EventLog.

EventLog()

Исходный код:
EventLog.cs
Исходный код:
EventLog.cs
Исходный код:
EventLog.cs
Исходный код:
EventLog.cs
Исходный код:
EventLog.cs
Исходный код:
EventLog.cs
Исходный код:
EventLog.cs
Исходный код:
EventLog.cs

Инициализирует новый экземпляр класса EventLog. Не связывает экземпляр с любым журналом.

public:
 EventLog();
public EventLog();
Public Sub New ()

Примеры

В следующем примере создается источник MySource , если он еще не существует, и записывает запись в журнал MyNewLogсобытий.

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

Комментарии

Перед вызовом WriteEntrySource укажите свойство экземпляраEventLog. Если вы читаете Entries только из журнала, можно также указать только Log те свойства и MachineName свойства.

Замечание

Если не указано значение, предполагается, что локальный MachineNameкомпьютер (".") предполагается.

В следующей таблице показаны начальные значения свойств для экземпляра EventLog.

Недвижимость Начальное значение
Source Пустая строка ("").
Log Пустая строка ("").
MachineName Локальный компьютер (".").

См. также раздел

Применяется к

EventLog(String)

Исходный код:
EventLog.cs
Исходный код:
EventLog.cs
Исходный код:
EventLog.cs
Исходный код:
EventLog.cs
Исходный код:
EventLog.cs
Исходный код:
EventLog.cs
Исходный код:
EventLog.cs
Исходный код:
EventLog.cs

Инициализирует новый экземпляр класса EventLog. Связывает экземпляр с журналом на локальном компьютере.

public:
 EventLog(System::String ^ logName);
public EventLog(string logName);
new System.Diagnostics.EventLog : string -> System.Diagnostics.EventLog
Public Sub New (logName As String)

Параметры

logName
String

Имя журнала на локальном компьютере.

Исключения

Имя nullжурнала — .

Недопустимое имя журнала.

Примеры

Следующий пример считывает записи в журнале событий myNewLog на локальном компьютере.

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 log name.
        EventLog myLog = new EventLog("myNewLog");

        // Read the event log entries.
        foreach (EventLogEntry entry in myLog.Entries)
        {
            Console.WriteLine("\tEntry: " + entry.Message);
        }
    }
}
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

        Dim myLog As New EventLog("myNewLog")
        
        ' Read the event log entries.
        Dim entry As EventLogEntry
        For Each entry In  myLog.Entries
            Console.WriteLine((ControlChars.Tab & "Entry: " & entry.Message))
        Next entry
    End Sub
End Class

Комментарии

Эта перегрузка задает Log свойство параметру logName . Перед вызовом WriteEntrySource укажите свойство экземпляраEventLog. Если вы читаете Entries только из журнала, можно также указать только Log те свойства и MachineName свойства.

Замечание

Если не указано значение, предполагается, что локальный MachineNameкомпьютер (".") предполагается. Эта перегрузка конструктора указывает Log свойство, но его можно изменить перед чтением Entries свойства.

Если источник, указанный в Source свойстве, является уникальным из других источников на компьютере, последующий вызов WriteEntry создает журнал с указанным именем, если он еще не существует.

В следующей таблице показаны начальные значения свойств для экземпляра EventLog.

Недвижимость Начальное значение
Source Пустая строка ("").
Log Параметр logName .
MachineName Локальный компьютер (".").

См. также раздел

Применяется к

EventLog(String, String)

Исходный код:
EventLog.cs
Исходный код:
EventLog.cs
Исходный код:
EventLog.cs
Исходный код:
EventLog.cs
Исходный код:
EventLog.cs
Исходный код:
EventLog.cs
Исходный код:
EventLog.cs
Исходный код:
EventLog.cs

Инициализирует новый экземпляр класса EventLog. Связывает экземпляр с журналом на указанном компьютере.

public:
 EventLog(System::String ^ logName, System::String ^ machineName);
public EventLog(string logName, string machineName);
new System.Diagnostics.EventLog : string * string -> System.Diagnostics.EventLog
Public Sub New (logName As String, machineName As String)

Параметры

logName
String

Имя журнала на указанном компьютере.

machineName
String

Компьютер, на котором существует журнал.

Исключения

Имя nullжурнала — .

Недопустимое имя журнала.

–или–

Недопустимое имя компьютера.

Примеры

Следующий пример считывает записи в журнале событий myNewLog на компьютере myServer.

using System;
using System.Diagnostics;
using System.Threading;

class MySample1
{
    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", "myServer");
            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 log name.
        EventLog myLog = new EventLog("myNewLog", "myServer");

        // Read the event log entries.
        foreach (EventLogEntry entry in myLog.Entries)
        {
            Console.WriteLine("\tEntry: " + entry.Message);
        }
    }
}
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", "myServer")
            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 log name.
        Dim myLog As New EventLog("myNewLog", "myServer")
        
        ' Read the event log entries.
        Dim entry As EventLogEntry
        For Each entry In  myLog.Entries
            Console.WriteLine((ControlChars.Tab & "Entry: " & entry.Message))
        Next entry
    End Sub
End Class

Комментарии

Эта перегрузка Log задает свойство logName параметру и MachineName свойству параметру machineName . Перед вызовом WriteEntrySource укажите свойство EventLogобъекта . Если вы читаете Entries только из журнала, можно также указать только Log те свойства и MachineName свойства.

Замечание

Эта перегрузка конструктора Log указывает и MachineName свойства, но можно изменить либо перед чтением Entries свойства.

В следующей таблице показаны начальные значения свойств для экземпляра EventLog.

Недвижимость Начальное значение
Source Пустая строка ("").
Log Параметр logName .
MachineName Параметр machineName .

См. также раздел

Применяется к

EventLog(String, String, String)

Исходный код:
EventLog.cs
Исходный код:
EventLog.cs
Исходный код:
EventLog.cs
Исходный код:
EventLog.cs
Исходный код:
EventLog.cs
Исходный код:
EventLog.cs
Исходный код:
EventLog.cs
Исходный код:
EventLog.cs

Инициализирует новый экземпляр класса EventLog. Связывает экземпляр с журналом на указанном компьютере и создает или назначает указанный источник указанному источнику EventLog.

public:
 EventLog(System::String ^ logName, System::String ^ machineName, System::String ^ source);
public EventLog(string logName, string machineName, string source);
new System.Diagnostics.EventLog : string * string * string -> System.Diagnostics.EventLog
Public Sub New (logName As String, machineName As String, source As String)

Параметры

logName
String

Имя журнала на указанном компьютере.

machineName
String

Компьютер, на котором существует журнал.

source
String

Источник записей журнала событий.

Исключения

Имя nullжурнала — .

Недопустимое имя журнала.

–или–

Недопустимое имя компьютера.

Примеры

В следующем примере записывается запись в журнал событий MyNewLog на локальном компьютере с помощью источника MySource.

using System;
using System.Diagnostics;
using System.Threading;

class MySample2
{
    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("myNewLog", ".", "MySource");

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

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("myNewLog", ".", "MySource")
        
        ' Write an entry to the log.        
        myLog.WriteEntry(("Writing to event log on " & myLog.MachineName))
    End Sub
End Class

Комментарии

Этот конструктор задает Log свойство logName параметру, MachineName свойству machineName параметру и Source свойству source для параметра. Свойство Source требуется при записи в журнал событий. Однако если вы читаете только из журнала событий, требуются только Log свойства и MachineName свойства (если журнал событий на сервере уже связан с ним). Если вы читаете только из журнала событий, может потребоваться еще одна перегрузка конструктора.

В следующей таблице показаны начальные значения свойств для экземпляра EventLog.

Недвижимость Начальное значение
Source Параметр source .
Log Параметр logName .
MachineName Параметр machineName .

См. также раздел

Применяется к