using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Xml.Serialization; using TransportGame.Business; using TransportGame.Model; namespace TransportGame.Utils { public static class Logger { public static readonly string LogsDirectory = "Logs"; private static string logFile = null; public enum Level { Info, Warning, Error, Critical } public static void Log(Level level, string format, params object[] args) { // Open log file if not opened if (logFile == null) { // Create logs folder if (!Directory.Exists(LogsDirectory)) Directory.CreateDirectory(LogsDirectory); // Create log file logFile = Path.Combine(LogsDirectory, String.Format("{0:s}.log", DateTime.Now).Replace(':', '_')); } lock (logFile) { using (var writer = new StreamWriter(logFile, true)) { // Log to file writer.Write("[{0}] ", Enum.GetName(typeof(Level), level)); writer.Write(DateTime.Now.ToString("%HH:%mm:%ss.%FFF")); writer.WriteLine(": " + format, args); writer.Close(); } // Log to unity switch (level) { case Level.Warning: UnityEngine.Debug.LogWarning(String.Format(format, args)); break; case Level.Error: UnityEngine.Debug.LogError(String.Format(format, args)); break; case Level.Critical: UnityEngine.Debug.LogError(String.Format(format, args)); break; } } } public static void Info(string format, params object[] args) { Log(Level.Info, format, args); } public static void Warning(string format, params object[] args) { Log(Level.Warning, format, args); } public static void Error(string format, params object[] args) { Log(Level.Error, format, args); } public static void Critical(string format, params object[] args) { Log(Level.Critical, format, args); } public static void Exception(Exception ex) { Log(Level.Critical, "{0}: {1}\nStack trace:{2}", ex.GetType().ToString(), ex.Message, ex.StackTrace); } public static void DumpMap(Map map, string filename) { map.SerializeXml(Path.Combine(LogsDirectory, filename)); } } }