@@ -47,6 +47,8 @@ public class MyApplicationContext : ApplicationContext
4747 private int lastBattery = 100 ;
4848
4949 private bool lightMode = false ;
50+ private readonly string logFilePath = Path . Combine ( Environment . GetFolderPath ( Environment . SpecialFolder . LocalApplicationData ) , "XBatteryStatus" , "log.txt" ) ;
51+ private readonly System . Threading . SemaphoreSlim logSemaphore = new System . Threading . SemaphoreSlim ( 1 , 1 ) ;
5052
5153 public MyApplicationContext ( )
5254 {
@@ -60,6 +62,7 @@ public MyApplicationContext()
6062 string versionString = Assembly . GetExecutingAssembly ( ) . GetCustomAttribute < AssemblyInformationalVersionAttribute > ( ) ? . InformationalVersion ?? "0.0.0" ;
6163 version = NuGetVersion . Parse ( versionString ) ;
6264
65+ Log ( $ "XBatteryStatus V{ versionString } started") ;
6366
6467 HideTimeoutTimer = new Timer ( ) ;
6568 HideTimeoutTimer . Tick += new EventHandler ( ( x , y ) => HideTimeout ( ) ) ;
@@ -454,6 +457,9 @@ private void Exit()
454457 }
455458
456459 notifyIcon . Visible = false ;
460+
461+ logSemaphore ? . Dispose ( ) ;
462+
457463 ToastNotificationManagerCompat . History . Clear ( ) ;
458464 Application . Exit ( ) ;
459465 }
@@ -730,20 +736,38 @@ public static bool IsStoreInstall()
730736 }
731737 }
732738
733- private void Log ( string s )
739+ private async void Log ( string s )
734740 {
735741#if DEBUG
736742 Console . WriteLine ( s ) ;
743+ #else
744+ await logSemaphore . WaitAsync ( ) ;
745+ try
746+ {
747+ string logDirectory = Path . GetDirectoryName ( logFilePath ) ;
748+ if ( ! Directory . Exists ( logDirectory ) )
749+ {
750+ Directory . CreateDirectory ( logDirectory ) ;
751+ }
752+
753+ string logEntry = $ "[{ DateTime . Now : dd.MM.yyyy HH:mm:ss} ] { s } ";
754+ await File . AppendAllTextAsync ( logFilePath , logEntry + Environment . NewLine ) ;
755+ }
756+ catch
757+ {
758+ }
759+ finally
760+ {
761+ logSemaphore . Release ( ) ;
762+ }
737763#endif
738764 }
739765
740766 private void LogError ( Exception e )
741767 {
742- #if DEBUG
743768 Log ( e . StackTrace ) ;
744769 Log ( e . Message ) ;
745770 Log ( "" ) ;
746- #endif
747771 }
748772 }
749773}
0 commit comments