Windows Event Log with .Net 5

Rajarajacholan Krishnamurthy 21 Reputation points
2021-08-24T14:35:26.297+00:00

I have a .Net 5 console application and want to write messages to Windows EventLog.

System.Diagnotics.EvengLog does not work also can't add Microsoft.Extensions.Logging.EventLog as getting error as it is targeted to .net framework 4.5.1

Why is it so difficult? Can't find anything useful so far!!!

Any help would be much appreciated.

Thanks.

.NET CLI
.NET CLI
A cross-platform toolchain for developing, building, running, and publishing .NET applications.
328 questions
0 comments No comments
{count} votes

3 answers

Sort by: Most helpful
  1. Timon Yang-MSFT 9,586 Reputation points
    2021-08-25T07:56:54.747+00:00

    Windows Event Log is a Windows-specific function, but .Net 5 is cross-platform. If you run this code on Linux, there will be problems.

    The solution is simple, just add a judgment statement:

            static void Main(string[] args)  
            {  
                if (OperatingSystem.IsWindows())  
                {  
                    using (EventLog eventLog = new EventLog("Application"))  
                    {  
                        eventLog.Source = "Application";  
                        eventLog.WriteEntry("Log message example", EventLogEntryType.Information, 101, 1);  
                    }  
                }  
            }  
    

    If the response is helpful, please click "Accept Answer" and upvote it.
    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.


  2. Matthias Vanneste | Cloudware 1 Reputation point
    2021-09-17T11:22:47.417+00:00

    You have to install the Microsoft.Extensions.Logging.EventLog NuGet package first, to be able to use the EventLog class.

    0 comments No comments

  3. Castorix31 83,101 Reputation points
    2021-09-17T12:58:35.897+00:00

    System.Diagnotics.EvengLog does not work

    It works if you add in the .csproj file :

     <ItemGroup>
            <FrameworkReference Include="Microsoft.WindowsDesktop.App" />
     </ItemGroup>
    

    (tested with .NET 5 Console, on Windows 10 1909)

    0 comments No comments