Log all windows messages

Windows Setup Log Files and Event Logs

Windows® Setup creates log files for all actions that occur during installation. If you are experiencing problems installing Windows, consult the log files to troubleshoot the installation.

WindowsВ Setup log files are available in the following directories:

Log location before Setup can access the drive.

Log location when Setup rolls back in the event of a fatal error.

Log location of Setup actions after disk configuration.

Used to log Plug and Play device installations.

Location of memory dump from bug checks.

Location of log minidumps from bug checks.

Location of Sysprep logs.

WindowsВ Setup Event Logs

WindowsВ Setup includes the ability to review the WindowsВ Setup performance events in the Windows Event Log viewer. This enables you to more easily review the actions that occurred during WindowsВ Setup and to review the performance statistics for different parts of WindowsВ Setup. You can filter the log so as to view only relevant items that you are interested in. The WindowsВ Setup performance events are saved into a log file that is named Setup.etl, which is available in the %WINDIR%\Panther directory of all installations. To view the logs, you must use the Event Viewer included with the Windows media that corresponds to the version of the customized image that you are building.

To view the logs on a computer that does not include the corresponding kit, you must run a script from the root of the media that installs the Event Trace for Windows (ETW) provider. From the command line, type:

where D is the drive letter of the Windows DVD media.

To view the WindowsВ Setup event logs

Start the Event Viewer, expand the Windows Logs node, and then click System.

In the Actions pane, click Open Saved Log and then locate the Setup.etl file. By default, this file is available in the %WINDIR%\Panther directory.

The log file contents appear in the Event Viewer.

To Export the log to a file

From the command line, use the Wevtutil or Tracerpt commands to save the log to an .xml or text file. For information about how to use these tools, see the command-line Help. The following commands show examples of how to use the tools:

Настройка ведения журналов сообщений Configuring Message Logging

В этом разделе описывается, как настроить ведение журнала сообщений для различных сценариев. This topic describes how you can configure message logging for different scenarios.

Включение ведения журнала сообщений Enabling Message Logging

Windows Communication Foundation (WCF) не регистрирует сообщения по умолчанию. Windows Communication Foundation (WCF) does not log messages by default. Чтобы включить ведение журнала сообщений, необходимо добавить прослушиватель трассировки в источник трассировки System.ServiceModel.MessageLogging и задать атрибуты элемента в файле конфигурации. To activate message logging, you must add a trace listener to the System.ServiceModel.MessageLogging trace source and set attributes for the element in the configuration file.

В следующем примере показано, как включить ведение журнала и указать дополнительные параметры. The following example shows how to enable logging and specify additional options.

Дополнительные сведения о параметрах ведения журнала сообщений см. в разделе Рекомендуемые параметры для трассировки и ведения журнала сообщений. For more information about message logging settings, see Recommended Settings for Tracing and Message Logging.

С помощью элемента add можно задать имя и тип прослушивателя, который требуется использовать. You can use add to specify the name and type of the listener you want to use. В данном примере прослушиватель с именем «messages» добавляет стандартный прослушиватель трассировки .NET Framework ( System.Diagnostics.XmlWriterTraceListener ) в качестве используемого типа. In the example configuration, the Listener is named «messages» and adds the standard .NET Framework trace listener ( System.Diagnostics.XmlWriterTraceListener ) as the type to use. Если используется прослушиватель System.Diagnostics.XmlWriterTraceListener , необходимо задать расположение выходного файла и имя файла конфигурации. If you use System.Diagnostics.XmlWriterTraceListener , you must specify the output file location and name in the configuration file. Для этого нужно присвоить свойству initializeData имя файла журнала. This is done by setting initializeData to the name of the log file. В противном случае система создает исключение. Otherwise, the system throws an exception. Кроме того, можно реализовать пользовательский прослушиватель, который выводит журналы в файл по умолчанию. You can also implement a custom listener that emits logs to a default file.

Поскольку для журнала сообщений требуется место на диске, необходимо ограничить число сообщений, записываемых на диск для конкретной службы. Because message logging accesses disk space, you should limit the number of messages that are written to disk for a particular service. Когда достигается максимальное число сообщений, создается трассировка на уровне информации, и все операции по ведению журнала сообщений останавливаются. When the message limit is reached, a trace at the Information level is produced and all message logging activities stop.

Уровень ведения журнала, а также дополнительные параметры, описаны в разделе Уровень и параметры ведения журнала. The logging level, as well as the additional options, are discussed in the Logging Level and Options section.

Действие атрибута switchValue элемента source распространяется только на трассировку. The switchValue attribute of a source is only valid for tracing. Если задать атрибут switchValue источника трассировки System.ServiceModel.MessageLogging , как показано ниже, это ни к чему не приведет. If you specify a switchValue attribute for the System.ServiceModel.MessageLogging trace source as follows, it has no effect.

Если требуется отключить источник трассировки, следует использовать атрибуты logMessagesAtServiceLevel , logMalformedMessages и logMessagesAtTransportLevel элемента messageLogging . If you want to disable the trace source, you should use the logMessagesAtServiceLevel , logMalformedMessages , and logMessagesAtTransportLevel attributes of the messageLogging element instead. Все эти атрибуты должны иметь значение false . You should set all these attributes to false . Для этого можно воспользоваться файлом конфигурации, приведенным в последнем примере кода, пользовательским интерфейсом редактора конфигурации или инструментарием WMI. This can be done by using the configuration file in the previous code example, through the Configuration Editor UI interface, or using WMI. Дополнительные сведения о средстве редактора конфигураций см. в разделе средство редактора конфигурации (SvcConfigEditor.exe). For more information about the Configuration Editor tool, see Configuration Editor Tool (SvcConfigEditor.exe). Дополнительные сведения об инструментарии WMI см. в разделе использование инструментарий управления Windows (WMI) для диагностики. For more information about WMI, see Using Windows Management Instrumentation for Diagnostics.

Уровни и параметры ведения журнала Logging Levels and Options

Для входящих сообщений регистрация в журнале осуществляется сразу после формирования сообщения, непосредственно перед попаданием сообщения в пользовательский код на уровне службы и при обнаружении неправильно сформированных сообщений. For incoming messages, logging happens immediately after the message is formed, immediately before the message gets to user code in the service level, and when malformed messages are detected.

Для исходящих сообщений регистрация в журнале осуществляется сразу после выхода сообщения из пользовательского кода и непосредственно перед отправкой сообщения по каналам связи. For outgoing messages, logging happens immediately after the message leaves user code and immediately before the message goes on the wire.

WCF регистрирует сообщения на двух разных уровнях: служба и транспорт. WCF logs messages at two different levels, service and transport. Также регистрируются неправильно сформированные сообщения. Malformed messages are also logged. Эти три категории журнала не зависят друг от друга и могут активироваться в конфигурации по отдельности. The three categories are independent from each other and can be activated separately in configuration.

Для управления уровнем ведения журнала необходимо задать атрибуты logMessagesAtServiceLevel , logMalformedMessages и logMessagesAtTransportLevel элемента messageLogging . You can control the logging level by setting the logMessagesAtServiceLevel , logMalformedMessages , and logMessagesAtTransportLevel attributes of the messageLogging element.

Уровень обслуживания Service Level

Сообщения, регистрируемые на этом уровне, готовы к входу (при получении) в пользовательский код или выходу (при отправке) из него. Messages logged at this layer are about to enter (on receiving) or leave (on sending) user code. Если определены фильтры, в журнал записываются только сообщения, соответствующие этим фильтрам. If filters have been defined, only messages that match the filters are logged. В противном случае в журнал записываются все сообщения на уровне службы. Otherwise, all messages at the service level are logged. На этом уровне также регистрируются сообщения инфраструктуры (транзакции, сообщения одноранговых каналов и безопасности), кроме сообщений системы надежного обмена сообщениями. Infrastructure messages (transactions, peer channel, and security) are also logged at this level, except for Reliable Messaging messages. Для потоковых сообщений в журнал заносятся только заголовки. On streamed messages, only the headers are logged. Защищенные сообщения регистрируются на этом уровне в расшифрованном виде. In addition, secure messages are logged decrypted at this level.

Уровень транспорта Transport Level

Сообщения, записываемые в журнал на этом уровне, готовы к кодированию или раскодированию для передачи по каналам связи или после нее. Messages logged at this layer are ready to be encoded or decoded for or after transportation on the wire. Если определены фильтры, в журнал записываются только сообщения, соответствующие этим фильтрам. If filters have been defined, only messages that match the filters are logged. В противном случае в журнал записываются все сообщения на уровне транспорта. Otherwise, all messages at the transport layer are logged. На этом уровне регистрируются все сообщения инфраструктуры, включая сообщения системы надежного обмена сообщениями. All infrastructure messages are logged at this layer, including reliable messaging messages. Для потоковых сообщений в журнал заносятся только заголовки. On streamed messages, only the headers are logged. Защищенные сообщения регистрируются на этом уровне в зашифрованном виде, если не используется защищенный транспорт, например протокол HTTPS. In addition, secure messages are logged as encrypted at this level, except if a secure transport such as HTTPS is used.

Уровень неправильно составленных сообщений Malformed Level

Неправильно сформированные сообщения — это сообщения, которые отклоняются стеком WCF на любом этапе обработки. Malformed messages are messages that are rejected by the WCF stack at any stage of processing. Сообщения неправильного формата записываются в журнал в исходном виде, зашифровываются с неправильным XML и т. д. Malformed messages are logged as-is: encrypted if they are so, with non-proper XML, and so on. Свойство maxSizeOfMessageToLog определяет размер сообщения, записываемого в журнал в виде CDATA. maxSizeOfMessageToLog defined the size of the message to be logged as CDATA. По умолчанию свойство maxSizeOfMessageToLog имеет значение 256 КБ. By default, maxSizeOfMessageToLog is equal to 256K. Дополнительные сведения об этом атрибуте см. в разделе другие параметры. For more information about this attribute, see the Other Options section.

Другие параметры Other Options

Помимо уровня ведения журнала можно задать следующие параметры. In addition to the logging levels, the user can specify the following options:

Записывать в журнал сообщение целиком (атрибут logEntireMessage ). Логическое значение, указывающее, записывается ли в журнал сообщение целиком (тело и заголовок сообщения). Log Entire Message ( logEntireMessage attribute): This value specifies whether the entire message (message header and body) is logged. Значением по умолчанию является false , означающее, что в журнал записывается только заголовок сообщения. The default value is false , meaning that only the header is logged. Действие этого параметра распространяется на уровни ведения журнала службы и транспорта. This setting affects service and transport message logging levels..

Максимальное число сообщений для внесения в журнал (атрибут maxMessagesToLog ). Значение, задающее максимальное количество сообщений для внесения в журнал. Max messages to log ( maxMessagesToLog attribute): This value specifies the maximum number of messages to log. Это значение относится ко всем сообщениям (службы, транспорта и неправильно сформированным сообщениям). All messages (service, transport, and malformed messages) are counted towards this quota. После достижения этого значения создается трассировка и новые сообщения в журнал не заносятся. When the quota is reached, a trace is emitted and no additional message is logged. Значение по умолчанию — 10 000. The default value is 10000.

Максимальный размер сообщения для внесения в журнал (атрибут maxSizeOfMessageToLog ). Значение, задающее максимальный размер сообщения для внесения в журнал в байтах. Max size of message to log ( maxSizeOfMessageToLog attribute): This value specifies the maximum size of messages to log in bytes. Сообщения, превышающие этот размер, в журнал не заносятся, и никакие другие действия с этими сообщениями не выполняются. Messages that exceed the size limit are not logged, and no other activity is performed for that message. Действие этого параметра распространяется на все уровни трассировки. This setting affects all trace levels. Если включена трассировка ServiceModel, в первой точке записи в журнал (ServiceModelSend* или TransportReceive) создается трассировка порога предупреждений для уведомления пользователя. If ServiceModel tracing is on, a Warning level trace is emitted at the first logging point (ServiceModelSend* or TransportReceive) to notify the user. Значение по умолчанию для сообщений уровня службы и транспорта составляет 256 КБ, а для сформированных сообщений неправильного формата — 4 КБ. The default value for service level and transport level messages is 256K, while the default value for malformed messages is 4K.

Размер сообщения, вычисляемый для сравнения со значением maxSizeOfMessageToLog , является размером сообщения в памяти до сериализации. The message size that is computed to compare against maxSizeOfMessageToLog is the message size in memory before serialization. Этот размер может отличаться от фактической длины строки сообщения, записываемой в журнал, и часто превышает фактический размер сообщения. This size can differ from the actual length of the message string that is being logged, and in many occasions is bigger than the actual size. Поэтому сообщение может быть не записано в журнал. As a result, messages may not be logged. Можно учесть этот факт, установив для атрибута maxSizeOfMessageToLog значение, на 10% превышающее ожидаемый размер сообщения. You can account for this fact by specifying the maxSizeOfMessageToLog attribute to be 10% larger than the expected message size. Кроме того, при внесении в журнал неправильно сформированного сообщения фактическое место на диске, занимаемое журналом сообщений, может до 5 раз превышать размер, задаваемый значением maxSizeOfMessageToLog . In addition, if malformed messages are logged, the actual disk space utilized by the message logs can be up to 5 times the size of the value specified by maxSizeOfMessageToLog .

Если в файле конфигурации не задан прослушиватель трассировки, в журнал ничего не записывается независимо от установленного уровня ведения журнала. If no trace listener is defined in the configuration file, no logging output is generated regardless of the specified logging level.

Параметры ведения журнала, например описанные в этом разделе атрибуты, можно изменить во время выполнения с помощью инструментария управления Windows (WMI). Message logging options, such as the attributes described in this section, can be changed at runtime using Windows Management Instrumentation (WMI). Это можно сделать, обратившись к экземпляру аппдомаининфо , который предоставляет эти логические свойства: LogMessagesAtServiceLevel , LogMessagesAtTransportLevel и LogMalformedMessages . This can be done by accessing the AppDomainInfo instance, which exposes these Boolean properties: LogMessagesAtServiceLevel , LogMessagesAtTransportLevel , and LogMalformedMessages . Поэтому, если в файле конфигурации прослушиватель трассировки настроен на ведение журнала, но эти параметры имеют значение false , можно впоследствии изменить их значения на true , когда приложение будет выполняться. Therefore, if you configure a trace listener for message logging, but set these options to false in configuration, you can later change them to true when the application is running. В результате ведение журнала будет включено во время выполнения. This effectively enables message logging at runtime. Аналогично, если ведение журнала было включено в файле конфигурации, его можно отключить во время выполнения с помощью инструментария WMI. Similarly, if you enable message logging in your configuration file, you can disable it at runtime using WMI. Дополнительные сведения см. в разделе использование инструментарий управления Windows (WMI) для диагностики. For more information, see Using Windows Management Instrumentation for Diagnostics.

Поле source в журнале сообщений определяет контекст, в котором регистрируется сообщение: отправка или получение сообщения с запросом, запрос-ответ или односторонний запрос, модель службы или транспортный уровень, либо сформированное сообщение неправильного формата. The source field in a message log specifies in which context the message is logged: when sending/receiving a request message, for a request-reply or 1-way request, at service model or transport layer, or in the case of a malformed message.

Для неверно сформированных сообщений source значение равно Malformed . For malformed messages, source is equal to Malformed . В противном случае поле source будет иметь следующие значения в зависимости от контекста. Otherwise, source has the following values based on the context.

Читайте также:  Windows 10 дополнительные параметры клавиатуры нет
Оцените статью
Log file location Description