I need a way to write to Windows' event viewer in my app that's using dnx. But, the EventLog
class isn't available in the System.Diagnostics
namespace so I'm stuck. Is there any other way to write to the EventViewer?
5 Answers
Add from NuGet
Microsoft.Extensions.Logging.EventLog
Version 2.1.1
CM> Install-Package Microsoft.Extensions.Logging.EventLog -Version 2.1.1
Include the namespace Microsoft.Extensions.Logging.EventLog
in the Program.cs
file
This resolved my problem.
-
3Hi, welcome to StackOverflow. Could you edit your answer to clarify how this answers the OP's question, please. Aug 12, 2018 at 18:24
-
1you can also install-Package System.Diagnostics.EventLog with version 6.0.0– UdayMar 10, 2022 at 8:22
Writing to the Event Log in .Net Core requires first a Nuget package installation
Install-Package Microsoft.Extensions.Logging.EventLog -Version 3.1.2
Note that the correct version to install depends on the version of .Net Core you are running.The package above was tested OK with .Net Core.
Then we need to add EventLog. In the Program class we can do this like so:
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Logging.EventLog;
namespace SomeAcme.SomeApi
{
public class Program
{
public static void Main(string[] args)
{
CreateHostBuilder(args).Build().Run();
}
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureLogging((hostingContext, logging) =>
{
logging.ClearProviders();
logging.AddConfiguration(hostingContext.Configuration.GetSection("Logging"));
logging.AddEventLog(new EventLogSettings()
{
**SourceName = "SomeApi",
LogName = "SomeApi",**
Filter = (x, y) => y >= LogLevel.Warning
});
logging.AddConsole();
})
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Startup>();
});
}
}
And our appsettings.json file includes setup:
{
"ConnectionStrings": {
"DefaultConnection": "Server=.\\SQLEXPRESS;Database=SomeApi;Trusted_Connection=True;MultipleActiveResultSets=true"
},
**"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft": "Warning",
"Microsoft.Hosting.Lifetime": "Information"
}
},**
"AllowedHosts": "*"
}
We can inject the ILogger instance
using SomeAcme.SomeApi.SomeModels;
using SomeAcme.SomeApi.Services;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using System.Collections.Generic;
namespace SomeAcme.SomeApi.Controllers
{
[Route("api/[controller]")]
[ApiController]
public class SomeController : ControllerBase
{
private readonly ISomeService _healthUnitService;
private readonly ILogger<SomeController> _logger;
public SomeController(ISomeService someService, ILogger<SomeController> logger)
{
_someService= someService;
_logger = logger;
}
// GET: api/Some
[HttpGet]
public IEnumerable<SomeModel> GetAll()
{
return _someService.GetAll();
}
}
}
More advanced use, add a global exception handler inside Configure method of Startup class in .Net Core:
//Set up a global error handler for handling Unhandled exceptions in the API by logging it and giving a HTTP 500 Error with diagnostic information in Development and Staging
app.UseExceptionHandler(errorApp =>
{
errorApp.Run(async context =>
{
context.Response.StatusCode = 500; // or another Status accordingly to Exception Type
context.Response.ContentType = "application/json";
var status = context.Features.Get<IStatusCodeReExecuteFeature>();
var error = context.Features.Get<IExceptionHandlerFeature>();
if (error != null)
{
var ex = error.Error;
string exTitle = "Http 500 Internal Server Error in SomeAcme.SomeApi occured. The unhandled error is: ";
string exceptionString = !env.IsProduction() ? (new ExceptionModel
{
Message = exTitle + ex.Message,
InnerException = ex?.InnerException?.Message,
StackTrace = ex?.StackTrace,
OccuredAt = DateTime.Now,
QueryStringOfException = status?.OriginalQueryString,
RouteOfException = status?.OriginalPath
}).ToString() : new ExceptionModel()
{
Message = exTitle + ex.Message,
OccuredAt = DateTime.Now
}.ToString();
try
{
_logger.LogError(exceptionString);
}
catch (Exception err)
{
Console.WriteLine(err);
}
await context.Response.WriteAsync(exceptionString, Encoding.UTF8);
}
});
});
And finally a helper model to pack our exception information into.
using System;
using Newtonsoft.Json;
namespace SomeAcme.SomeApi.Models
{
/// <summary>
/// Exception model for generic useful information to be returned to client caller
/// </summary>
public class ExceptionModel
{
public string Message { get; set; }
public string InnerException { get; set; }
public DateTime OccuredAt { get; set; }
public string StackTrace { get; set; }
public string RouteOfException { get; set; }
public string QueryStringOfException { get; set; }
public override string ToString()
{
return JsonConvert.SerializeObject(this);
}
}
}
The tricky bit here is to get hold of a logger inside the Startup class. You can inject ILoggerFactory for this and just do :
_logger = loggerFactory.CreateLogger<Startup>();
Where _logger is used in the global error handler above.
Now back again to the question of how to write to the event log, look at the source code for SomeController above. We inject ILogger here. Just use that instance and it offers different methods for writing to your configured logs. Since we added in the Program class event log, this happens automatically.
Before you test out the code above, run the following Powershell script as administrator to get your event log source:
New-EventLog -LogName SomeApi -SourceName SomeApi
What I like with this approach is that if we do everything correct, the exceptions pops up inside the SomeApi source nicely and not inside the application event log (clutter IMHO).
-
7The PowerShell syntax for creating the event log is
New-EventLog -LogName SomeApi -Source SomeApi
– MadMarcOct 9, 2020 at 8:06 -
1Yes, and if the -LogName and -Source has same value the log will also be visible in Event Viewer as an individual node in the list of logs to the left of eventvwr instead of being mixed with other logs, usually Applications log. Jan 17, 2021 at 1:27
Good news! EventLog is already ported to corefx and will be available in .NET Core 2.1.
Right now you can download a preview package System.Diagnostics.EventLog from their MyGet feed.
it is available in 2.0 but you have to install the compatibility pack. https://github.com/dotnet/corefx/issues/25440
Here for more information: https://blogs.msdn.microsoft.com/dotnet/2017/11/16/announcing-the-windows-compatibility-pack-for-net-core/
EventLog.WriteEntry
is a static method in Diagnostics:
System.Diagnostics.EventLog.WriteEntry(source, message, MessageType, EventId);
I've been calling it for years & it works fine. 1 line of code vs all the other answers & it directly answers the question asked
Defaults to the application event log. Using custom logs takes more work, including reg key permissions.
-
The issue is that the source must exist before you use it. According to the documentation, you have to create the source and exit. It will be available the second time the application is run. This makes it a good candidate for running inside an installer project. learn.microsoft.com/en-us/dotnet/api/… Aug 15 at 15:40
-
So, read the registry 1st. Supposed to be doing that anyway anytime anything outside an app is going to be accessed. If you use a custom event log, registry permissions also need to be modified. However, if you use the App or System event log, then the source already exists, if I'm interpreting your post correct.y– JRrelyeaOct 28 at 23:40
-
The issue is usually administrative rights. If your application has regular user permissions and the user can't elevate without an admin, you're going to need an installer with admin permissions. If you want your installer to run in a per-user mode then you can't do this at all. Oct 30 at 15:05
-
Use either the Application or System Event Log... built into all Windows flavors & it eliminates registry changes & permissions. And no, you don't need admin permissions.– JRrelyeaNov 15 at 3:52
-
We are already talking about the Application log. Did you try it? There is a "Source" column in event viewer. This is where you put the name of your application so you can filter the Application log for your application. You cannot add a new application to the list of registered application sources without admin. You must be using an existing source. That existing source was either created with admin permissions or is not unique to your application. Nov 15 at 16:55
frameworks
section ofproject.json
see stackoverflow.com/questions/30763115/… for some optionsEventLog
only when dnx461 is active, otherwise do something else.