Windows event log xml

Putting XML Data into the Windows Event Log

How can I write XML data into the Windows Event Log?

I have noticed that there is a way to insert XML into the windows event log (and not by just stuffing it into the description). The effect is that you get just your description message in the General view on Windows Vista. You can see your XML data in the Details view.

If you select the Friendly radio button, it appears under the Event Data node. If you select the XML view, then you get to see the XML.

I thought that the rawData byte array in the EventLog.WriteEntry() method would allow me to do this. I tried stuffing the output of XMLWriter into it. That put data into the event log, but it is viewed as binary instead of XML.

2 Answers 2

Unless I am mistaken, in order to write xml to the Crimson/Vista event log you will have create and register a manifest that will give you the appropriate channels and events. Then you have to compile the manifest using the Message Compiler (mc.exe) in the WindowsSDK.

Then if you want to log from C# you will want to create a managed provider to wrap the event logging API. This is a little harder because you will have to use PInvoke to get at the API.

There are blog posts on how to do this whole process here.

You have a sample in Windows SDK (ver 6.1) called EventProvider.
Its a C# provider (needs Vista and up to work) that uses the new Event log API (AKA crimson).
This sample show how to add custom data (amount other things).

Фильтрация событий в журналах Windows по имени пользователя

В Windows Server 2003 / Windows XP в журнале событий системы можно было с легкостью отфильтровать события по учетной записи конкретного пользователя, указав в фильтре в поле User фильтра журнала имя нужной учетной записи. Но в Windows Server 2008 / Windows 7 и выше этот простой способ найти события, связанные с конкретным пользователем, не работает, хотя в настройках фильтра само поле User имеется (видимо осталось по-старинке).

В Windows Server 2008 в стандартном виде журнала событий отсутствует поле User. Попробуем добавить его с помощью меню View -> Add/Remove Columns.

Теперь в представлении журнала появился столбец User, но имени пользователя, инициатора события в этом столбце нет, вместо этого отображается N/A. Иформация об учетной записи теперь содержится внутри описания самого события ( в значениях атрибутов Security ID и Account Name в данном примере). Как же теперь можно отфильтровать события в журнале? Для фильтрации событий по имени учетной записи пользователя ( и любым другим атрибутам событий), в Windows Server 2008 (и выше) можно воспользоваться возможность ручной модификации XML запросов (XPath) на выборку.

Итак, откройте нужный журнал в Event View (в нашем примере это журнал Security) и в контекстном меню выберите пункт Filter Current Log….

Перейдите на вкладку XML и отметьте чекбокс Edit query manually.

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

Сохраняем изменения в фильтре и смотрим на журнал. В нем должны остаться события, относящиеся к данной учетке.


Если, к примеру, нужно дополнительно отфильтровать события по пользователю и Event ID 4624 (Удачный вход — An account was successfully logged on) и 4625 (неудачный вход — An account failed to log on.), фильтр XPath может выглядеть так:

Читайте также:  Set java home windows 10 from cmd

Windows event log xml

This forum is closed. Thank you for your contributions.

Answered by:

Question

I’m trying to filter the creation and deletion of an AD OU object

This is the XML code of the event:

4662
0
0
14080
0
0x8020000000000000

924274805

Security
WSDC12.MYDOMAIN.local


S-1-5-21-1987142990-190398333-4244032772-14478
adminuser
MYDOMAIN
0x2b8e408d
DS
%
% <976c46f5-2d50-40f7-a435-4a2a27ab0f50>
Object Access
0x0
%%7680
0x1
%%7680
ou=TTTTTTTTTT,ou=QQQQQQQQQQ,OU=XTESTX,OU=test,DC=mydomain,DC=local
% <58650b59-da2e-425f-b667-7085185b522d>

It should be pretty straight forward, but unfortunately «and *[EventData[Data[@Name =’AccessList’] and (Data=’%%7680‘)]]» does NOT work, and does not return anything; if I remove it, I got almost what I want but I really would like to filter only %%7680

I believe the %% is causing issue, but cannot find the fix

bf967aa5-0de6-11d0-a285-00aa003049e2 is the Schema-GUID for an organizational unit
%%7680 translate to «Create Child»

Answers

The answer is here:

All replies

YOu need to use an XPath expression to match a field in the Data.

It would be someting like //Data[@Name=’AccessList’) and text()=’%%7680′)]

My Query looks like this now, but still doesn’t work

The query seems to be valid but I cannot find any reference to text= for eventlog filtering, it seems that the key word to use is Data=

You won’t find an yXPath in teh eventlog documents other thatn to say that we use XPAth queries that return a single value.

It is not «text» it is an XPath function that returns the text node value whch you are trying to query for a match in value.

You lost teh parens.

Jrv, sorry I forgot to mention that text()= ‘%%7680’ errors out

Either they don’t support that syntax or something else.

This XPAth works on that XML.

//EventData/Data[@Name=’AccessList’ and text()=’%%7680′]

HOw to translate that into EventLog query syntaxx which is a shorthand. Maybe it is an XQuery extension?

/Event/EventData/Data[@Name=’AccessList’ and text()=’%%7680′]

This is also possible

JRV, I’ve tried everything you mentionned, and some other variant without success, but unfortunately I’ve read the XPATH implementation for Eventlog has limitation

XPath 1.0 limitations

I’m not sure about the issue here, it could be possible that Accesslist is not queryable, or the %% is causing issue.

Is there an espace character in XPATH ? I have tried \ / and

This works for me. As you can see it is one off from what I was assuming.

*[EventData[Data[@Name=’AccessList’] and Data=’%%7680′]]

We have two separate ‘wherw’ clauses that are grouped hierarchically. First we want to say «give me the nodes that have the name ‘AccessList’ then search those nodes for the matching value. Not really intuitive but it works.

Yes we only get XPAth 1.0 with limitations and Microsoft’s own variations on the syntax too. XPath common syntax would have been better but.

The damn use of the colorizing HTML control is a pain in the neck. If you copy from a web page it will retain the style and corrupt the XML. MS must have sent the junior programming team from Tierra Del Fuego to build that one.

I did a bit of testing. That is XPAth 1.0 syntax with no MS changes.

Here is the full XPATH:

$xml.SelectNodes(«//*[EventData[Data[@Name=’AccessList’] and Data=’%%7680′]]»)

I can exract the XML version of teh eevntlog and use the exact same query. My earlier version would bemore efficient I believe but this works.

Читайте также:  Labtec webcam 2200 драйвер windows

WIth the EventLog we get the * but not the root specifier because that is assumed. To use the query in PowerShell XML we just preface the query with the // for the ‘start at the root’ and process every node.

Mine is //Event/EventData[.

This say start at the root but onle process against nodes that are Event/EventData. Using a keyed index would make this much faster.

So the MS path says. Give me all nodes where the element is an EventData where the child element is a Data and the value is %%7680

I’ve tried both of the query below, the first one doesn’t return anything, the second returns The specified query is invalid 🙁

I’ve tried both of the query below, the first one doesn’t return anything, the second returns The specified query is invalid 🙁

Sorry Cyreli — yu can’t just hang it outin space like that or it will be irellevent.

That does not throw any syntax errors and will return the expected results.

Just to make sure, what I’m trying to do is to create a Custom View in the Event Viewer of Windows 2008R2

I pasted the following into the XML designer of the Event Log Custom View designer.

It works exactly as designed to work with no error.

Just copy it and paste all of it into the XML designer window.

If you get an error then you are pasting in something wrong.

Still doesn’t work. I do not know what to think !

Here is the full XML code

I have tried to filter with every arribute in the list above, they all work except AccessList and Properties, the only thing they have in common is the %%

That is not a query itis an event records XML.

I know that, this is just to give you more info.

Quoting myself » I have tried to filter with every attribute in the list above, they all work except AccessList and Properties, the only thing they have in common is the %% «

Try it this way — we will encode the percent signs in the query,

Well it all seems to work for me so I am lost as to what your issue is.

I was very hopeful I was when I saw your last post with the «%%» I really thought that was it.

So I copy/paste your query in the eventlog, and what a disappointment, when I ran the query, nothing was returned, and when I went back to the Query Editor and the «%%» where replaced by «%%» 🙁

Anyway thank you for not giving up on this one

This exact syntax works evenwith compound statements. You have to be absolutely careful of the form.

While other versions work with XML this is the only one that works consistently witk teh XPAth 1 .0 that is being used by the Eveent Log.

A test can be made by just using one element:

*[EventData[Data[@Name=’ChangeType’] and Data=’%%16385′]]

This will return all events with a ChangeType field that contains ‘%%16385’ . Substitute your value and try it to see that it works.

Be careful to nte where the braces fall. If they are not grouped correctly the filter will compile but it will return nothing. A syntax error wil lindicate that you have copied this incorrectly.

You cannot paste from a web page into the filter editor or you might end up with a corrupt filter. Paste into notepad first then copy and paste into the filter editor.

Читайте также:  Процент пользователей линукс 2021

The Eventlog XPah supports at least one alternate form:

*/EventData/Data[@Name=’ChangeType’]=’%%16385′

This drops the ‘and’ and the node specifier and just does a compound ‘=’. This form may be more readable,

Just add ‘and’ and ‘or’ to chain the logic.

A note about Eventlog extractions. You can dump the eventlog to XML and then use XPath too query the file. This works very well in PowerShell and allows us to use full XPath 2.0 syntaxes. It also allows us to do the string substitution so we can query by name rather than substitution index (%%12345 is an index into the Provider help file).

I believe I found something very interesting. I’ve copy/paste your query, and modified it in Notepad. See below

Sorry — I doin’t have any event log entries with those elements on my test system.

I see no reaon for the one not working except that yu may have gotten garbage into the query editor somehow.

Be sure to copy an dpaste only from notepad or illegal characters can screw up you query text.

I’ve done this I believe now more than 50 times. As mentioned before I copied paste your query 3 times, in 3 custom filters, and just modified what was necessary. 2 out of 3 works ! So no typo possible.

Seems to be a bug for me so far.

If you want to test this on your system, you will need a Windows 2008R2 with audit enable, and create a OU, that will trigger an eventid 4662, with an AccessList = %%7680

Mo — you need to paste it into notepad first then copy it fro notepad and paste into the EL CML edit box. If you don’t do this illegal cahracters can be pasted from the web copy. You willnot see them but they will be there. They can alter any string. The%% is very likely to get decorated with invisible junk. Notepad does not support these caharacters and will strip them. The dit box is an HTML comtrol so it wil lmaintain the HTML.

Try this. Copy the foillowing line and paste into the edit box then paste it into notepad. (Yes bcakwards to show the error)

Some text — BOLD TEXT — regular text.

You should see that the text remains bolded in teh edit box but not in notepad. The HTML that set teh bold styles can getr included in your query and it will not be visible. The tags are not part of teh QueryList schema and will be invisible in the editor but can still be there. Once the tags are included the query will behave oddly. It took me many tries to realize that this was part of the probelem with teh queries.

This thread should be moved to the Server Platform forum as it really has nothing to do with scripting. I just pursued it because the same XML queries can be used in PowerShell and the XPath for this would be helpful to some scripters.

If ytou have specific issues with a prticular query I recommend taking that one query to the System Management FOrum and letting the SM people try to reproduce you issue more completely. You might finsd someone with a test system that has the events that you are having an issue with.

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