Windows service logging events

Практическое руководство. Запись сведений о службах в журнал How to: Log Information About Services

По умолчанию все проекты служб Windows могут взаимодействовать с журналом событий приложения и записывать в него сведения и исключения. By default, all Windows Service projects have the ability to interact with the Application event log and write information and exceptions to it. Чтобы указать, что эта функциональность должна быть в вашем приложении, можно использовать свойство AutoLog . You use the AutoLog property to indicate whether you want this functionality in your application. По умолчанию ведение журнала включено для любой службы, созданной с помощью шаблона проекта службы Windows. By default, logging is turned on for any service you create with the Windows Service project template. Можно использовать статическую форму класса EventLog для записи сведений в журнал, и тогда не потребуется создавать экземпляр компонента EventLog или вручную регистрировать источник. You can use a static form of the EventLog class to write service information to a log without having to create an instance of an EventLog component or manually register a source.

Установщик службы автоматически регистрирует каждую службу в проекте как допустимый источник событий для журнала приложений на компьютере, где установлена служба, если включено ведение журнала. The installer for your service automatically registers each service in your project as a valid source of events with the Application log on the computer where the service is installed, when logging is turned on. Служба записывает сведения каждый раз, когда служба запускается, останавливается, приостанавливается, возобновляется, устанавливается или удаляется. The service logs information each time the service is started, stopped, paused, resumed, installed, or uninstalled. Она также записывает все возникающие ошибки. It also logs any failures that occur. Вам не нужно писать никакой код для записи в журнал при использовании этого поведения по умолчанию; служба обрабатывает это автоматически. You do not need to write any code to write entries to the log when using the default behavior; the service handles this for you automatically.

Если вы хотите выполнять запись в другой журнал событий, отличный от журнала приложения, то необходимо задать для свойства AutoLog значение false , создать собственный пользовательский журнал событий в коде службы и зарегистрировать службу в качестве источника записей для этого журнала. If you want to write to an event log other than the Application log, you must set the AutoLog property to false , create your own custom event log within your services code, and register your service as a valid source of entries for that log. Затем вам придется написать код для выполнения записи в журнал всякий раз, когда происходит интересующее вас действие. You must then write code to record entries to the log whenever an action you’re interested in occurs.

Если вы используете пользовательский журнал событий и настроили службу для записи в этот журнал, не пытайтесь обратиться к этому журналу до установки свойства ServiceName службы в коде. If you use a custom event log and configure your service application to write to it, you must not attempt to access the event log before setting the service’s ServiceName property in your code. Журналу событий нужно значение этого свойства, чтобы зарегистрировать службу в качестве допустимого источника событий. The event log needs this property’s value to register your service as a valid source of events.

Читайте также:  Драйвер amd radeon hd 5700 series для windows 10 64 bit

Включение ведения журнала событий по умолчанию для службы To enable default event logging for your service

Установите для свойства AutoLog вашего компонента значение true . Set the AutoLog property for your component to true .

По умолчанию для свойства задано значение true . By default, this property is set to true . Вам не нужно задавать это явно, если только вы не создаете более сложную обработку, такую как оценка условия и последующая установка свойства AutoLog в зависимости от результата этого условия. You do not need to set this explicitly unless you are building more complex processing, such as evaluating a condition and then setting the AutoLog property based on the result of that condition.

Отключение ведения журнала событий для службы To disable event logging for your service

Установите для свойства AutoLog вашего компонента значение false . Set the AutoLog property for your component to false .

Настройка ведения пользовательского журнала To set up logging to a custom log

Задайте для свойства AutoLog значение false . Set the AutoLog property to false .

Чтобы использовать пользовательский журнал, необходимо задать в свойстве AutoLog значение false. You must set AutoLog to false in order to use a custom log.

Настройте экземпляр компонента EventLog в приложении службы Windows. Set up an instance of an EventLog component in your Windows Service application.

Создайте пользовательский журнал, вызвав метод CreateEventSource и задав исходную строку и имя файла журнала, который хотите создать. Create a custom log by calling the CreateEventSource method and specifying the source string and the name of the log file you want to create.

Укажите в свойстве Source компонента EventLog исходную строку, созданную на шаге 3. Set the Source property on the EventLog component instance to the source string you created in step 3.

Выполняйте запись в журнал, вызывая метод WriteEntry в экземпляре компонента EventLog . Write your entries by accessing the WriteEntry method on the EventLog component instance.

Следующий код показывает, как настроить ведение пользовательского журнала. The following code shows how to set up logging to a custom log.

В этом примере кода экземпляр компонента EventLog называется eventLog1 ( EventLog1 в Visual Basic). In this code example, an instance of an EventLog component is named eventLog1 ( EventLog1 in Visual Basic). Если на шаге 2 вы создали экземпляр с другим именем, измените код соответствующим образом. If you created an instance with another name in step 2, change the code accordingly.

Event Logging (Windows Installer)

Windows Events provides a standard, centralized way for applications (and the operating system) to record important software and hardware events. The event-logging service stores events from various sources in a single collection called an event log. Prior to WindowsВ Vista, you would use either Event Tracing for Windows (ETW) or Event Logging to log events. WindowsВ Vista introduced a new eventing model that unifies both ETW and the Windows Event Log API.

The installer also writes entries into the event log. These record events such as following:

  • Success or failure of the installation; removal or repair of a product.
  • Errors that occur during product configuration.
  • Detection of corrupted configuration data.

If a large amount of information is written, the Event Log file can become full and the installer displays the message, «The Application log file is full.»

Читайте также:  Кортана windows 10 что это как отключить

The installer may write the following entries in the event log. All event log messages have a unique event ID. All general errors authored in the Error table that are returned for an installation that fails are logged in the Application Event Log with a message ID equal to the Error + 10,000. For example, the error number in the Error table for an installation completed successfully is 1707. The successful installation is logged in the Application Event Log with a message ID of 11707 (1707 + 10,000).

For information about how to enable verbose logging on a user’s computer when troubleshooting deployment, see Windows Installer Best Practices.

Windows Event Log Service not starting or is unavailable

Windows Event Log service maintains a set of event logs that the system, system components, and applications use to record events. The service exposes functions that allow programs to maintain and manage the event logs and perform operations on the logs, such as archiving and clearing. As such, administrators can maintain event logs and perform administrative tasks requiring administrator privileges.

Windows Event Log Service Not Starting or Running

For some unknown reason, if you find you are having difficulty starting the following, it is quite possible that one of the reasons could be that Windows Event Log Service is Not Running.

  • Task Scheduler
  • Windows Event Calendar
  • Messenger Sharing Folders

In such a scenario, you may get error messages like:

Event Log service is unavailable. Verify that the service is running

Windows could not start the Windows Event Log service on Local Computer

First, reboot your system and see if it helps. Sometimes a simple restart helps reinitialize this service. If the Windows Event Log shows as being started, re-start it from Services Manager.

To check if the Windows Event Log service is started or stopped, Run services.msc and hit Enter to open the Services Manager. Here, again right-click on Windows Event Log Service, check up its Properties.

Ensure that the Startup type is set on Automatic and that the services is Started; and that it runs in the Local Service account.

Also ensure in the Recovery tab, all three drop-down boxes, show the option as ‘Restart the Service’, in case of Failure. Reboot if required.

At times the Windows Event Log Service still will not start, and you may instead get the following error message:

System cannot find the file specified

In this case, open the following folder:

This logs folder contains Event Logs in .evtx format and can only be read with the Event Viewer. Give this logs folder Read-Write access rights and see if it helps.

You might also want to do the following.

Open Registry Editor and navigate to the following key:

Double-click ObjectName and ensure that its value is set at NT AUTHORITY\LocalService. If it is not, then change it.

If it still does not help, run the System File Checker and go through its logs.

How to: Log Information About Services

By default, all Windows Service projects have the ability to interact with the Application event log and write information and exceptions to it. You use the AutoLog property to indicate whether you want this functionality in your application. By default, logging is turned on for any service you create with the Windows Service project template. You can use a static form of the EventLog class to write service information to a log without having to create an instance of an EventLog component or manually register a source.

The installer for your service automatically registers each service in your project as a valid source of events with the Application log on the computer where the service is installed, when logging is turned on. The service logs information each time the service is started, stopped, paused, resumed, installed, or uninstalled. It also logs any failures that occur. You do not need to write any code to write entries to the log when using the default behavior; the service handles this for you automatically.

Читайте также:  Linux для планшета x86

If you want to write to an event log other than the Application log, you must set the AutoLog property to false , create your own custom event log within your services code, and register your service as a valid source of entries for that log. You must then write code to record entries to the log whenever an action you’re interested in occurs.

If you use a custom event log and configure your service application to write to it, you must not attempt to access the event log before setting the service’s ServiceName property in your code. The event log needs this property’s value to register your service as a valid source of events.

To enable default event logging for your service

Set the AutoLog property for your component to true .

By default, this property is set to true . You do not need to set this explicitly unless you are building more complex processing, such as evaluating a condition and then setting the AutoLog property based on the result of that condition.

To disable event logging for your service

Set the AutoLog property for your component to false .

To set up logging to a custom log

Set the AutoLog property to false .

You must set AutoLog to false in order to use a custom log.

Set up an instance of an EventLog component in your Windows Service application.

Create a custom log by calling the CreateEventSource method and specifying the source string and the name of the log file you want to create.

Set the Source property on the EventLog component instance to the source string you created in step 3.

Write your entries by accessing the WriteEntry method on the EventLog component instance.

The following code shows how to set up logging to a custom log.

In this code example, an instance of an EventLog component is named eventLog1 ( EventLog1 in Visual Basic). If you created an instance with another name in step 2, change the code accordingly.

Are there any log file about Windows Services Status?

I want to figure out when the services was start up and terminated. Are there any kind log file about it?

4 Answers 4

Take a look at the System log in Windows EventViewer ( eventvwr from the command line).
You should see entries with source as ‘Service Control Manager’. e.g. on my WinXP machine,

Under Windows 7, open the Event Viewer. You can do this the way Gishu suggested for XP, typing eventvwr from the command line, or by opening the Control Panel, selecting System and Security, then Administrative Tools and finally Event Viewer. It may require UAC approval or an admin password.

In the left pane, expand Windows Logs and then System. You can filter the logs with Filter Current Log. from the Actions pane on the right and selecting «Service Control Manager.» Or, depending on why you want this information, you might just need to look through the Error entries.

The actual log entry pane (not shown) is pretty user-friendly and self-explanatory. You’ll be looking for messages like the following:

«The Praxco Assistant service entered the stopped state.»
«The Windows Image Acquisition (WIA) service entered the running state.»
«The MySQL service terminated unexpectedly. It has done this 3 time(s).»

Оцените статью