Przeglądaj źródła

增加日志保存本地

样式分支
fyf 2 lat temu
rodzic
commit
0fef06e22e
4 zmienionych plików z 452 dodań i 6 usunięć
  1. +1
    -0
      BPASmartClient.Helper/BPASmartClient.Helper.csproj
  2. +423
    -0
      BPASmartClient.Helper/logHelper.cs
  3. +25
    -3
      BPASmartClient.ViewModel/LogViewModel.cs
  4. +3
    -3
      BPASmartClient/Control/LogView.xaml

+ 1
- 0
BPASmartClient.Helper/BPASmartClient.Helper.csproj Wyświetl plik

@@ -17,6 +17,7 @@
</ItemGroup>

<ItemGroup>
<PackageReference Include="log4net" Version="2.0.14" />
<PackageReference Include="Microsoft.Win32.Registry" Version="5.0.0" />
<PackageReference Include="Newtonsoft.Json" Version="13.0.1" />
</ItemGroup>


+ 423
- 0
BPASmartClient.Helper/logHelper.cs Wyświetl plik

@@ -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
{
/// <summary>
/// 创建人:奉友福
/// 时间:2021/11/12
/// </summary>
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
/// <summary>
/// 日志显示委托
/// </summary>
public Action<string> 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;

/// <summary>
/// 初始化日志
/// </summary>
/// <param name="path"></param>
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;
}


}

/// <summary>
/// 创建人:奉友福
/// </summary>
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; }
}
}

/// <summary>
/// 创建人:奉友福
/// 时间:2021/11/12
/// </summary>
public enum LogLevel
{
OFF = 0,
FATAL,
ERROR,
WARN,
INFO,
DEBUG,
ALL
}
}

+ 25
- 3
BPASmartClient.ViewModel/LogViewModel.cs Wyświetl plik

@@ -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
/// </summary>
public class LogViewModel :ObservableObject
{
//public DispatcherTimer dispatcherTimer;
public DispatcherTimer dispatcherTimer;
public string ClientId= System.Configuration.ConfigurationManager.AppSettings["ClientId"].ToString();
private ObservableCollection<LogModel> _LogModels;
public ObservableCollection<LogModel> 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<LogModel>();
MessageLog.GetInstance.InfoNotify = new Action<string>((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<string>((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();
}

/// <summary>


+ 3
- 3
BPASmartClient/Control/LogView.xaml Wyświetl plik

@@ -25,9 +25,9 @@

<!--查询按钮栏-->
<StackPanel Orientation="Horizontal" Margin="10,0,10,0">
<CheckBox Margin="10,0,0,0" IsChecked="{Binding RealTimeModel, UpdateSourceTrigger=PropertyChanged}" >实时模式</CheckBox>
<CheckBox Margin="10,0,0,0" IsChecked="{Binding TimedClear, UpdateSourceTrigger=PropertyChanged}">定时清除</CheckBox>
<Button Margin="10,0,0,0" Cursor="Hand" Command="{Binding ExcelCommand}">导出</Button>
<!--<CheckBox Margin="10,0,0,0" IsChecked="{Binding RealTimeModel, UpdateSourceTrigger=PropertyChanged}" >实时模式</CheckBox>
<CheckBox Margin="10,0,0,0" IsChecked="{Binding TimedClear, UpdateSourceTrigger=PropertyChanged}">定时清除</CheckBox>-->
<Button Margin="10,0,0,0" Cursor="Hand" Command="{Binding ExcelCommand}">导出日志</Button>
</StackPanel>

<!--表格栏-->


Ładowanie…
Anuluj
Zapisz