|
| 1 | +using System; |
| 2 | +using System.Runtime.InteropServices; |
| 3 | +using System.IO; |
| 4 | +using System.Reflection; |
| 5 | +using System.Linq; |
| 6 | +using System.Threading.Tasks; |
| 7 | +using Windows.Storage; |
| 8 | + |
| 9 | +using log4net; |
| 10 | +using log4net.Config; |
| 11 | +using log4net.Appender; |
| 12 | + |
| 13 | +using ITHit.FileSystem.Windows; |
| 14 | + |
| 15 | +namespace ITHit.FileSystem.Samples.Common.Windows |
| 16 | +{ |
| 17 | + /// <summary> |
| 18 | + /// Outputs logging. |
| 19 | + /// </summary> |
| 20 | + public class LogFormatter |
| 21 | + { |
| 22 | + /// <summary> |
| 23 | + /// Log file path. |
| 24 | + /// </summary> |
| 25 | + public readonly string LogFilePath; |
| 26 | + |
| 27 | + /// <summary> |
| 28 | + /// Indicates if more debugging and performance information should be logged. |
| 29 | + /// </summary> |
| 30 | + public bool DebugLoggingEnabled |
| 31 | + { |
| 32 | + get { return debugLoggingEnabled; } |
| 33 | + set |
| 34 | + { |
| 35 | + debugLoggingEnabled = value; |
| 36 | + string debugLoggingState = debugLoggingEnabled ? "Enabled" : "Disabled"; |
| 37 | + log.Info($"{Environment.NewLine}Debug logging {debugLoggingState}"); |
| 38 | + } |
| 39 | + } |
| 40 | + |
| 41 | + public bool debugLoggingEnabled = false; |
| 42 | + |
| 43 | + private readonly ILog log; |
| 44 | + |
| 45 | + private readonly string appId; |
| 46 | + |
| 47 | + /// <summary> |
| 48 | + /// Creates instance of this class. |
| 49 | + /// </summary> |
| 50 | + /// <param name="log">Log4net logger.</param> |
| 51 | + public LogFormatter(ILog log, string appId) |
| 52 | + { |
| 53 | + this.log = log; |
| 54 | + this.appId = appId; |
| 55 | + LogFilePath = ConfigureLogger(); |
| 56 | + } |
| 57 | + |
| 58 | + /// <summary> |
| 59 | + /// Configures log4net logger. |
| 60 | + /// </summary> |
| 61 | + /// <returns>Log file path.</returns> |
| 62 | + private string ConfigureLogger() |
| 63 | + { |
| 64 | + // Load Log4Net for net configuration. |
| 65 | + var logRepository = LogManager.GetRepository(Assembly.GetEntryAssembly()); |
| 66 | + XmlConfigurator.Configure(logRepository, new FileInfo(Path.Combine(Path.GetDirectoryName(Assembly.GetEntryAssembly().Location), "log4net.config"))); |
| 67 | + |
| 68 | + // Update log file path for msix package. |
| 69 | + RollingFileAppender rollingFileAppender = logRepository.GetAppenders().Where(p => p.GetType() == typeof(RollingFileAppender)).FirstOrDefault() as RollingFileAppender; |
| 70 | + if (rollingFileAppender != null && rollingFileAppender.File.Contains("WindowsApps")) |
| 71 | + { |
| 72 | + rollingFileAppender.File = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData), appId, |
| 73 | + Path.GetFileName(rollingFileAppender.File)); |
| 74 | + } |
| 75 | + return rollingFileAppender?.File; |
| 76 | + } |
| 77 | + |
| 78 | + /// <summary> |
| 79 | + /// Prints environment description. |
| 80 | + /// </summary> |
| 81 | + public void PrintEnvironmentDescription() |
| 82 | + { |
| 83 | + // Log environment description. |
| 84 | + log.Info($"\n{"AppID:",-15} {appId}"); |
| 85 | + log.Info($"\n{"Engine version:",-15} {typeof(IEngine).Assembly.GetName().Version}"); |
| 86 | + log.Info($"\n{"OS version:",-15} {RuntimeInformation.OSDescription}"); |
| 87 | + log.Info($"\n{"Env version:",-15} {RuntimeInformation.FrameworkDescription} {IntPtr.Size * 8}bit."); |
| 88 | + //log.Info($"\n{"Is UWP:",-15} {PackageRegistrar.IsRunningAsUwp()}"); |
| 89 | + log.Info($"\n{"Admin mode:",-15} {new System.Security.Principal.WindowsPrincipal(System.Security.Principal.WindowsIdentity.GetCurrent()).IsInRole(System.Security.Principal.WindowsBuiltInRole.Administrator)}"); |
| 90 | + } |
| 91 | + |
| 92 | + /// <summary> |
| 93 | + /// Prints indexing state. |
| 94 | + /// </summary> |
| 95 | + /// <param name="path">File system path.</param> |
| 96 | + public async Task PrintIndexingStateAsync(string path) |
| 97 | + { |
| 98 | + StorageFolder userFileSystemRootFolder = await StorageFolder.GetFolderFromPathAsync(path); |
| 99 | + log.Info($"\nIndexed state: {(await userFileSystemRootFolder.GetIndexedStateAsync())}"); |
| 100 | + } |
| 101 | + |
| 102 | + /// <summary> |
| 103 | + /// Prints console commands. |
| 104 | + /// </summary> |
| 105 | + public void PrintHelp() |
| 106 | + { |
| 107 | + log.Info("\n\nPress Esc to unregister file system, delete all files/folders and exit (simulate uninstall)."); |
| 108 | + log.Info("\nPress Spacebar to exit without unregistering (simulate reboot)."); |
| 109 | + log.Info("\nPress 'p' to unregister sparse package."); |
| 110 | + log.Info("\nPress 'e' to start/stop the Engine and all sync services."); |
| 111 | + log.Info("\nPress 's' to start/stop full synchronization service."); |
| 112 | + log.Info("\nPress 'm' to start/stop remote storage monitor."); |
| 113 | + log.Info("\nPress 'd' to enable/disable debug and performance logging."); |
| 114 | + log.Info($"\nPress 'l' to open log file. ({LogFilePath})"); |
| 115 | + log.Info($"\nPress 'b' to submit support tickets, report bugs, suggest features. (https://userfilesystem.com/support/)"); |
| 116 | + log.Info("\n----------------------\n"); |
| 117 | + } |
| 118 | + |
| 119 | + public void LogError(IEngine sender, EngineErrorEventArgs e) |
| 120 | + { |
| 121 | + WriteLog(e, log4net.Core.Level.Error); |
| 122 | + } |
| 123 | + |
| 124 | + public void LogMessage(IEngine sender, EngineMessageEventArgs e) |
| 125 | + { |
| 126 | + WriteLog(e, log4net.Core.Level.Info); |
| 127 | + } |
| 128 | + |
| 129 | + public void LogDebug(IEngine sender, EngineMessageEventArgs e) |
| 130 | + { |
| 131 | + WriteLog(e, log4net.Core.Level.Debug); |
| 132 | + } |
| 133 | + |
| 134 | + /// <summary> |
| 135 | + /// Outputs log message. |
| 136 | + /// </summary> |
| 137 | + /// <param name="log">log4net</param> |
| 138 | + /// <param name="e">Message or error description.</param> |
| 139 | + /// <param name="level">Log level.</param> |
| 140 | + private void WriteLog(EngineMessageEventArgs e, log4net.Core.Level level) |
| 141 | + { |
| 142 | + string att = FsPath.Exists(e.SourcePath) ? FsPath.GetAttString(e.SourcePath) : null; |
| 143 | + string process = null; |
| 144 | + byte? priorityHint = null; |
| 145 | + ulong? clientFileId = null; |
| 146 | + string size = null; |
| 147 | + |
| 148 | + if (e.OperationContext != null) |
| 149 | + { |
| 150 | + process = System.IO.Path.GetFileName(e.OperationContext.ProcessInfo?.ImagePath); |
| 151 | + priorityHint = e.OperationContext.PriorityHint; |
| 152 | + clientFileId = (e.OperationContext as IWindowsOperationContext).FileId; |
| 153 | + size = FsPath.FormatBytes((e.OperationContext as IWindowsOperationContext).FileSize); |
| 154 | + } |
| 155 | + |
| 156 | + string message = Format(DateTimeOffset.Now.ToString("hh:mm:ss.fff"), process, priorityHint?.ToString(), e.ComponentName, e.Message, e.SourcePath, att, e.TargetPath); |
| 157 | + |
| 158 | + if (level == log4net.Core.Level.Error) |
| 159 | + { |
| 160 | + Exception ex = ((EngineErrorEventArgs)e).Exception; |
| 161 | + message += Environment.NewLine; |
| 162 | + log.Error(message, ex); |
| 163 | + } |
| 164 | + else if (level == log4net.Core.Level.Info) |
| 165 | + { |
| 166 | + log.Info(message); |
| 167 | + } |
| 168 | + else if (level == log4net.Core.Level.Debug && DebugLoggingEnabled) |
| 169 | + { |
| 170 | + log.Debug(message); |
| 171 | + } |
| 172 | + |
| 173 | + } |
| 174 | + |
| 175 | + private static string Format(string date, string process, string priorityHint, string componentName, string message, string sourcePath, string attributes, string targetPath) |
| 176 | + { |
| 177 | + return $"{Environment.NewLine}|{date, -12}| {process,-25}| {priorityHint,-5}| {componentName,-26}| {message,-45}| {sourcePath,-80}| {attributes, -22}| {targetPath}"; |
| 178 | + } |
| 179 | + |
| 180 | + /// <summary> |
| 181 | + /// Prints logging data headers. |
| 182 | + /// </summary> |
| 183 | + public void PrintHeader() |
| 184 | + { |
| 185 | + log.Info(Format("Time", "Process Name", "Prty", "Component", "Operation", "Source Path", "Attributes", "Target Path")); |
| 186 | + log.Info(Format("----", "------------", "----", "---------", "---------", "-----------", "----------", "-----------")); |
| 187 | + } |
| 188 | + } |
| 189 | +} |
0 commit comments