using MetroLog; using MetroLog.Layouts; using MetroLog.Targets; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Windows.Storage; using Windows.System; namespace KdanCommon.Log { public sealed class MetroLogService { private static MetroLogService _instance = new MetroLogService(); public static MetroLogService Instance { get { return _instance; } } public LogLevel MinLevel = LogLevel.Trace; public LogLevel MaxLevel = LogLevel.Fatal; private ILogManager currentLogManager = null; public bool IsWriteLog = true; private MetroLogService() { } public void Init(string appName, bool isWriteLog = true) { IsWriteLog = isWriteLog; var customLogLayout = new CustomLogLayout(appName); var loggingConfiguration = new LoggingConfiguration { IsEnabled = true }; loggingConfiguration.AddTarget(MinLevel, MaxLevel, new StreamingFileTarget(customLogLayout)); currentLogManager = LogManagerFactory.CreateLogManager(loggingConfiguration); } private ILogger GetCurrentLogger() { return currentLogManager.GetLogger(); } public void WriteTraceLog(string msg, Exception ex = null) { System.Diagnostics.Debug.Write(msg + " " + ex); if (!IsWriteLog) return; var log = GetCurrentLogger(); log.Trace(msg, ex); } public void WriteDebugLog(string msg, Exception ex = null) { System.Diagnostics.Debug.Write(msg + " " + ex); if (!IsWriteLog) return; var log = GetCurrentLogger(); log.Debug(msg, ex); } public void WriteInfoLog(string msg, Exception ex = null) { System.Diagnostics.Debug.Write(msg + " " + ex); if (!IsWriteLog) return; var log = GetCurrentLogger(); log.Info(msg, ex); } public void WriteWarnLog(string msg, Exception ex = null) { System.Diagnostics.Debug.Write(msg + " " + ex); if (!IsWriteLog) return; var log = GetCurrentLogger(); log.Warn(msg, ex); } public void WriteErrorLog(string msg, Exception ex = null) { System.Diagnostics.Debug.Write(msg + " " + ex); if (!IsWriteLog) return; var log = GetCurrentLogger(); log.Error(msg, ex); } public void WriteFatalLog(string msg, Exception ex = null) { System.Diagnostics.Debug.Write(msg + " " + ex); if (!IsWriteLog) return; var log = GetCurrentLogger(); log.Fatal(msg, ex); } public async Task OpenLogFolder() { var tmpFolder = await ApplicationData.Current.LocalFolder.CreateFolderAsync("MetroLogs", CreationCollisionOption.OpenIfExists); if (tmpFolder != null) await Launcher.LaunchFolderAsync(tmpFolder); } } public class CustomLogLayout : Layout { private string _appName; public CustomLogLayout(string appName) { _appName = appName; } public override string GetFormattedString(LogWriteContext context, LogEventInfo info) { return $"{_appName}|{info.TimeStamp.LocalDateTime}|{info.Level}|{info.Logger}|{info.Message}|{info.Exception}"; } } }