- Notifications
You must be signed in to change notification settings - Fork3
feat: add logging to App#78
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to ourterms of service andprivacy statement. We’ll occasionally send you account related emails.
Already on GitHub?Sign in to your account
Merged
Uh oh!
There was an error while loading.Please reload this page.
Merged
Changes fromall commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Uh oh!
There was an error while loading.Please reload this page.
Jump to
Jump to file
Failed to load files.
Loading
Uh oh!
There was an error while loading.Please reload this page.
Diff view
Diff view
There are no files selected for viewing
9 changes: 6 additions & 3 deletionsApp/App.csproj
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.Learn more about bidirectional Unicode characters
94 changes: 75 additions & 19 deletionsApp/App.xaml.cs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -16,6 +16,9 @@ | ||
using Microsoft.Win32; | ||
using Microsoft.Windows.AppLifecycle; | ||
using Windows.ApplicationModel.Activation; | ||
using Microsoft.Extensions.Logging; | ||
using Serilog; | ||
using System.Collections.Generic; | ||
namespace Coder.Desktop.App; | ||
@@ -24,22 +27,39 @@ public partial class App : Application | ||
private readonly IServiceProvider _services; | ||
private bool _handleWindowClosed = true; | ||
private const string MutagenControllerConfigSection = "MutagenController"; | ||
#if !DEBUG | ||
private const string ConfigSubKey = @"SOFTWARE\Coder Desktop\App"; | ||
private const string logFilename = "app.log"; | ||
#else | ||
private const string ConfigSubKey = @"SOFTWARE\Coder Desktop\DebugApp"; | ||
private const string logFilename = "debug-app.log"; | ||
spikecurtis marked this conversation as resolved. Show resolvedHide resolvedUh oh!There was an error while loading.Please reload this page. | ||
#endif | ||
private readonly ILogger<App> _logger; | ||
public App() | ||
{ | ||
var builder = Host.CreateApplicationBuilder(); | ||
var configBuilder = builder.Configuration as IConfigurationBuilder; | ||
// Add config in increasing order of precedence: first builtin defaults, then HKLM, finally HKCU | ||
// so that the user's settings in the registry take precedence. | ||
AddDefaultConfig(configBuilder); | ||
configBuilder.Add( | ||
new RegistryConfigurationSource(Registry.LocalMachine, ConfigSubKey)); | ||
configBuilder.Add( | ||
new RegistryConfigurationSource(Registry.CurrentUser, ConfigSubKey)); | ||
var services = builder.Services; | ||
// Logging | ||
builder.Services.AddSerilog((_, loggerConfig) => | ||
{ | ||
loggerConfig.ReadFrom.Configuration(builder.Configuration); | ||
}); | ||
services.AddSingleton<ICredentialManager, CredentialManager>(); | ||
services.AddSingleton<IRpcController, RpcController>(); | ||
@@ -69,12 +89,14 @@ public App() | ||
services.AddTransient<TrayWindow>(); | ||
_services = services.BuildServiceProvider(); | ||
_logger = (ILogger<App>)(_services.GetService(typeof(ILogger<App>))!); | ||
InitializeComponent(); | ||
} | ||
public async Task ExitApplication() | ||
{ | ||
_logger.LogDebug("exiting app"); | ||
_handleWindowClosed = false; | ||
Exit(); | ||
var syncController = _services.GetRequiredService<ISyncSessionController>(); | ||
@@ -87,36 +109,39 @@ public async Task ExitApplication() | ||
protected override void OnLaunched(Microsoft.UI.Xaml.LaunchActivatedEventArgs args) | ||
{ | ||
_logger.LogInformation("new instance launched"); | ||
// Start connecting to the manager in the background. | ||
var rpcController = _services.GetRequiredService<IRpcController>(); | ||
if (rpcController.GetState().RpcLifecycle == RpcLifecycle.Disconnected) | ||
// Passing in a CT with no cancellation is desired here, because | ||
// the named pipe open will block until the pipe comes up. | ||
_logger.LogDebug("reconnecting with VPN service"); | ||
_ = rpcController.Reconnect(CancellationToken.None).ContinueWith(t => | ||
{ | ||
if (t.Exception != null) | ||
{ | ||
_logger.LogError(t.Exception, "failed to connect to VPN service"); | ||
#if DEBUG | ||
Debug.WriteLine(t.Exception); | ||
Debugger.Break(); | ||
#endif | ||
} | ||
}); | ||
// Load the credentials in the background. | ||
var credentialManagerCts = new CancellationTokenSource(TimeSpan.FromSeconds(15)); | ||
var credentialManager = _services.GetRequiredService<ICredentialManager>(); | ||
_ = credentialManager.LoadCredentials(credentialManagerCts.Token).ContinueWith(t => | ||
{ | ||
if (t.Exception != null) | ||
{ | ||
_logger.LogError(t.Exception, "failed to load credentials"); | ||
#if DEBUG | ||
Debug.WriteLine(t.Exception); | ||
Debugger.Break(); | ||
#endif | ||
} | ||
credentialManagerCts.Dispose(); | ||
}, CancellationToken.None); | ||
@@ -125,10 +150,14 @@ protected override void OnLaunched(Microsoft.UI.Xaml.LaunchActivatedEventArgs ar | ||
var syncSessionController = _services.GetRequiredService<ISyncSessionController>(); | ||
_ = syncSessionController.RefreshState(syncSessionCts.Token).ContinueWith(t => | ||
{ | ||
if (t.IsCanceled || t.Exception != null) | ||
{ | ||
_logger.LogError(t.Exception, "failed to refresh sync state (canceled = {canceled})", t.IsCanceled); | ||
#if DEBUG | ||
Debugger.Break(); | ||
#endif | ||
} | ||
syncSessionCts.Dispose(); | ||
}, CancellationToken.None); | ||
@@ -148,17 +177,44 @@ public void OnActivated(object? sender, AppActivationArguments args) | ||
{ | ||
case ExtendedActivationKind.Protocol: | ||
var protoArgs = args.Data as IProtocolActivatedEventArgs; | ||
if (protoArgs == null) | ||
{ | ||
_logger.LogWarning("URI activation with null data"); | ||
return; | ||
} | ||
HandleURIActivation(protoArgs.Uri); | ||
break; | ||
default: | ||
_logger.LogWarning("activation for {kind}, which is unhandled", args.Kind); | ||
break; | ||
} | ||
} | ||
public void HandleURIActivation(Uri uri) | ||
{ | ||
// don't log the query string as that's where we include some sensitive information like passwords | ||
_logger.LogInformation("handling URI activation for {path}", uri.AbsolutePath); | ||
} | ||
private static void AddDefaultConfig(IConfigurationBuilder builder) | ||
{ | ||
var logPath = Path.Combine( | ||
Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), | ||
"CoderDesktop", | ||
logFilename); | ||
builder.AddInMemoryCollection(new Dictionary<string, string?> | ||
{ | ||
[MutagenControllerConfigSection + ":MutagenExecutablePath"] = @"C:\mutagen.exe", | ||
["Serilog:Using:0"] = "Serilog.Sinks.File", | ||
["Serilog:MinimumLevel"] = "Information", | ||
["Serilog:Enrich:0"] = "FromLogContext", | ||
["Serilog:WriteTo:0:Name"] = "File", | ||
["Serilog:WriteTo:0:Args:path"] = logPath, | ||
["Serilog:WriteTo:0:Args:outputTemplate"] = | ||
"{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz} [{Level:u3}] {SourceContext} - {Message:lj}{NewLine}{Exception}", | ||
["Serilog:WriteTo:0:Args:rollingInterval"] = "Day", | ||
}); | ||
} | ||
} |
Oops, something went wrong.
Uh oh!
There was an error while loading.Please reload this page.
Oops, something went wrong.
Uh oh!
There was an error while loading.Please reload this page.
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.