First in the Program.cs file, add .ConfigureLogging to the CreateHostBuilder expression-bodied member.
public static IHostBuilder CreateHostBuilder(string[] args) => Host.CreateDefaultBuilder(args) .ConfigureLogging( logging => { logging.ClearProviders(); logging.AddEventLog(new Microsoft.Extensions.Logging.EventLog.EventLogSettings { SourceName = "Steves Application" }); }) .ConfigureWebHostDefaults(webBuilder => { webBuilder.UseStartup(); });
If you didn't do this, CreateDefaultBuilder would actually add some providers by default. But since we want to use a custom source name, it is necessary to call ClearProviders and add our own explicitly.
Next, you need to make a change to your appSettings.json file. Add an EventLog section like the following:
"Logging": { "LogLevel": { "Default": "Information", "Microsoft": "Warning", "Microsoft.Hosting.Lifetime": "Information" }, "EventLog": { "LogLevel": { "AppName.Controllers.HomeController": "Information" } } }
AppName.Controllers.HomeController is the fully qualified name of the class where you are logging from. When you log to the event log in .NET Core, it assigns a category to the event. It uses the fully qualified name of the class it is logging from as the category name. By including this in the appSettings.json file, you are saying that you want any events with this category with a log level of Information or above to be logged. By default, only events with a log level of Warning and above will be logged. Since we do a lot of informational logging, it is necessary to override this default.
Now, all that is left to do it log.
You need to inject a ILogger object into the constructor of your class:
private readonly ILogger _logger; public HomeController(ILogger<HomeController> logger) { _logger = logger; }
Then, it just a matter of calling the LogInformation or LogWarning method of the logger:
_logger.LogInformation("Testing");