Write to Windows Application Event Log Without Event Source Registration

Write to Windows Application Event Log without event source registration

Yes, there is a way to write to the event log you are looking for. You don't need to create a new source, just simply use the existent one, which often has the same name as the EventLog's name and also, in some cases like the event log Application, can be accessible without administrative privileges*.

*Other cases, where you cannot access it directly, are the Security EventLog, for example, which is only accessed by the operating system.

I used this code to write directly to the event log Application:

using (EventLog eventLog = new EventLog("Application")) 
{
eventLog.Source = "Application";
eventLog.WriteEntry("Log message example", EventLogEntryType.Information, 101, 1);
}

As you can see, the EventLog source is the same as the EventLog's name. The reason of this can be found in Event Sources @ Windows Dev Center (I bolded the part which refers to source name):

Each log in the Eventlog key contains subkeys called event sources. The event source is the name of the software that logs the event. It is often the name of the application or the name of a subcomponent of the application if the application is large. You can add a maximum of 16,384 event sources to the registry.

Write to Application log without creating a source

You cannot write without registering event source and you need administrative rights to create one. If you have administrative rights and write a log without first creating source Windows creates the event source automatically.

From MSDN:

Use WriteEvent and WriteEntry to write events to an event log. You must specify an event source to write events; you must create and configure the event source before writing the first entry with the source.

Create the new event source during the installation of your application. This allows time for the operating system to refresh its list of registered event sources and their configuration. If the operating system has not refreshed its list of event sources, and you attempt to write an event with the new source, the write operation will fail. You can configure a new source using an EventLogInstaller, or using the CreateEventSource method. You must have administrative rights on the computer to create a new event source.

EventLog.Source Property

How to write Windows Event log records with non-existing source

OK, finally I found it (also, got the sources) - the prog creates the registry entry (probably happens when calling CreateEventSource()), it was just not visible until refreshing regedit :-|

And, it DOES register a formatting lib, only that it is something I cannot rely on: C:\Windows\Microsoft.NET\Framework64\v2.0.50727\EventLogMessages.dll

Or, can I?

Ah, here we go for an explanation:
Difference between EventLog.WriteEntry and EventLog.WriteEvent methods
So, I cannot, as I'm not using .Net ... :-|

Now, if I NOW send another event from MY prog (with the same, newly created source, as the foreign prog), I see it in the event viewer normally.
That means, WriteEntry() actually does not write a different/special type of evt log record containing the text directly (contrary to the standard method of writing just a msg catalog ID + params) but rather there must be some trick in the formatting lib to make the EventViewer apply some kind of "default" formatting.

Any ideas how I could accomplish this? Except just copying the EventLogMessages.dll above? :-)

OK, finally found an answer about this one in http://msdn.microsoft.com/en-us/magazine/cc163446.aspx
"This file is called EventLogMessages.dll, and it contains 65,536 event descriptions, each of which consists of the string "%1", a placeholder for whatever string you want to write"

I was hoping for something like "messageid=*" but that seems to be too simple :-|

But maybe somebody else is interested in whats happening here ...

How should I write to EventLog

You need Administrator access to create a custom event log source, and NETWORK SERVICE doesn't have that access. You will need to update your installer to create that log source, then the installer will have to be run as Administrator.

how can I writing windows log event with event source

You are receiving that error because you are not adding the event source to the Windows Registry.

Check the MSDN Documentation :

You can use the default Application log without adding an event source to the registry. However, Event Viewer will not be able to map your event identifier codes to message strings unless you register your event source and provide a message file.

The same link contains a sample with a C++ Code , which can be easily translated to Delphi.

UPDATE

I just found this article Writing an event logger with Delphi 2010 which shows how add an event source to the registry and write to the event log.

EventSource doesn't write logs in windows event viewer

You need some more steps to get this working. First of all, you need to set the Channel property of the Event attribute like this:

[EventSource(Name = "Samples-EventSourceDemos-EventLog")]
public sealed class MinimalEventSource : EventSource
{
public static MinimalEventSource Log = new MinimalEventSource();
[NonEvent]
public void WriteLog(Exception exception)
{
UnhandledException(exception.Message);
}

[Event(601, Channel = EventChannel.Admin, Message = "Unhandled exception occurred. Details: {0}", Keywords = EventKeywords.None, Level = EventLevel.Critical)]
private void UnhandledException(string exceptionMsg)
{
this.IsEnabled().Dump();
this.WriteEvent(601, exceptionMsg);
}
}

The, second, your EventSource need to be registered. The steps are outline here:

One requirement introduced by channel support is the need to statically register the ETW provider manifest. The NuGet package supports generating the files needed for static registration as part of your build. After your build completes a new step is run that generates a pair of files for each of the event source types defined in the project:
..etwManifest.man and
..etwManifest.dll

The first file contains the ETW manifest while the second one contains the binary form of the ETW manifest plus any needed native resources (localization string tables in particular).

The tool that generates the above two files is “eventRegister.exe” and it performs two functions:
It ensures the registration files are generated for all event source types that need static registration, and
It performs a number of validation checks on all the event source types defined in the output assembly.
Deploying your component will need to include these files and perform one registration step at installation time and one un-registration step at un-installation time.

Registration:

wevtutil.exe im <EtwManifestManFile> /rf:"<EtwManifestDllFullPathName>" /mf:"<EtwManifestDllFullPathName>"

Unregistration:

wevtutil.exe um <EtwManifestManFile>

For static registration eventRegister.exe generates manifests that include all localization information. This is needed because the manifest is generated at build time, when there’s no information regarding the culture in which the final application will run.

Note you will see that in the .etwManfest.man file that the build generated, there are path names for the resource file and manifest file in this file. They are the paths that existed at build time. These paths are NOT used if you use the /rf and /mf options. Thus you should always specify the /rf: and /mf options (unless you hand modify the .etwManifest.man file to specify deployment-time file paths for the DLL).
Finally, it is important that you use FULLY qualified names for the /mf: and /rf: options. You can use environment variables THAT ARE AVAILABLE TO ALL PROCESSes (e.g. %SystemRoot% or %ProgramFiles%), but you should not use relative paths (it is not clear what they are relative to, probably System32, but don’t count on it).
The general recommendation is to copy your etwManifest.dll and .etwManifest.man to a directory under %ProgramFiles% and then use wevtutil to register them at that location.

The easiest way to create the files described above is to add this NuGet Package as it will create those files when building your project. It comes with the docs in .docx format.

How to remove and create log in Windows Event Viewer

using System;
using System.Diagnostics;

...
...

public void WriteToEventLog(EventLogEntryType eventLogType, string message, string logSourceName)
{
if (!EventLog.SourceExists(logSourceName))
{
EventLog.CreateEventSource(logSourceName, "Application");
}
using (var eventLog = new EventLog { Source = logSourceName })
{
const int maxLength = 31000;
if (message.Length > maxLength)
{
message = message.Substring(0, maxLength);
}
eventLog.WriteEntry(message, eventLogType);
}
}

The user, under which account this app is going to run, needs to have access to be able to create logs.

Good luck.



Related Topics



Leave a reply



Submit