В данной статье описывается, как получить доступ к и
Настройка журналов событий Windows, с помощью Microsoft.NET Framework. С помощью
Журнал событий класс может взаимодействовать с журналами событий Windows. С помощью
Журнал событий записи класса, можно прочитать в существующих журналах
журнал событий, создавать или удалять источники событий удалять журналы и отвечать на вход
операции. В статье также описывается, как создать новые файлы журнала при создании
Источник события.
Требования
В следующем списке представлены рекомендуемого оборудования, программного обеспечения,
сетевой инфраструктуры и пакетов обновления, которые необходимы:
- Корпорация Майкрософт.NET Framework
- Microsoft Visual C#.NET или Microsoft Visual C# 2005.
В данной статье предполагается, что вы знакомы со следующими
разделы:
- Microsoft Visual C#.NET или Microsoft Visual C# 2005 синтаксис
- Microsoft Visual Studio.NET или Microsoft среды Visual Studio 2005
- Обработка ошибок в.NET Framework
Поиск существующего журнала на компьютере
Существующие журналы можно найти на компьютере с помощью
общий метод
GetEventLogs из
Журнал событий класс. В
GetEventLogs метод выполняет поиск всех журналов событий на локальном компьютере и
Создает массив
Журнал событий объектов, содержащих список. В следующем примере извлекается
Список журналов на локальном компьютере, а затем отображает имя журнала в
окно консоли.
EventLog[] remoteEventLogs;
// Gets logs on the local computer, gives remote computer name to get the logs on the remote computer.
remoteEventLogs = EventLog.GetEventLogs(System.Environment.MachineName);
Console.WriteLine("Number of logs on computer: " + remoteEventLogs.Length);
for ( int i=0; i<remoteEventLogs.Length; i++ )
Console.WriteLine("Log: " + remoteEventLogs[i].Log);Чтение и запись журналов
Локальные и удаленные системы
Чтение журнала
Чтение журнала событий, с помощью
Операции Свойства
Журнал событий класс. В
Журнал событий Класс
Операции Свойство представляет собой коллекцию всех записей в журнале событий. Вы
можно выполнять итерации по коллекции и прочитать все записи в указанном
журнал. Следующий код демонстрирует это:
//logType can be Application, Security, System or any other Custom Log.
string logType = "Application";
EventLog ev = new EventLog(logType, System.Environment.MachineName);
int LastLogToShow = ev.Entries.Count;
if ( LastLogToShow <= 0 )
Console.WriteLine("No Event Logs in the Log :" + logType);
// Read the last 2 records in the specified log.
int i;
for ( i = ev.Entries.Count - 1; i>= LastLogToShow - 2; i--)
{
EventLogEntry CurrentEntry = ev.Entries[i];
Console.WriteLine("Event ID : " + CurrentEntry.EventID);
Console.WriteLine("Entry Type : " + CurrentEntry.EntryType.ToString());
Console.WriteLine("Message : " + CurrentEntry.Message + "\n");
}
ev.Close();Запись в журналы
Для записи журнала событий, используйте
WriteEntry метод
Журнал событий класс. Успешно выполнять запись в журнал событий, необходимо приложение
иметь разрешение на запись в журнал, он пытается записать. Для получения дополнительных
сведения о разрешениях, которые необходимы для чтения и записи
журнал событий, посетите следующий веб-узел корпорации Майкрософт.
Необходимо задать свойство source на вашем
Журнал событий экземпляр компонента перед внесением записей в журнал. Когда
компонент вносит запись, система автоматически проверяет наличие
Источник регистрируется в журнале событий данного компонента
запись в, а затем вызывает
CreateEventSource (если он
CreateEventSource должен быть вызван).
//See if the source exists.
if ( ! ( EventLog.SourceExists("MySystemSource", System.Environment.MachineName)))
EventLog.CreateEventSource("MySystemSource", "System", System.Environment.MachineName);
EventLog ev = new EventLog("System", System.Environment.MachineName, "MySystemSource");
/* Writing to system log, in the similar way you can write to other
* logs that you have appropriate permissions to write to
*/
ev.WriteEntry("Warning is written to system Log", EventLogEntryType.Warning, 10001);
MessageBox.Show("Warning is written to System Log");
ev.Close(); Очистить
Журналы
Прекращается при заполнении журнала событий запись новых событий
сведения, или началом перезаписи предыдущих операций. Если запись событий прекращается,
Очистить существующие записи из журнала и локальный вход для начала записи
события снова. Вызов
Очистить метод экземпляра компонента журнала событий.
Примечание Очистка журнала событий, необходимо чтобы администратор
разрешения на компьютере, где находится журнал.
//Create an EventLog instance and pass log name and MachineName where the log resides.
EventLog ev = new EventLog("Security", System.Environment.MachineName);
ev.Clear();
ev.Close(); Создание и удаление
Пользовательские журналы событий
Создать пользовательский журнал
Можно использовать
CreateEventSource метод, чтобы создать собственный пользовательский обработчик событий. Перед созданием
журнал событий использования
SourceExists метод, чтобы проверить, не поддерживает источника с помощью
уже существует, а затем вызвать метод
CreateEventSource. При попытке создания журнала событий, который уже существует
System.ArgumentException создается исключение.
// Create the source, if it does not already exist.
if (! (EventLog.SourceExists("MyOldSource", System.Environment.MachineName)))
EventLog.CreateEventSource("MyOldSource", "MyNewLog", System.Environment.MachineName);
Console.WriteLine("CreatingEventSource"); Удаление пользовательского журнала
Чтобы удалить журнал событий, можно использовать
Удалить метод
Журнал событий класс. Несколько источников может записать в журнал событий. Таким образом,
Перед удалением пользовательского журнала убедитесь, что нет никаких других источников
При записи этого журнала.
string logName = "MyNewLog";
if ( EventLog.SourceExists("MyOldSource", System.Environment.MachineName))
{
logName = EventLog.LogNameFromSourceName("MyOldSource", System.Environment.MachineName);
EventLog.DeleteEventSource("MyOldSource", System.Environment.MachineName);
EventLog.Delete(logName, System.Environment.MachineName);
Console.WriteLine(logName + " deleted.");
} Получение событий
Уведомления
При добавлении записи можно получать уведомления о событии
журналом. Чтобы сделать это, следует реализовать
EntryWritten обработчик событий для экземпляра компонента
Журнал событий. Кроме того значение
EnableRaisingEvents Кому
ИСТИНА.
Примечание Получать уведомления о событиях можно только при записи операции
на локальном компьютере. Не распространяется на операции, которые являются
запись на удаленном компьютере.
Полный исходный код
Перепись
using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;
using System.Security;
using System.IO;
using System.Diagnostics;
namespace WindowsApplication1
{
/// <summary>
/// Summary description for Form1.
/// </summary>
public class Form1 : System.Windows.Forms.Form
{
private System.Diagnostics.EventLog eventLog1;
private System.Windows.Forms.Button btnListLog;
private System.Windows.Forms.Button btnReadLog;
private System.Windows.Forms.Button btnWriteLog;
private System.Windows.Forms.Button btnClearLog;
private System.Windows.Forms.Button btnCreateLog;
private System.Windows.Forms.Button btnDeleteLog;
private System.Windows.Forms.Button btnRecNotice;
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.Container components = null;
public Form1()
{
//
// Required for Windows Form Designer support.
//
InitializeComponent();
//
// TODO: Add any constructor code after InitializeComponent call.
//
}
/// <summary>
/// Clean up any resources that are being used.
/// </summary>
protected override void Dispose( bool disposing )
{
if( disposing )
{
if (components != null)
{
components.Dispose();
}
}
base.Dispose( disposing );
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.eventLog1 = new System.Diagnostics.EventLog();
this.btnListLog = new System.Windows.Forms.Button();
this.btnReadLog = new System.Windows.Forms.Button();
this.btnWriteLog = new System.Windows.Forms.Button();
this.btnClearLog = new System.Windows.Forms.Button();
this.btnCreateLog = new System.Windows.Forms.Button();
this.btnDeleteLog = new System.Windows.Forms.Button();
this.btnRecNotice = new System.Windows.Forms.Button();
((System.ComponentModel.ISupportInitialize)(this.eventLog1)).BeginInit();
this.SuspendLayout();
//
// eventLog1
//
this.eventLog1.MachineName = System.Environment.MachineName;
this.eventLog1.SynchronizingObject = this;
this.eventLog1.EntryWritten += new System.Diagnostics.EntryWrittenEventHandler(this.eventLog1_EntryWritten);
//
// btnListLog
//
this.btnListLog.Location = new System.Drawing.Point(32, 16);
this.btnListLog.Name = "btnListLog";
this.btnListLog.Size = new System.Drawing.Size(152, 23);
this.btnListLog.TabIndex = 0;
this.btnListLog.Text = "List Event Logs";
this.btnListLog.Click += new System.EventHandler(this.btnListLog_Click);
//
// btnReadLog
//
this.btnReadLog.Location = new System.Drawing.Point(32, 46);
this.btnReadLog.Name = "btnReadLog";
this.btnReadLog.Size = new System.Drawing.Size(152, 23);
this.btnReadLog.TabIndex = 1;
this.btnReadLog.Text = "Read Event Logs";
this.btnReadLog.Click += new System.EventHandler(this.btnReadLog_Click);
//
// btnWriteLog
//
this.btnWriteLog.Location = new System.Drawing.Point(32, 77);
this.btnWriteLog.Name = "btnWriteLog";
this.btnWriteLog.Size = new System.Drawing.Size(152, 23);
this.btnWriteLog.TabIndex = 2;
this.btnWriteLog.Text = "Write Event Logs";
this.btnWriteLog.Click += new System.EventHandler(this.btnWriteLog_Click);
//
// btnClearLog
//
this.btnClearLog.Location = new System.Drawing.Point(32, 106);
this.btnClearLog.Name = "btnClearLog";
this.btnClearLog.Size = new System.Drawing.Size(152, 23);
this.btnClearLog.TabIndex = 3;
this.btnClearLog.Text = "Clear Logs";
this.btnClearLog.Click += new System.EventHandler(this.btnClearLog_Click);
//
// btnCreateLog
//
this.btnCreateLog.Location = new System.Drawing.Point(32, 137);
this.btnCreateLog.Name = "btnCreateLog";
this.btnCreateLog.Size = new System.Drawing.Size(152, 23);
this.btnCreateLog.TabIndex = 4;
this.btnCreateLog.Text = "Create Custom Logs";
this.btnCreateLog.Click += new System.EventHandler(this.btnCreateLog_Click);
//
// btnDeleteLog
//
this.btnDeleteLog.Location = new System.Drawing.Point(32, 168);
this.btnDeleteLog.Name = "btnDeleteLog";
this.btnDeleteLog.Size = new System.Drawing.Size(152, 23);
this.btnDeleteLog.TabIndex = 5;
this.btnDeleteLog.Text = "Delete Custom Logs";
this.btnDeleteLog.Click += new System.EventHandler(this.btnDeleteLog_Click);
//
// btnRecNotice
//
this.btnRecNotice.Location = new System.Drawing.Point(32, 199);
this.btnRecNotice.Name = "btnRecNotice";
this.btnRecNotice.Size = new System.Drawing.Size(152, 23);
this.btnRecNotice.TabIndex = 6;
this.btnRecNotice.Text = "Receive Event Notifications";
this.btnRecNotice.Click += new System.EventHandler(this.btnRecNotice_Click);
//
// Form1
//
this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
this.ClientSize = new System.Drawing.Size(216, 237);
this.Controls.Add(this.btnRecNotice);
this.Controls.Add(this.btnDeleteLog);
this.Controls.Add(this.btnCreateLog);
this.Controls.Add(this.btnClearLog);
this.Controls.Add(this.btnWriteLog);
this.Controls.Add(this.btnReadLog);
this.Controls.Add(this.btnListLog);
this.Name = "Form1";
this.Text = "Form1";
((System.ComponentModel.ISupportInitialize)(this.eventLog1)).EndInit();
this.ResumeLayout(false);
}
#endregion
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
Application.Run(new Form1());
}
private void btnListLog_Click(object sender, System.EventArgs e)
{
EventLog[] remoteEventLogs;
// Gets logs on the local computer, gives remote computer name to get the logs on the remote computer.
remoteEventLogs = EventLog.GetEventLogs(System.Environment.MachineName);
Console.WriteLine("Number of logs on computer: " + remoteEventLogs.Length);
for ( int i=0; i<remoteEventLogs.Length; i++ )
Console.WriteLine("Log: " + remoteEventLogs[i].Log);
}
private void btnReadLog_Click(object sender, System.EventArgs e)
{
//logType can be Application, Security, System or any other Custom Log.
string logType = "Application";
/* In this case the EventLog constructor is passed a string variable for the log name and
* second argument mention the computer name that you want to read the logs from,
* and that you have appropriate permissions to*/
EventLog ev = new EventLog(logType, System.Environment.MachineName);
int LastLogToShow = ev.Entries.Count;
if ( LastLogToShow <= 0 )
Console.WriteLine("No Event Logs in the Log :" + logType);
// Read the last 2 record in the specified log.
int i;
for ( i = ev.Entries.Count - 1; i>= LastLogToShow - 2; i--)
{
EventLogEntry CurrentEntry = ev.Entries[i];
Console.WriteLine("Event ID : " + CurrentEntry.EventID);
Console.WriteLine("Entry Type : " + CurrentEntry.EntryType.ToString());
Console.WriteLine("Message : " + CurrentEntry.Message + "\n");
}
ev.Close();
/* Similarly you can loop through all the entries in the log using
* the entries collection as shown in the following commented code.
* For Each entry In ev.Entries */
}
private void btnWriteLog_Click(object sender, System.EventArgs e)
{
/* When writing to an event log, pass the computer name where
* the log resides. Here the MachineName Property of the Environment class
* is used to determine the name of the local computer. Assuming that you have
* the appropriate permissions, it is also easy to write to event logs on
* other computers.*/
//See if the Source exists.
if ( ! ( EventLog.SourceExists("MySystemSource", System.Environment.MachineName)))
EventLog.CreateEventSource("MySystemSource", "System", System.Environment.MachineName);
EventLog ev = new EventLog("System", System.Environment.MachineName, "MySystemSource");
/* Writing to system log, in the similar way you can write to other
* logs that you have appropriate permissions to write to
*/
ev.WriteEntry("Warning is written to system Log", EventLogEntryType.Warning, 10001);
MessageBox.Show("Warning is written to System Log");
ev.Close();
}
private void btnClearLog_Click(object sender, System.EventArgs e)
{
//Create an EventLog instance, and pass log name and MachineName where the log resides.
EventLog ev = new EventLog("Security", System.Environment.MachineName);
ev.Clear();
ev.Close();
}
private void btnCreateLog_Click(object sender, System.EventArgs e)
{
// Create the source, if it does not already exist.
if (! (EventLog.SourceExists("MyOldSource", System.Environment.MachineName)))
// Creating a new log
EventLog.CreateEventSource("MyOldSource", "MyNewLog", System.Environment.MachineName);
Console.WriteLine("CreatingEventSource");
}
private void btnDeleteLog_Click(object sender, System.EventArgs e)
{
string logName = "MyNewLog";
if ( EventLog.SourceExists("MyOldSource", System.Environment.MachineName))
{
logName = EventLog.LogNameFromSourceName("MyOldSource", System.Environment.MachineName);
EventLog.DeleteEventSource("MyOldSource", System.Environment.MachineName);
EventLog.Delete(logName, System.Environment.MachineName);
Console.WriteLine(logName + " deleted.");
}
}
private void btnRecNotice_Click(object sender, System.EventArgs e)
{
// Create the source, if it does not already exist.
if (EventLog.SourceExists("MySource", System.Environment.MachineName) == false)
{
EventLog.CreateEventSource("MySource", "Application", System.Environment.MachineName);
Console.WriteLine("CreatingEventSource");
}
eventLog1.Log = "Application";
//Enable EnableRaisingEvents to true
eventLog1.EnableRaisingEvents = true;
EventLog.WriteEntry("MySource", "EntryWritten event is fired", EventLogEntryType.Information);
}
private void eventLog1_EntryWritten(object sender, System.Diagnostics.EntryWrittenEventArgs e)
{
if (e.Entry.Source == "MySource")
Console.WriteLine("Entry written by my app. Message: " + e.Entry.Message);
}
}
}
Проверка результатов
Чтобы проверить результаты, выполните следующие действия:
- В Microsoft Visual Studio.NET или в Microsoft Visual Studio 2005 создайте новый Visual C#
.NET или приложения Windows Visual C# 2005 проекта. По умолчанию создается файл Form1.vb.
- Замените код в файл Form1.vb, указанный код
в разделе «Полный листинг кода» данной статьи.
- На Отладка меню, нажмите кнопкуНачало для запуска приложения.
- Выполните различные действия в форме.
- На Представление меню, нажмите кнопку Сервер
Проводник для проверки результатов.
- Разверните узел Серверы, а затем разверните узелИмя компьютера.
- Разверните имя компьютера События
Журналы.
Примечание В Серверы не является узлом из обозревателя серверов
доступные в академический выпуск Visual C#.NET. В таких случаях можно использовать
Средство просмотра событий Windows для просмотра результатов выполнения приложения. - Проверьте обозреватель серверов, чтобы убедиться, что все задачи
выполнена правильно.
Код статьи: 815314 - Последнее изменение :: 14 июня 2011 г. - Редакция: 5.0
Информация в данной статье относится к следующим продуктам.
- Microsoft Visual C# .NET 2002 Standard Edition
- Microsoft Visual C# .NET 2003 Standard Edition
- Microsoft Visual C# 2005 Express Edition
| kbeventservice kbnetwork kbmanaged kbprogramming kbhowtomaster kbeventlog kbhowto kbmt KB815314 KbMtru |
Переведено с помощью машинного переводаВНИМАНИЕ! Перевод данной статьи был выполнен не человеком, а с помощью программы машинного перевода, разработанной корпорацией Майкрософт. Корпорация Майкрософт предлагает вам статьи, переведенные как людьми, так и средствами машинного перевода, чтобы у вас была возможность ознакомиться со статьями базы знаний KB на родном языке. Однако машинный перевод не всегда идеален. Он может содержать смысловые, синтаксические и грамматические ошибки, подобно тому как иностранец делает ошибки, пытаясь говорить на вашем языке. Корпорация Майкрософт не несет ответственности за неточности, ошибки и возможный ущерб, причиненный в результате неправильного перевода или его использования. Корпорация Майкрософт также часто обновляет средства машинного перевода.
Эта статья на английском языке:
815314
(http://support.microsoft.com/kb/815314/en-us/
)