I'm a fairly new programmer. I have been working on a .net core wpf application and I would like to add logging for exceptions. I've looked into ways to do logging in .net core with nlogger and log4net, but all the tutorials are specific to asp.net core. Can someone point me in the right direction for how to use logging in .net core for a wpf application? I assume I will have to add a config file since .net core doesn't implement this for you.
- 1I recommend nlog. Instantiation is expensive. You should register it as a singleton ( or use a static if you decide against ioc ). Nlog uses it's own nlog.config file. You can find examples online. However you instantiate, ensure it's either after the entry point or plan for a slow startup user experience.Andy– Andy2019-12-17 09:18:12 +00:00Commented Dec 17, 2019 at 9:18
- This is what I ended up doing and it works great. Thanks!RomanOwensby– RomanOwensby2019-12-17 18:07:23 +00:00Commented Dec 17, 2019 at 18:07
- does Nlog works prefectly in .net core wpf application?any references?jithu– jithu2020-10-12 09:04:28 +00:00Commented Oct 12, 2020 at 9:04
1 Answer
I suggest you use dependency injection (DI) for your logger and for all other dependencies. In WPF, you can use Application_Startup as the "composition root" where you register all dependencies.
This example uses Castle Windsor for DI but you can use your choice. The logger here is Serilog but again, it doesn't matter which you use:
/// <summary> /// Interaction logic for App.xaml /// </summary> public partial class App : Application { private async void Application_Startup(object sender, StartupEventArgs e) { ILogger log = new LoggerConfiguration() .Enrich.FromLogContext() .WriteTo.File(path: logFolder, restrictedToMinimumLevel: Serilog.Events.LogEventLevel.Information, rollingInterval: RollingInterval.Day, rollOnFileSizeLimit: true) .CreateLogger(); var ioc = new WindsorContainer(); ioc.Register(Castle.MicroKernel.Registration.Component.For<ILogger>().Instance(log)); ioc.Register(Castle.MicroKernel.Registration.Component.For<SomeDependency...>().ImplementedBy<SomeDependency Implementation...>()); ioc.Register(Castle.MicroKernel.Registration.Component.For<SomeDependency...>().ImplementedBy<SomeDependency Implementation...>()); ioc.Register(Castle.MicroKernel.Registration.Component.For<MainWindow>().ImplementedBy<MainWindow>()); //... etc. var window = ioc.Resolve<MainWindow>(); window.Show(); } } Anything that needs to log can just declare an ILogger in the constructor, and as long as the Type is also resolved through DI it will get an instance:
public class SomeClassThatLogs { private readonly ILogger _logger; public SomeClassThatLogs(ILogger logger) { _logger = logger; } } I don't intend this answer to be a lesson on DI, you will probably need to research it, but this is one method for using DI in WPF.