using System;
using System.Diagnostics;
using System.IO;
namespace DRG.DRGInterfaceClient
{
/// 本地滚动日志:写 DRGInterfaceClient.log,并提供界面订阅、打开、清空。
internal static class Logger
{
private static readonly string LogPath =
Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "DRGInterfaceClient.log");
private static readonly object _lock = new object();
public static event Action OnLog;
public static void Info(string msg) { Write("INFO", msg); }
public static void Warn(string msg) { Write("WARN", msg); }
public static void Error(string msg, Exception ex = null)
{
string m = msg;
if (ex != null) m += " | " + ex.GetType().Name + ": " + ex.Message;
Write("ERROR", m);
}
private static void Write(string level, string msg)
{
string line = string.Format("[{0}] [{1}] {2}",
DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff"), level, msg);
lock (_lock)
{
try
{
RollIfNeeded();
File.AppendAllText(LogPath, line + Environment.NewLine);
}
catch { }
}
try { OnLog?.Invoke(line); } catch { }
}
private static void RollIfNeeded()
{
try
{
if (File.Exists(LogPath))
{
long size = new FileInfo(LogPath).Length;
long max = (long)Config.Current.MaxLogSizeMB * 1024 * 1024;
if (size > max)
{
string bak = LogPath + ".1";
if (File.Exists(bak)) File.Delete(bak);
File.Move(LogPath, bak);
}
}
}
catch { }
}
public static string ReadAll()
{
try { return File.Exists(LogPath) ? File.ReadAllText(LogPath) : ""; }
catch { return ""; }
}
public static void OpenLogFile()
{
try { Process.Start(LogPath); }
catch (Exception ex) { Error("打开日志文件失败", ex); }
}
public static void Clear()
{
lock (_lock)
{
try { if (File.Exists(LogPath)) File.WriteAllText(LogPath, ""); }
catch { }
}
}
}
}