none
How do I create an Event Log source under Vista?

    Question

  • In the Windows SDK documentation for the EventLog class, there is some sample code that contains the following code snippet:

            // Create the source, if it does not already exist.
            if(!EventLog.SourceExists("MySource")){
                EventLog.CreateEventSource("MySource", "MyNewLog");
                Console.WriteLine("CreatingEventSource");
            }

    However, when I build and run this sample code on the February CTP of Vista, I get a SecurityException on the call to EventLog.SourceExists. The error message says "The source was not found, but some or all event logs could not be searched. Inaccessible logs: Security." One of the troubleshooting tips in the unhandled exception dialog suggests using a certificate to obtain the required permission. Is that the best way around this problem? If so, is there some documentation on how to do this? How do I create the certificate? What permission(s) are needed to avoid the SecurityException? How do I tell the program to use the certificate to obtain the necessary permission(s)?

    Tom

    Wednesday, March 29, 2006 10:28 PM

Answers

  • Permissions for the Event log are driven through the registry. Each event log has an entry in the registry under the following key:
    HKEY_LOCAL_MACHINE\System\CurrentControlSet\Services\EventLog

    To allow the ASP.NET account access to create an event source, you need to have read permission on this and all sub keys, and write permission on the event to which you want to create the event source. Part of your error message says " Inaccessible logs: Security.". Note that "Virtual Server" seems to be another common inaccessible log. This means that for the Security log, the ASP.NET account (MachineName\ASPNET) does not have read access to that key.

    For reasons that I can't explain, the
    EventLog.CreateEventSource() method attempts to search Event Sources under all event logs, not just the event log for which you want to create the source. There are two solutions to this. The first, easiest, and most insecure, is just to give read/write access to all event logs for the ASP.NET account. To do this, follow these steps:
    1. Start -> Run -> regedit.exe
    2. Navigate to My Computer > HKEY_LOCAL_MACHINE\System\CurrentControlSet\Services\EventLog
    3. Right click this key, select Permissions, and grant the ASPNET account read/write permissions as described above. Note that for the "inaccessible" logs (ie. Security, Virtual Server), you'll also need to grant read access, as permissions have been set to not inherity from the parent key.
    4. Restart IIS (start -> Run  -> iisreset)
    5. Cause the code line that creates the event source to be executed (EventLog.CreateEventSource())
    I don't like this solution because it means that every time a new program that installs its own log (an hence premissions) is installed, the same problem will be encountered.

    The second solution is to bypass the use of the EventLog.CreateEventSource() code, and write your own Event Source addition code, by directly editing adding it to the registry (using code, not regedit!).

    Each event source appears as a key below the event log name. So an event source named "MediaManager" under the event log "Hoksoft" would appear as HKEY_LOCAL_MACHINE\System\CurrentControlSet\Services\EventLog\Hoksoft\MediaManager.

    An "Event Message File" contains resource strings which format your message content based on parameters. The default .NET message file, EventLogMessages.dll, simply has one parameter "%1", which means that your text is inserted as the message content in its entirity. For further reading on this topic, read http://www.codeproject.com/dotnet/evtvwr.asp. Anyway, to avoid message text similar to the following being displayed...

    The description for Event ID ( 0 ) in Source ( MediaManager ) cannot be found. The local computer may not have the necessary registry information or message DLL files to display messages from a remote computer. You may be able to use the /AUXSOURCE= flag to retrieve this description; see Help and Support for details. The following information is part of the event:

    ..., it's necessary to set the EventMessageFile parameter (registry string value) under the subkey for the Event Source. The default location of this file is in the following directory:  c:\WINNT\Microsoft.NET\Framework\v2.0.50727\, where v2.0.50727 is the version of the framework you are using (starting with v1.1.x).

    The following partial snippet of code should contain enough detail to dynamically create the event log source, without requiring access to other event logs. To use this code snippet, ensure that the following permissions are set:
    1. Read access to ASPNET on the EventLog key: HKEY_LOCAL_MACHINE\System\CurrentControlSet\Services\EventLog
    2. Read + Write (Full Control OK) on the custom Event Log for your application, eg., for event Log "Hoksoft", on key: HKEY_LOCAL_MACHINE\System\CurrentControlSet\Services\EventLog\Hoksoft
    3. Ensure that the permissions are set to apply to "this key and subkeys".

    string eventLogName = "Hoksoft";
    string sourceName = "MediaManager";
    EventLog hoksoftLog;
    hoksoftLog = new EventLog();
    hoksoftLog.Log = eventLogName;

    // set default event source (to be same as event log name) if not passed in
    if((sourceName == null) || (sourceName.Trim().Length == 0))
    {
        sourceName = eventLogName;
    }

    hoksoftLog.Source = sourceName;

    // Extra Raw event data can be added (later) if needed
    byte[] rawEventData = Encoding.ASCII.GetBytes("");

    /// Check whether the Event Source exists. It is possible that this may
    /// raise a security exception if the current process account doesn't
    /// have permissions for all sub-keys under
    /// HKEY_LOCAL_MACHINE\System\CurrentControlSet\Services\EventLog

    // Check whether registry key for source exists

    string keyName = @"SYSTEM\CurrentControlSet\Services\EventLog\" + eventLogName;

    RegistryKey rkEventSource = Registry.LocalMachine.OpenSubKey(keyName + @"\" + sourceName);

    // Check whether key exists
    if(rkEventSource == null)
    {
        /// Key does not exist. Create key which represents source
        Registry.LocalMachine.CreateSubKey(keyName + @"\" + sourceName);
    }

    /// Now validate that the .NET Event Message File, EventMessageFile.dll (which correctly
    /// formats the content in a Log Message) is set for the event source
    object eventMessageFile = rkEventSource.GetValue("EventMessageFile");

    /// If the event Source Message File is not set, then set the Event Source message file.
    if(eventMessageFile == null)
    {
        /// Source Event File Doesn't exist - determine .NET framework location,
        /// for Event Messages file.
        RegistryKey dotNetFrameworkSettings = Registry.LocalMachine.OpenSubKey(
            @"SOFTWARE\Microsoft\.NetFramework\");

        if(dotNetFrameworkSettings != null)
        {

            object dotNetInstallRoot = dotNetFrameworkSettings.GetValue(
                "InstallRoot",
                null,
                RegistryValueOptions.None);

            if(dotNetInstallRoot != null)
            {
                string eventMessageFileLocation =
    dotNetInstallRoot.ToString() +
    "v" +
    System.Environment.Version.Major.ToString() + "." +
    System.Environment.Version.Minor.ToString()  + "." +
    System.Environment.Version.Build.ToString() +
    @"\EventLogMessages.dll";

                /// Validate File exists
                if(System.IO.File.Exists(
    eventMessageFileLocation))
                {
    /// The Event Message File exists in the anticipated location on the
    /// machine. Set this value for the new Event Source

    // Re-open the key as writable
    rkEventSource = Registry.LocalMachine.OpenSubKey(
        keyName + @"\" + sourceName,
        true);

    // Set the "EventMessageFile" property
    rkEventSource.SetValue(
        "EventMessageFile",
        eventMessageFileLocation,
        RegistryValueKind.String);
                }
            }
        }

        dotNetFrameworkSettings.Close();
    }

    rkEventSource.Close();

    /// Log the message
    hoksoftLog.WriteEntry(
        logMessage,
        type,
        eventId,
        0,
        rawEventData);

    Tuesday, June 20, 2006 6:37 AM

All replies

  • Estou com o mesmo problema.

    I have equal problem. Quat's is this?

     

    Wednesday, May 31, 2006 1:01 PM
  • Permissions for the Event log are driven through the registry. Each event log has an entry in the registry under the following key:
    HKEY_LOCAL_MACHINE\System\CurrentControlSet\Services\EventLog

    To allow the ASP.NET account access to create an event source, you need to have read permission on this and all sub keys, and write permission on the event to which you want to create the event source. Part of your error message says " Inaccessible logs: Security.". Note that "Virtual Server" seems to be another common inaccessible log. This means that for the Security log, the ASP.NET account (MachineName\ASPNET) does not have read access to that key.

    For reasons that I can't explain, the
    EventLog.CreateEventSource() method attempts to search Event Sources under all event logs, not just the event log for which you want to create the source. There are two solutions to this. The first, easiest, and most insecure, is just to give read/write access to all event logs for the ASP.NET account. To do this, follow these steps:
    1. Start -> Run -> regedit.exe
    2. Navigate to My Computer > HKEY_LOCAL_MACHINE\System\CurrentControlSet\Services\EventLog
    3. Right click this key, select Permissions, and grant the ASPNET account read/write permissions as described above. Note that for the "inaccessible" logs (ie. Security, Virtual Server), you'll also need to grant read access, as permissions have been set to not inherity from the parent key.
    4. Restart IIS (start -> Run  -> iisreset)
    5. Cause the code line that creates the event source to be executed (EventLog.CreateEventSource())
    I don't like this solution because it means that every time a new program that installs its own log (an hence premissions) is installed, the same problem will be encountered.

    The second solution is to bypass the use of the EventLog.CreateEventSource() code, and write your own Event Source addition code, by directly editing adding it to the registry (using code, not regedit!).

    Each event source appears as a key below the event log name. So an event source named "MediaManager" under the event log "Hoksoft" would appear as HKEY_LOCAL_MACHINE\System\CurrentControlSet\Services\EventLog\Hoksoft\MediaManager.

    An "Event Message File" contains resource strings which format your message content based on parameters. The default .NET message file, EventLogMessages.dll, simply has one parameter "%1", which means that your text is inserted as the message content in its entirity. For further reading on this topic, read http://www.codeproject.com/dotnet/evtvwr.asp. Anyway, to avoid message text similar to the following being displayed...

    The description for Event ID ( 0 ) in Source ( MediaManager ) cannot be found. The local computer may not have the necessary registry information or message DLL files to display messages from a remote computer. You may be able to use the /AUXSOURCE= flag to retrieve this description; see Help and Support for details. The following information is part of the event:

    ..., it's necessary to set the EventMessageFile parameter (registry string value) under the subkey for the Event Source. The default location of this file is in the following directory:  c:\WINNT\Microsoft.NET\Framework\v2.0.50727\, where v2.0.50727 is the version of the framework you are using (starting with v1.1.x).

    The following partial snippet of code should contain enough detail to dynamically create the event log source, without requiring access to other event logs. To use this code snippet, ensure that the following permissions are set:
    1. Read access to ASPNET on the EventLog key: HKEY_LOCAL_MACHINE\System\CurrentControlSet\Services\EventLog
    2. Read + Write (Full Control OK) on the custom Event Log for your application, eg., for event Log "Hoksoft", on key: HKEY_LOCAL_MACHINE\System\CurrentControlSet\Services\EventLog\Hoksoft
    3. Ensure that the permissions are set to apply to "this key and subkeys".

    string eventLogName = "Hoksoft";
    string sourceName = "MediaManager";
    EventLog hoksoftLog;
    hoksoftLog = new EventLog();
    hoksoftLog.Log = eventLogName;

    // set default event source (to be same as event log name) if not passed in
    if((sourceName == null) || (sourceName.Trim().Length == 0))
    {
        sourceName = eventLogName;
    }

    hoksoftLog.Source = sourceName;

    // Extra Raw event data can be added (later) if needed
    byte[] rawEventData = Encoding.ASCII.GetBytes("");

    /// Check whether the Event Source exists. It is possible that this may
    /// raise a security exception if the current process account doesn't
    /// have permissions for all sub-keys under
    /// HKEY_LOCAL_MACHINE\System\CurrentControlSet\Services\EventLog

    // Check whether registry key for source exists

    string keyName = @"SYSTEM\CurrentControlSet\Services\EventLog\" + eventLogName;

    RegistryKey rkEventSource = Registry.LocalMachine.OpenSubKey(keyName + @"\" + sourceName);

    // Check whether key exists
    if(rkEventSource == null)
    {
        /// Key does not exist. Create key which represents source
        Registry.LocalMachine.CreateSubKey(keyName + @"\" + sourceName);
    }

    /// Now validate that the .NET Event Message File, EventMessageFile.dll (which correctly
    /// formats the content in a Log Message) is set for the event source
    object eventMessageFile = rkEventSource.GetValue("EventMessageFile");

    /// If the event Source Message File is not set, then set the Event Source message file.
    if(eventMessageFile == null)
    {
        /// Source Event File Doesn't exist - determine .NET framework location,
        /// for Event Messages file.
        RegistryKey dotNetFrameworkSettings = Registry.LocalMachine.OpenSubKey(
            @"SOFTWARE\Microsoft\.NetFramework\");

        if(dotNetFrameworkSettings != null)
        {

            object dotNetInstallRoot = dotNetFrameworkSettings.GetValue(
                "InstallRoot",
                null,
                RegistryValueOptions.None);

            if(dotNetInstallRoot != null)
            {
                string eventMessageFileLocation =
    dotNetInstallRoot.ToString() +
    "v" +
    System.Environment.Version.Major.ToString() + "." +
    System.Environment.Version.Minor.ToString()  + "." +
    System.Environment.Version.Build.ToString() +
    @"\EventLogMessages.dll";

                /// Validate File exists
                if(System.IO.File.Exists(
    eventMessageFileLocation))
                {
    /// The Event Message File exists in the anticipated location on the
    /// machine. Set this value for the new Event Source

    // Re-open the key as writable
    rkEventSource = Registry.LocalMachine.OpenSubKey(
        keyName + @"\" + sourceName,
        true);

    // Set the "EventMessageFile" property
    rkEventSource.SetValue(
        "EventMessageFile",
        eventMessageFileLocation,
        RegistryValueKind.String);
                }
            }
        }

        dotNetFrameworkSettings.Close();
    }

    rkEventSource.Close();

    /// Log the message
    hoksoftLog.WriteEntry(
        logMessage,
        type,
        eventId,
        0,
        rawEventData);

    Tuesday, June 20, 2006 6:37 AM
  • Well... I think that this tricky workaround should be really avoided.
    If .NET has a class to MANAGE the event log then you should use it instead of mangling with registry keys.

    That assured..

    There must be a way to correctly use the "EventLog.SourceExists" method or there's a bug in the framework (or at least a missing documentation on MSDN).
    Maybe they'll mark the method as obsolete and create a new one to do the job.

    Anyway.. IS there any managed (and clear) method to do the same task?
    Yes.. I know it (It would be better to create the log source during the setup of my application but in some cases this is not applicable)

    I actually use this piece of code but I feel there must be something more elegant:

    try
    {
        return EventLog.SourceExists(Source, Server);
    }
    catch (SecurityException)
    {
        //Vista goes here if log doesn't exists!
        return false;
    }

    Let me know if this works for you or if you find a better workaround.

    Wednesday, February 7, 2007 12:01 PM
  • I was able to get this working on my dev machine, but it still gives me a security problem on my production machines.  They are 2003 Server Web Edition.

    One thing to note is in order for the code above to work for me I had to give the MachineName\ASPNET user full control of the Eventlog Folder and all subkeys in the registry.

    Any follow up help would be appreciated.  I cannot believe MSFT wrote their EventLog.SourceExists() method so retarded as to check all Lognames and subkeys by default and not even provide a way to search in a particular Logname for a source.  Lame...

    Thursday, February 8, 2007 12:42 AM
  • I am having the same problem.  My program works with Windows XP but not Vista.  Under Vista, I am not able do CreateEventSource, check EventLog.SourceExists or use the WriteEntry method.  I am able to read the Application logs and the System logs but I am not able to read the Security logs. 

    My program starts by entering "MyApp service has started" in to the Application log of the computer that it is executed on.  Also, one of the main functions is to read event logs.  Since I can't write to the app or read from the security, I'm pretty much dead in the water. 

    I'm pretty sure it's a security issue but I don't know where to look.  This is not a Web application and there is no ASPNET user on the computer.  There has to be a way to use these functions without jumping through too many hoops. 

    Has anyone found a way to get this to work yet (besides the work-around mentioned in this thread)?

     

    "MC"

    Wednesday, February 14, 2007 4:45 PM
  • I've been trying to sort this out too. The problem under Vista seems to be UAC. I run my vb.net 2005 app and it fails but doesn't write an eventlog entry. However, if I run my program "As Administrator" it does write the Event Log Source correctly, and then the Event log entry is correctly written. When the program is run normally after this, the event logging works fine as the Source is already there.

    Rob.

    Wednesday, February 28, 2007 1:47 PM
  • There needs to be a section in the installer package for an application which uses a custom event source that ensures that the event source is created if necessary, and has adequate permissions, during the installation process.
    Tuesday, March 13, 2007 2:56 PM
  • RobMc's reply is the only fitting reply to the question which Tom was asking.

    Wednesday, August 8, 2007 4:48 AM
  • Here is a bug/suggestion report to update MSDN Documentation in relation to this issue:

     

    https://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=293617

     

    Thursday, August 16, 2007 2:31 PM
  • Why shouldn't it be possible for every user to write application messages to the EventLogger?! To me the current implementation seems to be poor.

    Monday, October 22, 2007 9:38 AM
  • Giving the adminitrator rights to the ASP.NET process is doesn't suit to my application scnario.

    Do you guys know the final solution or it is still pending by the Microsoft.

     

    Cheers

    Ashik Wani

     

    Monday, February 4, 2008 4:27 PM
  •  

    The reason this is giving you problems on production is because both Vista RTM and the various production flavors of Windows Server 2003 (Web, Enterprise, DataCenter, etc.) all run the IIS application under the "NETWORK SERVICE" account. As you stated the appropriate permissions to give it on an XP box are the ASPNET account...you can verify which account IIS is running under by simply looking at the Identity property of the application pool (e.g. DefaultAppPool). You will see "NetworkService" or something similar when viewing it on W2K3/Vista and ASPNET when viewing the properties under XP.

     

    Best of luck!

     

    (p.s. for best practices you should create a separate secure dll with elevated trust settings from the rest of the application. If security isn't extremely critical then I'd just continue using the method you use on your dev boxes)

    Tuesday, February 19, 2008 4:25 AM
  • >>>You will see "NetworkService" or something similar when viewing it on W2K3/Vista and ASPNET when viewing the properties under XP.

     

    Good info but now what.   You left us hanging.  Sure, I assume we need to change this but to what.  Since in Vista I don't see a way to change that to "ASPNET", I only see the following options when you try to change the user running that process for the default application pool in Vista when you go to the advanced settings which are the following user options:

     

    Network Service

    Local Service

    Local System

     

    Ok, so none of those are ASPET I wouldn't think right?  So how do I complete your suggested resolution to get the aspnet to run the default pool?

     

    Tuesday, March 25, 2008 1:44 AM
  •  

    adding ASPNET to the permissions of my EventLog folder in registry did nothing to remedy the issue.
    Tuesday, March 25, 2008 1:47 AM
  • Where are you putting the EventLog creation code?  I mean are you creating a .cs and then when are you firing this off and where in your .NET project?  This is sort of important to know.

    Tuesday, March 25, 2008 2:03 AM
  •  

    For your production servers I would just stick with the "Network Service" account -- sorry I didn't make that clear. You just need to make certain that the account specified for the application pool your application runs under has Read permissions on the EventLog\Security key and Full Control on EventLog. I don't really advise changing the default identity that your application pool runs under b/c that's more involved since the account requires permissions to temp directories and other registry keys. There are scripts in the Framework directory that make the job of creating accounts with the necessary permissions fairly simple but for the average environment the default accounts should work fine.

     

    Let me know if that helps to better clarify what I posted earlier.

     

    Cheers.

    Monday, April 21, 2008 3:16 PM
  • And what about when not running an IIS application - it seems that the code when run from VS is running under my own account, which is an administrator - still Security is unavailable. What is going on?

    Tuesday, April 29, 2008 9:29 AM
  •  

    On Vista you're not running under Administrator by default -- and while there are ways to switch to a mode where you are that is not really a topic of this thread. Even if you have UAC disabled you will still be running in an account without full administrative privilages until you right-click and choose Run As Administrator on your program or when UAC is enabled set the properties of the link to always run as administrator.

     

    One of the things that VS.NET 2005/2008 do when you initially load them is warn you that the program should be run as administator -- you can check the box to not remind you again and maybe you're forgetting to run your application as administrator. If you were actually executing as administrator you would not get these permissions issues. If you don't care to go through the steps to figure out what identity your program is running under you can fall-back on setting permissions for the EVERYONE user on those same keys....the better route would obviously be to troubleshoot why your application isn't running under the identity you think it is.

    Wednesday, April 30, 2008 12:23 PM
  •  

    I'm running into the same issue with a desktop (instead of ASP.NET) app.  The regkey approach works if I manually added, but running your code, I run into Vista UAC again because of the permissions needed to write to the registry.  Setting the permissions on the registry in the first place seemed a bit hackish as I just want the app to work.  So I dug a bit deeper and ran across blog by David Boschmans about running with least privilege (http://blogs.msdn.com/davbosch/archive/2007/06/04/windows-vista-uac-demo-code-develop-using-least-privilege.aspx).

     

    Using his sample, I suggest the following changes to Christopher's (answer on page 1) code to solve the problem without ever needed to run Regedit:

    Code Snippet

    string eventLogName = "LogName";

    string sourceName = "SourceName";

    EventLog eventLog;

    eventLog = new EventLog();

    eventLog.Log = eventLogName;

    eventLog.Source = sourceName;

     

    // Check whether registry key for source exists

    string keyName = @"SYSTEM\CurrentControlSet\Services\EventLog\" + eventLogName + @"\" + sourceName;

    RegistryKey rkEventSource = Registry.LocalMachine.OpenSubKey(keyName);

    // Check whether keys exists

    if (rkEventSource == null)

    {

    // Key doesnt exist. Create key which represents source

    Process Proc = new Process();

    ProcessStartInfo ProcStartInfo = new ProcessStartInfo("Reg.exe");

    ProcStartInfo.Arguments = @"add HKLM\" + keyName;

    ProcStartInfo.UseShellExecute = true;

    ProcStartInfo.Verb = "runas";

    Proc.StartInfo = ProcStartInfo;

    Proc.Start();

    }

    try

    {

    eventLog.WriteEntry("With key.... :)");

    }

    catch

    {

    Debug.Print("failed to write key");

    }

     

     

     

    If the Key isn't there, then you get the UAC pop-up just for the reg add.  Otherwise it merrily logs the event!  Now obviously this wouldn't work for ASP.Net folks, but it definately helps for regular old apps.
    Thursday, May 8, 2008 2:27 AM
  • I didn't know it was possible to hate an OS so much!
    Friday, June 6, 2008 4:55 PM
  • I have the same problem, but I using Windows Application is not Web Application.

     

    Everybody any idea about this?

     

    Thanks

     

    Saturday, September 27, 2008 3:19 PM
  • I got this working a while ago with the original code I posted here:

     

    Dim MyEventType As EventLogEntryType

    Dim ev As New EventLog("Application", MyPC, "Test_App")

     

    MyEventType = EventLogEntryType.Information

     

    If Not EventLog.SourceExists("Test_App", MyPCName) Then

    EventLog.CreateEventSource("Test_App", "Application")

    End If

     

    ev.WriteEntry(My_Message, MyEventType, CInt(My_Event_ID))

    ev.Close()

     

    I think my original problem was with the UAC.  The other problem I had as that I was trying to create a souce in the Security event log.  I'm able to create one under Application and System but I get an error message when creating one under Security.  I don't really need to write to the Security log so my app runs fine now.

     

    If the app creates an eventlog with the UAC off, you can go to the project's properties page, go the Application tab, and then click the <View UAC Settings> button.  That will bring up the app.manifest page and there are instructions there for how to get the app to run as administrator.  However, with the setting on, you have to give your app permission to run every time it starts.  That's not the greatest solution because you only need to create the event log source once.  You could create a custom app that runs during the setup process that will create the event log and then run the setup as adminitrator.  Not sure if that's the best solution but I'm not an expert.

    Sunday, September 28, 2008 1:27 PM
  • How about a different approach:

    1.) when your application runs, it should have limited privileges, thus it shouldn't be creating event sources.
    2.) when you install your application (classic or web), the installation happens with higher privileges.
    Thus, you should consider event source creation an installation task.

    To get to steps: create a deployment project for your application, that writes an event log entry into the desired Event Log, using the desired events source - this will happen with administrative privileges, during installation.

    B


    BalintN
    • Proposed as answer by Rich_876 Saturday, May 22, 2010 2:58 PM
    Monday, April 19, 2010 4:11 PM
  • I was also facing the same issue while writing the eventlog in the event viewer using asp.net process

    I was using the iis 7.0 version.

    I resovled this issue by chaging the account setting of IIS web application pool from network service to local account.

    And the issue was resovled automatically.

     

     

    Regards,

    Ajay Singh Beniwal

    Thursday, May 13, 2010 5:28 AM
  • There's a lot of good information in this thread but this guy's got the right answer.  Normally, an app wouldn't be creating event log sources at run time.  If it writes to the log, that's fine but, as BalintN says, creating the source is an installation task.

    If your app is going to require a lot of installation and set-up, consider developing a set-up project for it, especially if it's going to have to be re-deployed to multiple platforms.  (Probably more likely for a Windows app  as opposed to an ASP.NET app.)  Otherwise, you can always write a simple console app that does all your installation stuff - run it "as administrator" each time you need to deploy.

    I would also be careful about what kind of information is written to Event Logs and how often.  I believe that writing to logs is fairly expensive and not something that should be a routine part of a web page, especially in a high volume environment. 

     

    Saturday, May 22, 2010 2:57 PM
  • I faced this issue. But then instead of creating my own eventlog and source i just used this:

     

    catch (Exception ex)

    {

     

    EventLog.WriteEntry(ex.Source, ex.Message + " This is my custom message!", EventLogEntryType.Error);

    return =

    null;

     

    }

    It added entry to "Application" Log with the original Source. This way I was able to add entry to EventLog and also didn't have any permission issues. Not fancy but it serves the purpose in my case.

    Note: Using the same statement outside of the "catch" didn't work. Somehow it did not like when I moved the statement into another function.

    Thursday, August 19, 2010 9:26 PM
  • I'm having a similar problem running under Windows 7 64 bit and it only seems to be related to one custom app. I have code that creates a new event log that creates the log and then write's an entry to it. The only problem is the message writes to the Application log instead of the log I created.. This code works in other apps so I'm not sure whats going on now.. here's my code:

                    if (!EventLog.Exists(ApplicationInformation.Title)) {
                        if (!EventLog.SourceExists(sourceName, ApplicationInformation.ComputerName)) {
                            EventSourceCreationData el = new EventSourceCreationData(sourceName, ApplicationInformation.Title) {
                                MachineName = ApplicationInformation.ComputerName
                            };
                            EventLog.CreateEventSource(el);
                            
                        }
                    } else {
                        using (EventLog logEntry = new EventLog(ApplicationInformation.Title, ApplicationInformation.ComputerName, sourceName)) {
                            logEntry.WriteEntry("This is a test", EventLogEntryType.Error, 5);
                        }
                    }

    ApplicationInformation is a static class I created that returns application information and other misc info. Title is the title of the application..  I noticed that if I delete the log I created, any messages that got written to the Application log with the source name i provided gets deleted as well.. definitely something weird going on.. Any ideas anybody?
    Monday, February 13, 2012 8:54 PM
  • I am working on an ASP.NET 2.0 application under Win7 32 bit and VS2005. When I get events in the global.aspx (application_start for example) my application sources get created. When I hit a custom event handler (where I have custom classes, and hence, custom source names), a check for the source via

    (EventLog.SourceExists(source))

    throws {"The source was not found, but some or all event logs could not be searched.  Inaccessible logs: Security."}.

    I have granted "read" access to the "eventlog" key in the registry, and "write" access to the "(application name)" key in the registry for "IIS_IUSRS" which is the standard 'anonymous' access for a web application. 

    "(application name)" was previously created by another application in our suite. It seems that source is subordinate to application in the log, so why is it MORE difficult to create a source than an application? Does it take a Masters of Science to understand Windows Security as it applies to the event logging model? Point me to a good reference, I dare you!

     

    Tuesday, February 28, 2012 5:54 AM
  • James3838 has a great solution (for desktop apps).  The only problem is that running the reg process still requires elevated privileges, and end user's in my corporate environment won't have that. 
    Wednesday, June 6, 2012 7:08 PM
  • I tried using the .NET framework's EventLogInstaller running as a Custom Action in my MSI, and when that failed, I tried СђrΐsτσρhΞr ScЋδlτξη solution but even that didn't work.  Then I tried manually creating the registry keys and found that I couldn't do that either!  In my case, we have a bunch of security bloatware like every version of McAfee known to mankind which I suspected was interfering.  So to test it, I rebooted into safe mode to prevent McAfee from starting and was able to add the registry keys manually.  So just be advised it could also be security software interfering with your install.
    Tuesday, May 21, 2013 7:24 PM
  • The basic problem here is that, if you're using the Event Log, you *should*, as best practice, make a new Event Log for your application so as to not flood the system Event Logs with spurious traffic.  Microsoft, in their infinite wisdom, has set their security practices in direct opposition to this, making it effectively impossible to do without doing a whole bunch of things that, from a security standpoint, are just plain nasty.  

    The best solution, oddly, is to simply ignore best practice.  Use the Application Event Log for your log entries, and the "Application Error" event source as the source.  Yes, that will flood the Application event log with your events.   However, Microsoft has crippled the Event Log so that is the only way it can safely work.  If the "Application Error" source doesn't work, then try "Desktop Window Manager", or "WMI", or "EventSystem", all of which are built-ins, and at least one of them should work on any box. 

    Of course, this will mean that the Application Source is no longer related to your actual Application.  To side-step this issue, pick some arbitrary number to register as the Event ID.  Then you can use the Event Id to identify entries from your particular application, unless you pick one that is in use by something else, in which case you will get both, but it's still better than nothing.


    • Proposed as answer by NetMage Thursday, December 10, 2015 11:07 PM
    Sunday, June 16, 2013 10:42 PM
  • >Microsoft has crippled the Event Log so that is the only way it can safely work.

    As pointed out by others earlier in this thread, the way to safely work is to write an installer that would automatically run as administrator and write to the registry, or launch a program that demand administrator access. If the user does not trust you enough to run an installer or click through the UAC prompt, you got a bigger problem to solve.



    Visual C++ MVP


    Monday, June 17, 2013 9:32 PM
    Moderator