From 0fef06e22e533967136a6e21e4c82dbc8b6378f1 Mon Sep 17 00:00:00 2001 From: fyf Date: Fri, 13 May 2022 11:10:42 +0800 Subject: [PATCH] =?UTF-8?q?=E5=A2=9E=E5=8A=A0=E6=97=A5=E5=BF=97=E4=BF=9D?= =?UTF-8?q?=E5=AD=98=E6=9C=AC=E5=9C=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../BPASmartClient.Helper.csproj | 1 + BPASmartClient.Helper/logHelper.cs | 423 ++++++++++++++++++ BPASmartClient.ViewModel/LogViewModel.cs | 28 +- BPASmartClient/Control/LogView.xaml | 6 +- 4 files changed, 452 insertions(+), 6 deletions(-) create mode 100644 BPASmartClient.Helper/logHelper.cs diff --git a/BPASmartClient.Helper/BPASmartClient.Helper.csproj b/BPASmartClient.Helper/BPASmartClient.Helper.csproj index 576693a5..bb501632 100644 --- a/BPASmartClient.Helper/BPASmartClient.Helper.csproj +++ b/BPASmartClient.Helper/BPASmartClient.Helper.csproj @@ -17,6 +17,7 @@ + diff --git a/BPASmartClient.Helper/logHelper.cs b/BPASmartClient.Helper/logHelper.cs new file mode 100644 index 00000000..8938429f --- /dev/null +++ b/BPASmartClient.Helper/logHelper.cs @@ -0,0 +1,423 @@ +using log4net; +using log4net.Repository; +using System; +using System.Collections.Generic; +using System.Diagnostics; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace BPASmartClient.Helper +{ + /// + /// 创建人:奉友福 + /// 时间:2021/11/12 + /// + public class logHelper + { + #region 单例模式 + static private logHelper m_logHelperInstance = null; + public static logHelper GetLogConfigInstance() + { + if (null == m_logHelperInstance) + { + m_logHelperInstance = new logHelper(); + + } + return m_logHelperInstance; + } + #endregion + /// + /// 日志显示委托 + /// + public Action InfoNotify { get; set; } + private ILog directLogger = null; + private log4net.Appender.RollingFileAppender directRollfileAppender = null; + ILoggerRepository logRepos = null; + private static bool m_isInitDirectLog = false; //是否初始化了直接写入日志文件 + private static Int32 directFileSize = 50; + private static string directLogDir = string.Empty; + private static string directLogFileName = string.Empty; + //static private UAFLogHelper uafLogInstance = null; + private LogLevel logLevel = LogLevel.ALL; + + /// + /// 初始化日志 + /// + /// + public static void Fun_InitLog(string path) + { + try + { + /// 设置需要的日志信息 + GetLogConfigInstance().SetConfigEnableThreadId(true); + GetLogConfigInstance().SetConfigEnableAppDomain(true); + + /// 使用直接日志接口写入日志信息 + GetLogConfigInstance().SetLogLevel(LogLevel.ERROR); + GetLogConfigInstance().SetDirectFileLogInfo(5, string.Empty); + GetLogConfigInstance().SetDirectFileLogName("HBL.LogDir"); + if (!(GetLogConfigInstance().initDirectLogger(path))) + { + + } + } + catch (Exception ex) + { + } + } + public void SetDirectFileLogInfo(Int32 fileSize, string logDirectory) + { + directFileSize = fileSize; + directLogDir = logDirectory; + } + + public void SetDirectFileLogName(string logFileName) + { + directLogFileName = logFileName; + } + + //初始化日志实例 + public bool initDirectLogger(string loggerName) + { + try + { + logRepos = log4net.LogManager.CreateRepository(loggerName); + //初始化记录日志到文件的 appender + InitDirectRollFileAppender(loggerName); + + m_isInitDirectLog = true; + + return true; + } + catch (Exception e) + { + throw e; + } + } + + private void InitDirectRollFileAppender(string loggerName) + { + try + { + directLogger = LogManager.GetLogger(logRepos.Name, loggerName); + //初始化记录日志到文件的 appender + directRollfileAppender = new log4net.Appender.RollingFileAppender(); + + // pattern layout + log4net.Layout.PatternLayout layout = new log4net.Layout.PatternLayout(); + //UAFCustomDataDB.UAFCustomLayout layout = new UAFCustomDataDB.UAFCustomLayout(); + //layout.ConversionPattern = "%log_time %log_threadname %log_ip %-5level %log_domain %log_location %log_msg %log_details%n"; // pattern + + layout.ConversionPattern = string.Empty; + if (LogConfig.GetLogConfigInstance().EnableDate) + { + layout.ConversionPattern += "%date{yyyy-MM-dd HH:mm:ss} "; + } + + //级别 + layout.ConversionPattern += "%-5level "; + + if (LogConfig.GetLogConfigInstance().EnableAppDomain) + { + layout.ConversionPattern += "%a "; + } + + if (LogConfig.GetLogConfigInstance().EnableThreadId) + { + layout.ConversionPattern += "[%t] "; + } + + layout.ConversionPattern += "%m%n"; + + layout.ActivateOptions(); // activate + + //directRollfileAppender.CloseFlag = false; //添加打开标志 + directRollfileAppender.Layout = layout; // layout pattern + //directRollfileAppender.Name = "DirectLogRollFileAppender"; + directRollfileAppender.Name = loggerName; + + directRollfileAppender.File = string.Empty; + + //设置日志文件路径 + if (string.Empty == directLogDir) + { + directRollfileAppender.File = "LogDir\\"; + } + + else + { + if (directLogDir.EndsWith("\\")) + { + directRollfileAppender.File = directLogDir; + } + else + { + directRollfileAppender.File = directLogDir + "\\"; + } + } + //设置日志文件名字 + if (string.Empty == directLogFileName) + { + //获取进程Id,构造日志文件名字 + string loggerFileName = Process.GetCurrentProcess().ProcessName + + Process.GetCurrentProcess().Id.ToString() + "_" + + DateTime.Now.Year.ToString() + + DateTime.Now.Month.ToString() + + DateTime.Now.Day.ToString() + + DateTime.Now.Hour.ToString() + + DateTime.Now.Minute.ToString() + + DateTime.Now.Second.ToString() + + DateTime.Now.Millisecond.ToString() + "_";//"UAFMsgName"; + directRollfileAppender.File += loggerFileName; + } + else + { + directRollfileAppender.File += directLogFileName; + } + + directRollfileAppender.AppendToFile = true; // overwrite any existin g file with the same name + if (directFileSize <= 0) + { + directRollfileAppender.MaxFileSize = (50 * 1024 * 1024); // max file size - 50*1024*1024 = 50MB + } + else + { + directRollfileAppender.MaxFileSize = (directFileSize * 1024 * 1024); + } + + directRollfileAppender.MaxSizeRollBackups = 50; // keep 50 files + directRollfileAppender.ImmediateFlush = true; // flush after every append + directRollfileAppender.Threshold = log4net.Core.Level.All; + directRollfileAppender.DatePattern = "yyyy_M_d'.log'"; + directRollfileAppender.StaticLogFileName = false; + + directRollfileAppender.ActivateOptions(); // activate + + + + // add appenders + //log4net.Config.BasicConfigurator.Configure(directRollfileAppender); + log4net.Config.BasicConfigurator.Configure(logRepos, directRollfileAppender); + } + catch (Exception e) + { + throw e; + } + } + + //重新设置日志保存路径和文件名 + public void ReconfigLogDirAndName() + { + directRollfileAppender.File = string.Empty; + + //设置日志文件路径 + if (string.Empty == directLogDir) + { + directRollfileAppender.File = "LogDir\\"; + } + + else + { + if (directLogDir.EndsWith("\\")) + { + directRollfileAppender.File = directLogDir; + } + else + { + directRollfileAppender.File = directLogDir + "\\"; + } + } + //设置日志文件名字 + if (string.Empty == directLogFileName) + { + //获取进程Id,构造日志文件名字 + string loggerFileName = Process.GetCurrentProcess().ProcessName + + Process.GetCurrentProcess().Id.ToString() + "_" + + DateTime.Now.Year.ToString() + + DateTime.Now.Month.ToString() + + DateTime.Now.Day.ToString() + + DateTime.Now.Hour.ToString() + + DateTime.Now.Minute.ToString() + + DateTime.Now.Second.ToString() + + DateTime.Now.Millisecond.ToString() + "_";//"UAFMsgName"; + directRollfileAppender.File += loggerFileName; + } + else + { + directRollfileAppender.File += directLogFileName; + } + + if (directFileSize <= 0) + { + directRollfileAppender.MaxFileSize = (50 * 1024 * 1024); // max file size - 50*1024*1024 = 50MB + } + else + { + directRollfileAppender.MaxFileSize = (directFileSize * 1024 * 1024); + } + + directRollfileAppender.ActivateOptions(); // activate + } + + public void SetLogLevel(LogLevel level) + { + logLevel = level; + + } + + public bool WriteLog(LogLevel level, string logMsg) + { + try + { + if (null == directLogger) + { + return false; + } + + //if ((LogLevel.OFF == logLevel) || ((Int32)level > (Int32)logLevel /*&& LogObjectLib.LogLevel.ALL != logLevel*/)) + //{ + // return true; + //} + + //调用日志接口直接写日志信息 + switch (level) + { + case LogLevel.FATAL: + if (directLogger.IsFatalEnabled) + { + directLogger.Fatal(logMsg); + } + break; + case LogLevel.ERROR: + if (directLogger.IsErrorEnabled) + { + directLogger.Error(logMsg); + } + break; + case LogLevel.WARN: + if (directLogger.IsWarnEnabled) + { + directLogger.Warn(logMsg); + } + break; + case LogLevel.INFO: + if (directLogger.IsInfoEnabled) + { + directLogger.Info(logMsg); + } + break; + case LogLevel.DEBUG: + if (directLogger.IsDebugEnabled) + { + directLogger.Debug(logMsg); + } + break; + default: + break; + } + if (InfoNotify != null) + { + logMsg = $"{DateTime.Now.ToString("HH:mm:ss")}:{level} {logMsg} \n\r"; + InfoNotify(logMsg); + } + return true; + } + catch (Exception e) + { + throw e; + } + + + } + + //设置日志配置--app域名 + public void SetConfigEnableAppDomain(bool value) + { + LogConfig.GetLogConfigInstance().EnableAppDomain = value; + } + + //设置日志配置--线程id + public void SetConfigEnableThreadId(bool value) + { + LogConfig.GetLogConfigInstance().EnableThreadId = value; + } + + public bool GetConfigEnableAppDomain() + { + return LogConfig.GetLogConfigInstance().EnableAppDomain; + } + + public bool GetConfigEnableThreadId() + { + return LogConfig.GetLogConfigInstance().EnableThreadId; + } + + + } + + /// + /// 创建人:奉友福 + /// + public class LogConfig + { + private bool m_enableDate = true; + private bool m_enableAppDomain = false; + private bool m_enableThreadId = false; + #region 单例模式 + static private LogConfig m_logConfigInstance = null; + public static LogConfig GetLogConfigInstance() + { + if (null == m_logConfigInstance) + { + m_logConfigInstance = new LogConfig(); + + } + return m_logConfigInstance; + } + #endregion + private LogConfig() + { + + } + public bool EnableDate + { + set + { + m_enableDate = value; + } + get { return m_enableDate; } + } + public bool EnableAppDomain + { + set + { + m_enableAppDomain = value; + } + get { return m_enableAppDomain; } + } + public bool EnableThreadId + { + set + { + m_enableThreadId = value; + } + get { return m_enableThreadId; } + } + } + + /// + /// 创建人:奉友福 + /// 时间:2021/11/12 + /// + public enum LogLevel + { + OFF = 0, + FATAL, + ERROR, + WARN, + INFO, + DEBUG, + ALL + } +} diff --git a/BPASmartClient.ViewModel/LogViewModel.cs b/BPASmartClient.ViewModel/LogViewModel.cs index 24fb7ce7..d4dea169 100644 --- a/BPASmartClient.ViewModel/LogViewModel.cs +++ b/BPASmartClient.ViewModel/LogViewModel.cs @@ -1,4 +1,5 @@ -using BPASmartClient.IoT; +using BPASmartClient.Helper; +using BPASmartClient.IoT; using BPASmartClient.Message; using Microsoft.Toolkit.Mvvm.ComponentModel; using Microsoft.Toolkit.Mvvm.Input; @@ -22,7 +23,7 @@ namespace BPASmartClient.ViewModel /// public class LogViewModel :ObservableObject { - //public DispatcherTimer dispatcherTimer; + public DispatcherTimer dispatcherTimer; public string ClientId= System.Configuration.ConfigurationManager.AppSettings["ClientId"].ToString(); private ObservableCollection _LogModels; public ObservableCollection LogDataGrid @@ -43,13 +44,18 @@ namespace BPASmartClient.ViewModel public static LogViewModel GetInstance() => _Instance ?? (_Instance = new LogViewModel()); private LogViewModel() { - if(LogDataGrid==null) + //3.初始化日志 + logHelper.Fun_InitLog(System.AppDomain.CurrentDomain.BaseDirectory); + + + if (LogDataGrid==null) LogDataGrid = new ObservableCollection(); MessageLog.GetInstance.InfoNotify = new Action((s) => { System.Windows.Application.Current?.Dispatcher.Invoke((Action)(() => { LogDataGrid.Insert(0,new LogModel { message = s,type = "Info" }); + logHelper.GetLogConfigInstance().WriteLog(LogLevel.INFO, s); })); }); MessageLog.GetInstance.ExInfoNotify = new Action((s) => @@ -57,6 +63,7 @@ namespace BPASmartClient.ViewModel System.Windows.Application.Current?.Dispatcher.Invoke((Action)(() => { LogDataGrid.Insert(0,new LogModel { message = s,type = "Error" }); + logHelper.GetLogConfigInstance().WriteLog(LogLevel.ERROR, s); DataVClient.GetInstance().HttpAddLog(new LogTable { ClientId = ClientId, @@ -71,6 +78,21 @@ namespace BPASmartClient.ViewModel { ExcellOrder(); }); + + dispatcherTimer = new DispatcherTimer(); + dispatcherTimer.Tick += delegate + { + System.Windows.Application.Current?.Dispatcher.Invoke((Action)(() => + { + if (LogDataGrid.Count > 100) + { + LogDataGrid.RemoveAt(LogDataGrid.Count-1); + } + })); + + }; + dispatcherTimer.Interval = TimeSpan.FromSeconds(10); + dispatcherTimer.Start(); } /// diff --git a/BPASmartClient/Control/LogView.xaml b/BPASmartClient/Control/LogView.xaml index a4918f84..0f50aa06 100644 --- a/BPASmartClient/Control/LogView.xaml +++ b/BPASmartClient/Control/LogView.xaml @@ -25,9 +25,9 @@ - 实时模式 - 定时清除 - + +