| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081 |
- using System;
- using System.Diagnostics;
- using System.IO;
- namespace DRG.DRGInterfaceClient
- {
- /// <summary>本地滚动日志:写 DRGInterfaceClient.log,并提供界面订阅、打开、清空。</summary>
- 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<string> 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 { }
- }
- }
- }
- }
|