Skip to content

Commit

Permalink
Merge pull request #98 from stevealexandre/fix_logger_issue
Browse files Browse the repository at this point in the history
fix: log admin permission issue
  • Loading branch information
BrianLima committed Sep 18, 2022
2 parents 80419ca + ab58a6a commit 826822c
Show file tree
Hide file tree
Showing 9 changed files with 202 additions and 89 deletions.
12 changes: 12 additions & 0 deletions UWPHook/App.config
Original file line number Diff line number Diff line change
Expand Up @@ -82,6 +82,18 @@
</ArrayOfString>
</value>
</setting>
<setting name="LogLevel" serializeAs="Xml">
<value>
<ArrayOfString xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<string>ERROR</string>
<string>DEBUG</string>
<string>TRACE</string>
</ArrayOfString>
</value>
</setting>
<setting name="SelectedLogLevel" serializeAs="String">
<value>0</value>
</setting>
</UWPHook.Properties.Settings>
</userSettings>
<runtime>
Expand Down
16 changes: 8 additions & 8 deletions UWPHook/AppManager.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
using Serilog;
using Serilog.Core;
using System;
using System.Collections.Generic;
using System.Diagnostics;
Expand Down Expand Up @@ -28,16 +29,13 @@ static class AppManager
/// <param name="aumid">The AUMID of the app to launch</param>
public static void LaunchUWPApp(string[] args)
{


// We receive the args from Steam,
// 0 is application location,
// 1 is the aumid,
// 2 is the executable, the rest are extras
string aumid = args[1];
executablePath = args[2].Contains("/") ? args[2].Replace('/', '\\') : args[2];
FileStream debug = File.OpenWrite("debug.log");
Log.Debug("Arguments => " + String.Join("/", args));
Log.Verbose("Arguments => " + String.Join("/", args));
var mgr = new ApplicationActivationManager();
uint processId;

Expand All @@ -50,13 +48,14 @@ public static void LaunchUWPApp(string[] args)
{
mgr.ActivateApplication(aumid, extra_args, ActivateOptions.None, out processId);
runningProcessId = (int) processId;
Log.Debug("Process ID => " + runningProcessId.ToString());
Log.Verbose("Process ID => " + runningProcessId.ToString());

//Bring the launched app to the foreground, this fixes in-home streaming
BringProcess();
}
catch (Exception e)
{
Log.Error("Error while trying to launch your app." + Environment.NewLine + e.Message);
throw new Exception("Error while trying to launch your app." + Environment.NewLine + e.Message);
}
}
Expand Down Expand Up @@ -96,12 +95,12 @@ public static Boolean IsRunning()
foreach (var process in processes)
{
string executableFile = executablePath.Contains('\\') ? executablePath.Substring(executablePath.LastIndexOf('\\') + 1) : executablePath;
Log.Debug("Process " + process.Value.Path + " contains " + executablePath + " ? : " + process.Value.Path.Contains(executablePath).ToString());
Log.Debug("Process " + process.Key + " contains " + executableFile + " ? : " + process.Key.Contains(executableFile).ToString());
Log.Verbose("Process " + process.Value.Path + " contains " + executablePath + " ? : " + process.Value.Path.Contains(executablePath).ToString());
Log.Verbose("Process " + process.Key + " contains " + executableFile + " ? : " + process.Key.Contains(executableFile).ToString());
if (process.Value.Path.Contains(executablePath) || process.Key.Contains(executableFile))
{
int pid = process.Value.Pid;
Log.Debug($"Launcher opened child process ({runningProcessId}->{pid}), using new process as target");
Log.Verbose($"Launcher opened child process ({runningProcessId}->{pid}), using new process as target");
runningProcessId = pid;
isLauncherProcess = true;

Expand Down Expand Up @@ -173,6 +172,7 @@ public static List<String> GetInstalledApps()
}
catch (Exception e)
{
Log.Error("Error trying to get installed apps on your PC " + Environment.NewLine + e.Message, e.InnerException);
throw new Exception("Error trying to get installed apps on your PC " + Environment.NewLine + e.Message, e.InnerException);
}

Expand Down
71 changes: 56 additions & 15 deletions UWPHook/GamesWindow.xaml.cs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
using Force.Crc32;
using Serilog;
using Serilog.Core;
using SharpSteam;
using System;
using System.Collections.Generic;
Expand Down Expand Up @@ -29,18 +30,30 @@ public partial class GamesWindow : Window
{
AppEntryModel Apps;
BackgroundWorker bwrLoad;
static LoggingLevelSwitch levelSwitch = new LoggingLevelSwitch();

public GamesWindow()
{
InitializeComponent();
Debug.WriteLine("Init GamesWindow");
Log.Debug("Init GamesWindow");
Apps = new AppEntryModel();
var args = Environment.GetCommandLineArgs();

// Init log file to AppData\Roaming\Briano\UWPHook directory with size rotation on 10Mb with max 5 files
System.Reflection.Assembly assembly = System.Reflection.Assembly.GetExecutingAssembly();
FileVersionInfo fvi = System.Diagnostics.FileVersionInfo.GetVersionInfo(assembly.Location);
string loggerFilePath = String.Join("\\", Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), fvi.CompanyName, fvi.ProductName, "application.log");

Log.Logger = new LoggerConfiguration()
.MinimumLevel.Error()
.WriteTo.File("debug.log", rollingInterval: RollingInterval.Day)
.MinimumLevel.ControlledBy(levelSwitch)
.WriteTo.File(path: loggerFilePath, rollOnFileSizeLimit: true, fileSizeLimitBytes: 10485760, retainedFileCountLimit: 5)
.WriteTo.Console()
.CreateLogger();

// Switch to Info by default to inform logger level in log file and switch to the correct log level
levelSwitch.MinimumLevel = Serilog.Events.LogEventLevel.Information;
SetLogLevel();

// If null or 1, the app was launched normally
if (args?.Length > 1)
{
Expand Down Expand Up @@ -176,6 +189,7 @@ private async void ExportButton_Click(object sender, RoutedEventArgs e)
}
catch (TaskCanceledException exception)
{
Log.Error(exception.Message);
msg = exception.Message;
}

Expand All @@ -202,8 +216,9 @@ private async Task SaveImage(string imageUrl, string destinationFilename, ImageF
{
stream = client.OpenRead(imageUrl);
}
catch (Exception e)
catch (Exception exception)
{
Log.Error(exception.Message);
//Image with error?
//Skip for now
}
Expand Down Expand Up @@ -277,13 +292,14 @@ private async Task DownloadTempGridImages(string appName, string appTarget)
}
catch (TaskCanceledException exception)
{
Log.Error(exception.Message);
throw;
}

if (games != null)
{
var game = games[0];
Debug.WriteLine("Detected Game: " + game.ToString());
Log.Verbose("Detected Game: " + game.ToString());
UInt64 gameId = GenerateSteamGridAppId(appName, appTarget);

if (!Directory.Exists(tmpGridDirectory))
Expand All @@ -296,7 +312,7 @@ private async Task DownloadTempGridImages(string appName, string appTarget)
var gameHeroes = api.GetGameHeroes(game.Id);
var gameLogos = api.GetGameLogos(game.Id);

Debug.WriteLine("Game ID: " + game.Id);
Log.Verbose("Game ID: " + game.Id);

await Task.WhenAll(
gameGridsVertical,
Expand Down Expand Up @@ -360,15 +376,15 @@ private async Task<bool> ExportGames()
List<Task> gridImagesDownloadTasks = new List<Task>();
bool downloadGridImages = !String.IsNullOrEmpty(Properties.Settings.Default.SteamGridDbApiKey);
//To make things faster, decide icons and download grid images before looping users
Debug.WriteLine("downloadGridImages: " + (downloadGridImages));
Log.Verbose("downloadGridImages: " + (downloadGridImages));

foreach (var app in selected_apps)
{
app.Icon = app.widestSquareIcon();

if (downloadGridImages)
{
Debug.WriteLine("Downloading grid images for app " + app.Name);
Log.Verbose("Downloading grid images for app " + app.Name);

gridImagesDownloadTasks.Add(DownloadTempGridImages(app.Name, exePath));
}
Expand All @@ -390,6 +406,7 @@ private async Task<bool> ExportGames()
//If it's a short VDF, let's just overwrite it
if (ex.GetType() != typeof(VDFTooShortException))
{
Log.Error("Error: Program failed to load existing Steam shortcuts." + Environment.NewLine + ex.Message);
throw new Exception("Error: Program failed to load existing Steam shortcuts." + Environment.NewLine + ex.Message);
}
}
Expand Down Expand Up @@ -421,13 +438,13 @@ private async Task<bool> ExportGames()
Boolean isFound = false;
for (int i = 0; i < shortcuts.Length; i++)
{
Debug.WriteLine(shortcuts[i].ToString());
Log.Verbose(shortcuts[i].ToString());


if (shortcuts[i].AppName == app.Name)
{
isFound = true;
Debug.WriteLine(app.Name + " already added to Steam. Updating existing shortcut.");
Log.Verbose(app.Name + " already added to Steam. Updating existing shortcut.");
shortcuts[i] = newApp;
}
}
Expand All @@ -451,12 +468,14 @@ private async Task<bool> ExportGames()
}
catch (Exception ex)
{
Log.Error("Error: Program failed while trying to write your Steam shortcuts" + Environment.NewLine + ex.Message);
throw new Exception("Error: Program failed while trying to write your Steam shortcuts" + Environment.NewLine + ex.Message);
}
}
}
catch (Exception ex)
{
Log.Error("Error: Program failed exporting your games:" + Environment.NewLine + ex.Message + ex.StackTrace);
MessageBox.Show("Error: Program failed exporting your games:" + Environment.NewLine + ex.Message + ex.StackTrace);
}
}
Expand Down Expand Up @@ -517,7 +536,7 @@ private async Task<bool> RestartSteam(bool restartSteam)
string steamExe = steam.MainModule.FileName;

//we always ask politely
Debug.WriteLine("Requesting Steam shutdown");
Log.Debug("Requesting Steam shutdown");
Process.Start(steamExe, "-exitsteam");

bool restarted = false;
Expand All @@ -531,7 +550,7 @@ private async Task<bool> RestartSteam(bool restartSteam)
await Task.Delay(TimeSpan.FromSeconds(0.5f));
if (getSteam() == null)
{
Debug.WriteLine("Restarting Steam");
Log.Debug("Restarting Steam");
Process.Start(steamExe);
restarted = true;
break;
Expand All @@ -540,22 +559,22 @@ private async Task<bool> RestartSteam(bool restartSteam)

if (!restarted)
{
Debug.WriteLine("Steam instance not restarted");
Log.Debug("Steam instance not restarted");
MessageBox.Show("Failed to restart Steam, please launch it manually", "Error", MessageBoxButton.OK, MessageBoxImage.Warning);
return false;
}
}
else
{
Debug.WriteLine("Steam instance not found to be restarted");
Log.Debug("Steam instance not found to be restarted");
}

return true;
}

public static void ClearAllShortcuts()
{
Debug.WriteLine("DBG: Clearing all elements in shortcuts.vdf");
Log.Debug("Clearing all elements in shortcuts.vdf");
string[] tags = Settings.Default.Tags.Split(',');
string steam_folder = SteamManager.GetSteamFolder();

Expand All @@ -582,11 +601,13 @@ public static void ClearAllShortcuts()
}
catch (Exception ex)
{
Log.Error("Error: Program failed while trying to write your Steam shortcuts" + Environment.NewLine + ex.Message);
throw new Exception("Error: Program failed while trying to write your Steam shortcuts" + Environment.NewLine + ex.Message);
}
}
catch (Exception ex)
{
Log.Error("Error: Program failed while trying to clear your Steam shortcuts:" + Environment.NewLine + ex.Message + ex.StackTrace);
MessageBox.Show("Error: Program failed while trying to clear your Steam shortcuts:" + Environment.NewLine + ex.Message + ex.StackTrace);
}
}
Expand Down Expand Up @@ -679,6 +700,7 @@ private void Bwr_DoWork(object sender, DoWorkEventArgs e)
}
catch (Exception ex)
{
Log.Error(ex.Message);
MessageBox.Show(ex.Message, "UWPHook", MessageBoxButton.OK, MessageBoxImage.Error);
}
}
Expand Down Expand Up @@ -732,5 +754,24 @@ private void Window_Loaded(object sender, RoutedEventArgs e)
}
}
}

public static void SetLogLevel()
{
switch (Settings.Default.SelectedLogLevel)
{
case 1:
Log.Information("Init log with DEBUG level.");
levelSwitch.MinimumLevel = Serilog.Events.LogEventLevel.Debug;
break;
case 2:
Log.Information("Init log with TRACE level.");
levelSwitch.MinimumLevel = Serilog.Events.LogEventLevel.Verbose;
break;
default:
Log.Information("Init log with ERROR level.");
levelSwitch.MinimumLevel = Serilog.Events.LogEventLevel.Error;
break;
}
}
}
}
37 changes: 32 additions & 5 deletions UWPHook/Properties/Settings.Designer.cs

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

11 changes: 11 additions & 0 deletions UWPHook/Properties/Settings.settings
Original file line number Diff line number Diff line change
Expand Up @@ -70,5 +70,16 @@
&lt;string&gt;true&lt;/string&gt;
&lt;/ArrayOfString&gt;</Value>
</Setting>
<Setting Name="LogLevel" Type="System.Collections.Specialized.StringCollection" Scope="User">
<Value Profile="(Default)">&lt;?xml version="1.0" encoding="utf-16"?&gt;
&lt;ArrayOfString xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"&gt;
&lt;string&gt;ERROR&lt;/string&gt;
&lt;string&gt;DEBUG&lt;/string&gt;
&lt;string&gt;TRACE&lt;/string&gt;
&lt;/ArrayOfString&gt;</Value>
</Setting>
<Setting Name="SelectedLogLevel" Type="System.String" Scope="User">
<Value Profile="(Default)">0</Value>
</Setting>
</Settings>
</SettingsFile>
Loading

0 comments on commit 826822c

Please sign in to comment.