-1

I try to flush the log on applcation exit. Here is my try, but CoreApplicationExiting is never called:

public partial class App : Application
{
    public App()
    {
        Serilog.Log.Logger = new LoggerConfiguration()
            .WriteTo.Console()
            .WriteTo.File(ApplicationData.Current.LocalFolder.Path + "\\.log", rollingInterval: RollingInterval.Day, 
                outputTemplate: "[{Timestamp:HH:mm:ss.fff} {SourceContext} [{Level}] {Message}{NewLine}{Exception}")
            .MinimumLevel.Debug()
            .CreateLogger();

        Serilog.Log.Information("Starting App at: " + DateTime.Now);

        base.UnhandledException += App_UnhandledException;
        CoreApplication.Exiting += CoreApplicationExiting;
        InitializeComponent();

        Host = Microsoft.Extensions.Hosting.Host
            .CreateDefaultBuilder()
            .UseContentRoot(AppContext.BaseDirectory)
            .UseSerilog()
            .ConfigureServices((context, services) =>
            
            ....
    }
    
     private void CoreApplicationExiting(object? sender, object e)
    {
        Serilog.Log.CloseAndFlush();
    }

I tested that with a button handler and a breakpoint in CoreApplicationExiting.

    private void tryExit(object sender, RoutedEventArgs e)
    {
        Application.Current.Exit();
    }
brainer33
  • 19
  • 5

2 Answers2

1

You could use Window's Closed event.

protected override void OnLaunched(LaunchActivatedEventArgs args)
{
    _window = new MainWindow();
    _window.Activate();
    _window.Closed += (sender, args) =>
    {
        // Flush your logs here.
    };
}
Andrew KeepCoding
  • 7,040
  • 2
  • 14
  • 21
0

You can handle the AppWindow.Closing event in the MainWindow.xaml.cs:

public MainWindow(){
    ...
    this.AppWindow.Closing += AppWindow_Closing1;
}

private void AppWindow_Closing1(Microsoft.UI.Windowing.AppWindow sender, Microsoft.UI.Windowing.AppWindowClosingEventArgs args)
{
    //Handle your code to clear the log here
}
FrozenAssassine
  • 1,392
  • 1
  • 7
  • 16