增加日志

master
mzhifa 8 months ago
parent 8997ccec41
commit 77524c71de

@ -1,5 +1,7 @@
using Prism.Ioc;
using Prism.Regions;
using System.IO;
using System;
using System.Text.Json;
using System.Windows;
using Txgy.FilesWatcher.model;
@ -15,6 +17,8 @@ namespace Txgy.FilesWatcher
{
protected override Window CreateShell()
{
var path = AppDomain.CurrentDomain.BaseDirectory + @"log4net.config";
log4net.Config.XmlConfigurator.Configure(new FileInfo(path));
return Container.Resolve<MainWindow>();
}

@ -15,6 +15,7 @@
<ItemGroup>
<PackageReference Include="Dapper" Version="2.1.21" />
<PackageReference Include="HandyControl" Version="3.4.0" />
<PackageReference Include="log4net" Version="2.0.17" />
<PackageReference Include="MQTTnet.Extensions.ManagedClient" Version="3.0.5" />
<PackageReference Include="MySql.Data" Version="8.2.0" />
<PackageReference Include="Prism.DryIoc" Version="8.1.97" />
@ -24,6 +25,9 @@
<Resource Include="Views\Upload Database.png" />
</ItemGroup>
<ItemGroup>
<None Update="log4net.config">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</None>
<None Update="systemconfig.json">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</None>

@ -28,6 +28,8 @@ using System.Windows.Markup;
using System.Windows.Forms.VisualStyles;
using System.Xml.Linq;
using Prism.Services.Dialogs;
using Microsoft.VisualBasic.Logging;
using log4net;
namespace Txgy.FilesWatcher.ViewModels
{
@ -35,6 +37,7 @@ namespace Txgy.FilesWatcher.ViewModels
{
public MainViewModel(WebsocketClient websocketClient, SystemConfig systemConfig, IEventAggregator ea, IDialogService dialogService, ManualModeDialogViewModel manualModeDialog)
{
_log = new GetLogger("MainViewModel");
StartCommand = new DelegateCommand(Start, StartCanExecute).ObservesProperty(() => StartEnable);
StopCommand= new DelegateCommand(Stop, StopCanExecute).ObservesProperty(() => StopEnable);
string filter = "*.index";
@ -56,7 +59,7 @@ namespace Txgy.FilesWatcher.ViewModels
this._dialogService = dialogService;
this._manualModeDialog = manualModeDialog;
}
private GetLogger _log;
private string watcherPath;
public string PostPath
@ -267,6 +270,7 @@ namespace Txgy.FilesWatcher.ViewModels
public DelegateCommand ManualCommand => new DelegateCommand(() =>
{
_log.Log.Debug("MainViewModel.ManualCommand,打开");
DialogParameters param = new DialogParameters
{
{ "main", this }
@ -278,7 +282,7 @@ namespace Txgy.FilesWatcher.ViewModels
});
private void Start()
{
int res= WatchStartOrSopt(true);
int res = WatchStartOrSopt(true);
if (res == 0)
{
StartEnable = false;
@ -434,7 +438,7 @@ namespace Txgy.FilesWatcher.ViewModels
mqttClient = new MqttFactory().CreateManagedMqttClient();
mqttClient.UseDisconnectedHandler(ee =>
{
Debug.WriteLine($">>> 服务器断开连接,{ee}");
_log.Log.Debug($">>> 服务器断开连接,{ee}");
});
mqttClient.UseApplicationMessageReceivedHandler(ee =>
{
@ -514,6 +518,8 @@ namespace Txgy.FilesWatcher.ViewModels
private void MseedFileChanged(DateTime currentT)
{
_log.Log.Debug("MainViewModel.MseedFileChanged() > enter....");
_log.Log.DebugFormat("MainViewModel.MseedFileChanged() currentT:{0}", currentT);
string path = $"{Path.Combine(MainPath, MseedPath)}/{currentT.Month.ToString("D2")}/{currentT.Day.ToString("D2")}/{currentT.Hour.ToString("D2")}/{currentT.AddMinutes(-2).Minute.ToString("D2")}";
Debug.WriteLine($"**********当前时间:{currentT},监控路径:{path}");
if (Directory.Exists(path) && IsUploadDB && IsUploadMseedPath)
@ -531,6 +537,8 @@ namespace Txgy.FilesWatcher.ViewModels
});
}), path, WorkAreaId);
}
_log.Log.Debug("MainViewModel.MseedFileChanged() < exit....");
}
@ -605,7 +613,8 @@ namespace Txgy.FilesWatcher.ViewModels
var watch= sender as FileSystemWatcher;
string lastLine = File.ReadLines(e.FullPath).Last().Trim();
Debug.WriteLine($"最后修改时间:{lastWriteTime},文件路径:{watch.Path}");
var filePath= Path.GetDirectoryName(e.FullPath);
_log.Log.DebugFormat($"MainViewModel.Watcher_Changed() 最后修改时间:{lastWriteTime},文件路径:{watch.Path}");
var filePath = Path.GetDirectoryName(e.FullPath);
if (watch != null && watch.Path == watcherArray[0].Path)
{
watcherArray[0].EnableRaisingEvents = false;
@ -727,7 +736,6 @@ namespace Txgy.FilesWatcher.ViewModels
private void Watcher_Deleted(object sender, FileSystemEventArgs e)
{
DateTime dt = DateTime.Now;
string tmp = dt.Hour.ToString() + "时" + dt.Minute.ToString() + "分" + dt.Second.ToString() + "秒" + dt.Millisecond.ToString() + "毫秒,目录发生变化\r\n";
tmp += "改变类型 :" + e.ChangeType.ToString() + "\r\n"; ;
@ -744,8 +752,9 @@ namespace Txgy.FilesWatcher.ViewModels
private void StartConnectMQ()
{
_log.Log.Debug("MainViewModel.StartConnectMQ() > enter....");
// 向服务端开放的端口进行服务请求
// string clientID = Guid.NewGuid().ToString();
// string clientID = Guid.NewGuid().ToString();
var mqttClientOptions = new MqttClientOptionsBuilder()
.WithClientId(_systemConfig.mQTTConfig.clientID)// 传入ClientID参数
.WithTcpServer(_systemConfig.mQTTConfig.serverIP, _systemConfig.mQTTConfig.port)//指定TCP连接的IP和Port
@ -757,6 +766,7 @@ namespace Txgy.FilesWatcher.ViewModels
.Build();
mqttClient.StartAsync(options);
startTime = DateTime.Now;
_log.Log.Debug("MainViewModel.StartConnectMQ() < exit....");
}
private void StopMQ()
{
@ -764,7 +774,9 @@ namespace Txgy.FilesWatcher.ViewModels
}
private void MQPublish(string topic, string openCmd)
{
// byte[] cmdByte = Convert.FromHexString(openCmd.Replace(" ", ""));
_log.Log.Debug("MainViewModel.MQPublish() > enter....");
_log.Log.DebugFormat("MainViewModel.MQPublish() topic:{0},cmd:{1}", topic, openCmd);
// byte[] cmdByte = Convert.FromHexString(openCmd.Replace(" ", ""));
MqttApplicationMessage message = new MqttApplicationMessageBuilder()
.WithTopic(topic)
.WithPayload(openCmd)
@ -781,6 +793,7 @@ namespace Txgy.FilesWatcher.ViewModels
mes = $">>>数据发送失败:{topic},{openCmd}";
}
Debug.WriteLine(mes);
_log.Log.Debug("MainViewModel.MQPublish() < exit....");
}
@ -822,6 +835,9 @@ namespace Txgy.FilesWatcher.ViewModels
private bool CMDStartProcess(ProcessInfo proInfo, string path)
{
_log.Log.Debug("MainViewModel.CMDStartProcess() > enter....");
_log.Log.DebugFormat("MainViewModel.CMDStartProcess() proInfo:{0},path:{1}", proInfo.ProName, path);
Process process = new Process();
process.Exited += Process_Exited;
process.EnableRaisingEvents = true;
@ -838,17 +854,18 @@ namespace Txgy.FilesWatcher.ViewModels
process.ErrorDataReceived += new DataReceivedEventHandler(OutputHandler);
bool res = process.Start();
_log.Log.Debug("MainViewModel.CMDStartProcess() < exit....");
return res;
}
private void Process_Exited(object? sender, EventArgs e)
{
_log.Log.Debug("MainViewModel.Process_Exited()");
}
void OutputHandler(object sendingProcess, DataReceivedEventArgs outLine)
{
Debug.WriteLine("output*************:{0},{1}", sendingProcess.ToString(), outLine.Data);
_log.Log.DebugFormat("MainViewModel.OutputHandler() output:{0},{1}", sendingProcess.ToString(), outLine.Data);
if (string.IsNullOrEmpty(outLine.Data)) return;
}
#endregion

@ -27,9 +27,10 @@ namespace Txgy.FilesWatcher.ViewModels
{
public ManualModeDialogViewModel(IEventAggregator ea)
{
_log = new GetLogger("ManualModeDialogViewModel");
_log.Log.Debug("ManualModeDialogViewModel() ...");
}
private GetLogger _log;
public string Title => "手动模式";
public event Action<IDialogResult> RequestClose;
@ -104,6 +105,8 @@ namespace Txgy.FilesWatcher.ViewModels
CancellationTokenSource cts = new CancellationTokenSource();
public async Task StartHandle(DateTime start, DateTime end)
{
_log.Log.Debug("ManualModeDialogViewModel.StartHandle() > enter...");
_log.Log.DebugFormat("ManualModeDialogViewModel.StartHandle() start:{0},end:{1}",start, end);
CancellationToken cancellationToken = cts.Token;
string realtimePath = Path.Combine(mainModel.MainPath, mainModel.RealtimePath);
string postPath = Path.Combine(mainModel.MainPath, mainModel.PostPath);
@ -155,6 +158,7 @@ namespace Txgy.FilesWatcher.ViewModels
}
}, cancellationToken);
await Task.WhenAll(task1, task2, task3);
_log.Log.Debug("ManualModeDialogViewModel.StartHandle() < exit...");
}
@ -165,12 +169,13 @@ namespace Txgy.FilesWatcher.ViewModels
private void MseedUpload(DateTime currentT)
{
_log.Log.Debug("ManualModeDialogViewModel.MseedUpload() > enter...");
string path = $"{Path.Combine(mainModel.MainPath, mainModel.MseedPath)}/{currentT.Month.ToString("D2")}/{currentT.Day.ToString("D2")}/{currentT.Hour.ToString("D2")}/{currentT.Minute.ToString("D2")}";
// path = "I:\\yuwuN3102mseed\\NET2023\\06\\22\\21\\51";
Debug.WriteLine($"**********当前时间:{currentT},监控路径:{path}");
if (Directory.Exists(path) && mainModel.IsUploadDB && mainModel.IsUploadMseedPath)
{
_log.Log.DebugFormat("ManualModeDialogViewModel.MseedUpload() currentT:{0},path:{1}", currentT, path);
UploadMseedFile.UploadMSeedOnce((a =>
{
timer1.Dispatcher.Invoke(() =>
@ -184,14 +189,18 @@ namespace Txgy.FilesWatcher.ViewModels
});
}), path, mainModel.WorkAreaId);
}
_log.Log.Debug("ManualModeDialogViewModel.MseedUpload() < exit...");
}
private void RealtimeChanged(string filePath, string lastLine)
{
_log.Log.Debug("ManualModeDialogViewModel.RealtimeChanged() > enter...");
// string tmp = dt.Hour.ToString() + "时" + dt.Minute.ToString() + "分" + dt.Second.ToString() + "秒" + dt.Millisecond.ToString() + "毫秒,目录发生变化\r\n";
DateTime lastWriteTime = DateTime.Now; //File.GetLastWriteTime(e.FullPath);
Debug.WriteLine($"最后修改时间:{lastWriteTime},文件路径:{filePath}");
filePath = Path.GetDirectoryName(filePath);
_log.Log.DebugFormat("ManualModeDialogViewModel.RealtimeChanged() filePath:{0},path:{1}", filePath, lastLine);
if (mainModel.IsUploadDB && mainModel.IsUploadRealtimePath)
{
UploadRealtimeFile.UploadRealtimeFileOnce(filePath, lastLine, mainModel.WorkAreaId, out bool isUpload);
@ -215,15 +224,18 @@ namespace Txgy.FilesWatcher.ViewModels
}, filePath, lastLine);
}
_log.Log.Debug("ManualModeDialogViewModel.RealtimeChanged() < exit...");
}
private void PostChanged(string filePath, string lastLine)
{
_log.Log.Debug("ManualModeDialogViewModel.PostChanged() > enter...");
// string tmp = dt.Hour.ToString() + "时" + dt.Minute.ToString() + "分" + dt.Second.ToString() + "秒" + dt.Millisecond.ToString() + "毫秒,目录发生变化\r\n";
DateTime lastWriteTime = DateTime.Now; //File.GetLastWriteTime(e.FullPath);
Debug.WriteLine($"最后修改时间:{lastWriteTime},文件路径:{filePath}");
filePath = Path.GetDirectoryName(filePath);
_log.Log.DebugFormat("ManualModeDialogViewModel.RealtimeChanged() filePath:{0},path:{1}", filePath, lastLine);
if (mainModel.IsUploadDB && mainModel.IsUploadPostPath)
{
UploadPostproFile.UploadPostproFileOnce(filePath, lastLine, mainModel.WorkAreaId, out bool isUpload);
@ -252,7 +264,7 @@ namespace Txgy.FilesWatcher.ViewModels
});
}, filePath, lastLine);
}
_log.Log.Debug("ManualModeDialogViewModel.PostChanged() < exit...");
}
private DispatcherTimer timer1 = new DispatcherTimer();

@ -0,0 +1,89 @@
<?xml version="1.0" encoding="utf-8" ?>
<log4net>
<root>
<priority value="ALL"/>
<!--控制级别,由低到高: ALL|DEBUG|INFO|WARN|ERROR|FATAL|OFF-->
<!--比如定义级别为INFO则INFO级别向下的级别比如DEBUG日志将不会被记录-->
<!--如果没有定义LEVEL的值则缺省为DEBUG-->
<level value="DEBUG"/>
<!--控制台控制显示日志-->
<!--<appender-ref ref="ConsoleAppender"/>-->
<!--trace显示日志-->
<appender-ref ref="RollingFileTrace"/>
<appender-ref ref="RollingFileError"/>
</root>
<appender name="ConsoleAppender" type="log4net.Appender.ConsoleAppender">
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%date [%thread] %-5level %logger [%property{NDC}] - %message%newline"/>
</layout>
</appender>
<appender name="RollingFileTrace" type="log4net.Appender.RollingFileAppender">
<!--日志文件名开头-->
<file value="LOG\TRACE\Trace_"/>
<!--多线程时采用最小锁定-->
<lockingModel type="log4net.Appender.FileAppender+MinimalLock"/>
<!--日期的格式,每天换一个文件记录,如不设置则永远只记录一天的日志,需设置-->
<datePattern value="yyyyMMdd&quot;\\trace_&quot;yyyyMMHH&quot;&quot;"/>
<!--是否追加到文件,默认为true通常无需设置-->
<appendToFile value="true"/>
<StaticLogFileName value="false"/>
<!--变换的形式为日期,这种情况下每天只有一个日志-->
<!--此时MaxSizeRollBackups和maximumFileSize的节点设置没有意义-->
<!--<rollingStyle value="Date"/>-->
<!--变换的形式为日志大小-->
<!--这种情况下MaxSizeRollBackups和maximumFileSize的节点设置才有意义-->
<RollingStyle value="Composite"/>
<!--每天记录的日志文件个数与maximumFileSize配合使用-->
<MaxSizeRollBackups value="10"/>
<!--每个日志文件的最大大小-->
<!--可用的单位:KB|MB|GB-->
<!--不要使用小数,否则会一直写入当前日志-->
<maximumFileSize value="20MB"/>
<CountDirection value="1"/>
<!--日志格式-->
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="[%p] (%d) %m%n"/>
</layout>
</appender>
<appender name="RollingFileError" type="log4net.Appender.RollingFileAppender">
<file value="LOG\ERROR\Error_"/>
<lockingModel type="log4net.Appender.FileAppender+MinimalLock"/>
<!--日期的格式,每天换一个文件记录,如不设置则永远只记录一天的日志,需设置-->
<datePattern value="yyyyMMdd&quot;\\error_&quot;yyyyMMdd&quot;&quot;"/>
<!-- 这是按日期产生文件夹,并在文件名前也加上日期 -->
<!--<param name="DatePattern" value="yyyyMMdd/yyyyMMddhhmm&quot;-TimerServer.log&quot;" />-->
<!-- 这是先按日期产生文件夹,再形成下一级固定的文件夹 -->
<!--<param name="DatePattern" value="yyyyMMdd/&quot;TimerServer/TimerServer.log&quot;" />-->
<!--是否追加到文件,默认为true通常无需设置-->
<appendToFile value="true"/>
<!--是否只写到一个文件中-->
<StaticLogFileName value="false"/>
<!--变换的形式为日期,这种情况下每天只有一个日志-->
<!--此时MaxSizeRollBackups和maximumFileSize的节点设置没有意义-->
<!--<rollingStyle value="Date"/>-->
<!--变换的形式为日志大小-->
<!--这种情况下MaxSizeRollBackups和maximumFileSize的节点设置才有意义-->
<RollingStyle value="Composite"/>
<!--每天记录的日志文件个数与maximumFileSize配合使用-->
<MaxSizeRollBackups value="10"/>
<maximumFileSize value="5000KB"/>
<CountDirection value="1"/>
<RollingStyle value="Composite"/>
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%n记录时间: %date %nthreadID: [%t] %n日志级别: %-5level %n错误类 : %logger property -%F :line %L
%n错误描述: %message%newline"/>
</layout>
<filter type="log4net.Filter.LevelRangeFilter">
<levelMin value="ERROR"/>
<levelMax value="FATAL"/>
</filter>
</appender>
</log4net>

@ -0,0 +1,49 @@
using log4net;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Txgy.FilesWatcher.model
{
class GetLogger
{
/// <summary>
/// construct
/// </summary>
/// <param name="moduleName"></param>
public GetLogger(string moduleName)
{
getmoduleName = moduleName;
}
/// <summary>
/// get module name
/// </summary>
public string GetModuleName
{
get { return getmoduleName; }
}
private string getmoduleName;
/// <summary>
/// get logger instance
/// </summary>
public ILog Log
{
get
{
_logInstance = log4net.LogManager.GetLogger(GetModuleName);
return _logInstance;
}
}
private static ILog _logInstance;
}
}

@ -22,6 +22,9 @@ namespace Txgy.FilesWatcher.model
public static void UploadMSeedOnce(Action<string> mseedAction, string path, int workAreaId)
{
GetLogger _log = new GetLogger("UploadMseedFile");
_log.Log.Debug("UploadMseedFile.UploadMSeedOnce() > enter....");
_log.Log.DebugFormat("UploadMseedFile.UploadMSeedOnce() path:{0},workAreaId:{1}", path, workAreaId);
try
{
var currentTime = DateTime.Now;
@ -53,9 +56,12 @@ namespace Txgy.FilesWatcher.model
sqlNumber = $"INSERT INTO {tbname} (WaveTime, WorkAreaID, WaveData) VALUES('{WaveTime}', '{workAreaId}', @mseedD)";
var res = conn.Execute(sqlNumber, new { mseedD = mseedDatas });
_log.Log.DebugFormat("UploadMseedFile.UploadMSeedOnce() 上传数据表:{0},WaveTime:{1}", tbname, WaveTime);
//更新上传文件记录
sqlNumber = $"INSERT INTO {uploadedtbname}(filename, uploadtime) VALUES('{file}', '{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")}')";
res = conn.Execute(sqlNumber);
_log.Log.DebugFormat("UploadMseedFile.UploadMSeedOnce() 上传数据表:{0},文件:{1}", uploadedtbname, file);
}
}
}
@ -67,8 +73,10 @@ namespace Txgy.FilesWatcher.model
}
catch (Exception ex)
{
// System.Windows.MessageBox.Show(ex.ToString());
_log.Log.ErrorFormat("UploadMseedFile.UploadMSeedOnce()() error:{0}", ex);
}
_log.Log.Debug("UploadMseedFile.UploadMSeedOnce()() < exit....");
}
}

@ -19,6 +19,9 @@ namespace Txgy.FilesWatcher.model
public static void UploadPostproFileOnce(string path, string eventMessage, int workAreaId , out bool isUpload)
{
GetLogger _log = new GetLogger("UploadPostproFile");
_log.Log.Debug("UploadPostproFile.UploadPostproFileOnce() > enter....");
_log.Log.DebugFormat("UploadPostproFile.UploadPostproFileOnce() path:{0},eventMessage:{1},workAreaId:{2}", path, eventMessage, workAreaId);
isUpload = false;
try
{
@ -40,8 +43,8 @@ namespace Txgy.FilesWatcher.model
var a = conn.QueryFirst<int>(sqlNumber);
if (a == 0)
{
string[] index_file_line = eventMessage.Split(" ",StringSplitOptions.RemoveEmptyEntries);
if (index_file_line[4]== "None")
string[] index_file_line = eventMessage.Split(" ", StringSplitOptions.RemoveEmptyEntries);
if (index_file_line[4] == "None")
{
index_file_line[5] = "-4";
}
@ -52,6 +55,7 @@ namespace Txgy.FilesWatcher.model
sqlNumber = $"INSERT INTO {tbrealtimeresult}(WorkAreaId, EventTime, OriginTime, X, Y, Z, ML, LocSta, MLSta, RMS) VALUES('{workAreaId}', '{EventTime}', '{OriginTime}', '{index_file_line[1]}', '{index_file_line[2]}', '{index_file_line[3]}', '{index_file_line[5]}', '{index_file_line[7]}', '{index_file_line[8]}', '{index_file_line[6]}')";
var res = conn.Execute(sqlNumber);
isUpload = true;
_log.Log.DebugFormat("UploadPostproFileOnce() 上传数据表:{0},eventMessage:{1}", tbrealtimeresult, eventMessage);
// .mseed文件
FileStream fs = new FileStream(dFile.FullName, FileMode.Open, FileAccess.Read);
BinaryReader mbr = new BinaryReader(fs);
@ -80,21 +84,28 @@ namespace Txgy.FilesWatcher.model
sqlNumber = $"INSERT INTO {tbname} (EventTime, WorkAreaID, WaveData, JsonFile) VALUES('{EventTime}', '{workAreaId}', @mDatas, @jDatas);";
MySqlCommand mycomm = new MySqlCommand(sqlNumber, conn);
res = conn.Execute(sqlNumber, new { mDatas = mseedDatas, jDatas = jsonDatas });
_log.Log.DebugFormat("UploadPostproFileOnce() 上传数据表:{0}", tbname);
}
sqlNumber = $"INSERT INTO {uploadedtbname}(filename, uploadtime) VALUES('{file}', '{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")}')";
res = conn.Execute(sqlNumber);
_log.Log.DebugFormat("UploadPostproFileOnce() 上传数据表:{0},文件:{1}", uploadedtbname, file);
}
}
}
}
catch (Exception ex)
{
_log.Log.ErrorFormat("UploadPostproFile.UploadPostproFileOnce() error:{0}", ex);
System.Windows.MessageBox.Show(ex.ToString());
}
_log.Log.Debug("UploadPostproFile.UploadPostproFileOnce() < exit....");
}
public static void UploadPostproFileMQ(Action<string, string> mqAction, string path, string eventMessage)
{
GetLogger _log = new GetLogger("UploadPostproFile");
_log.Log.Debug("UploadPostproFile.UploadPostproFileMQ() > enter....");
_log.Log.DebugFormat("UploadPostproFile.UploadPostproFileMQ() path:{0},eventMessage:{1}", path, eventMessage);
try
{
var currentTime = DateTime.Now;
@ -128,9 +139,9 @@ namespace Txgy.FilesWatcher.model
}
catch (Exception ex)
{
// System.Windows.MessageBox.Show(ex.ToString());
_log.Log.ErrorFormat("UploadPostproFile.UploadPostproFileMQ() error:{0}", ex);
}
_log.Log.Debug("UploadPostproFile.UploadPostproFileMQ() < exit....");
}
}

@ -25,18 +25,21 @@ namespace Txgy.FilesWatcher.model
{
public static void UploadRealtimeFileOnce(string path, string eventMessage, int workAreaId, out bool isUpload)
{
GetLogger _log = new GetLogger("UploadRealtimeFile");
_log.Log.Debug("UploadRealtimeFile.UploadRealtimeFileOnce() > enter....");
_log.Log.DebugFormat("UploadRealtimeFile.UploadRealtimeFileOnce() path:{0},eventMessage:{1},workAreaId:{2}", path, eventMessage, workAreaId);
isUpload = false;
try
{
var currentTime = DateTime.Now;
var mseedFile = new DirectoryInfo(path).GetFiles("*.mseed");
var Dfiles= mseedFile.Where(f => eventMessage.Contains($"{f.Name.Substring(3, 4)}-{f.Name.Substring(7, 2)}-{f.Name.Substring(9, 2)}T{f.Name.Substring(12, 2)}:{f.Name.Substring(14, 2)}:{f.Name.Substring(16, 2)}"));
var Dfiles = mseedFile.Where(f => eventMessage.Contains($"{f.Name.Substring(3, 4)}-{f.Name.Substring(7, 2)}-{f.Name.Substring(9, 2)}T{f.Name.Substring(12, 2)}:{f.Name.Substring(14, 2)}:{f.Name.Substring(16, 2)}"));
var files = Directory.GetFiles(path);
foreach (var dFile in Dfiles)
{
string file = dFile.Name;
string tbrealtimeresult = "realtimeeventresult";
string tbname = "realtimewavedatas";
string tbrealtimeresult = "realtimeeventresult";
string tbname = "realtimewavedatas";
string uploadedtbname = "uploadedrealtime";
string sqlNumber = $"SELECT COUNT(*) FROM {uploadedtbname} WHERE filename = '{file}'";
//检查文件是否已经上传
@ -44,7 +47,7 @@ namespace Txgy.FilesWatcher.model
{
MySqlCommand cmd = new MySqlCommand(sqlNumber, conn);
var a = conn.QueryFirst<int>(sqlNumber);
if (a==0)
if (a == 0)
{
string[] index_file_line = eventMessage.Split(" ", StringSplitOptions.RemoveEmptyEntries);
if (index_file_line[4] == "None")
@ -57,15 +60,16 @@ namespace Txgy.FilesWatcher.model
//WorkAreaId = 1,更新realtimeeventresult
sqlNumber = $"INSERT INTO {tbrealtimeresult}(WorkAreaId, EventTime, OriginTime, X, Y, Z, ML, LocSta, MLSta, RMS) VALUES('{workAreaId}', '{EventTime}', '{OriginTime}', '{index_file_line[1]}', '{index_file_line[2]}', '{index_file_line[3]}', '{index_file_line[5]}', '{index_file_line[7]}', '{index_file_line[8]}', '{index_file_line[6]}')";
var res = conn.Execute(sqlNumber);
var res = conn.Execute(sqlNumber);
isUpload = true;
_log.Log.DebugFormat("UploadRealtimeFileOnce() 上传数据表:{0},eventMessage:{1}", tbrealtimeresult, eventMessage);
// .mseed文件
FileStream fs = new FileStream(dFile.FullName, FileMode.Open, FileAccess.Read);
BinaryReader mbr = new BinaryReader(fs);
Byte[] mseedDatas = mbr.ReadBytes((int)fs.Length);
fs.Close();
//.json文件
string JsonPath = dFile.FullName.Replace(".mseed", "A.json");
string JsonPath = dFile.FullName.Replace(".mseed", "A.json");
fs = new FileStream(JsonPath, FileMode.Open, FileAccess.Read);
BinaryReader jbr = new BinaryReader(fs);
Byte[] jsonDatas = jbr.ReadBytes((int)fs.Length);
@ -78,30 +82,38 @@ namespace Txgy.FilesWatcher.model
//重新编码,解决中文乱码问题
Encoder = JavaScriptEncoder.Create(UnicodeRanges.All)
};
sqlNumber = $"SELECT COUNT(*) FROM {tbname} WHERE EventTime = '{EventTime}'";
sqlNumber = $"SELECT COUNT(*) FROM {tbname} WHERE EventTime = '{EventTime}'";
MySqlCommand md = new MySqlCommand(sqlNumber, conn);
var count = conn.QueryFirst<int>(sqlNumber);
var count = conn.QueryFirst<int>(sqlNumber);
if (count == 0)
{
sqlNumber = $"INSERT INTO {tbname} (EventTime, WorkAreaID, WaveData, JsonFile) VALUES('{EventTime}', '{workAreaId}', @mDatas, @jDatas);";
MySqlCommand mycomm = new MySqlCommand(sqlNumber, conn);
res = conn.Execute(sqlNumber, new { mDatas = mseedDatas, jDatas = jsonDatas });
_log.Log.DebugFormat("UploadRealtimeFileOnce() 上传数据表:{0}", tbname);
}
sqlNumber = $"INSERT INTO {uploadedtbname}(filename, uploadtime) VALUES('{file}', '{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")}')";
res = conn.Execute(sqlNumber);
_log.Log.DebugFormat("UploadRealtimeFileOnce() 上传数据表:{0},文传:{1}", uploadedtbname, file);
}
}
}
}
catch (Exception ex)
{
_log.Log.ErrorFormat("UploadRealtimeFile.UploadRealtimeFileOnce() error:{0}", ex);
MessageBox.Show(ex.ToString());
}
_log.Log.Debug("UploadRealtimeFile.UploadRealtimeFileOnce() < exit....");
}
public static void UploadRealtimeFileMQ(Action<string, string> mqAction, string path, string eventMessage)
{
GetLogger _log = new GetLogger("UploadRealtimeFile");
_log.Log.Debug("UploadRealtimeFile.UploadRealtimeFileMQ() > enter....");
_log.Log.DebugFormat("UploadRealtimeFile.UploadRealtimeFileMQ() path:{0},eventMessage:{1}", path, eventMessage);
try
{
var currentTime = DateTime.Now;
@ -111,7 +123,7 @@ namespace Txgy.FilesWatcher.model
foreach (var dFile in Dfiles)
{
string file = dFile.Name;
//.json文件
string JsonPath = dFile.FullName.Replace(".mseed", "A.json");
FileStream fs = new FileStream(JsonPath, FileMode.Open, FileAccess.Read);
@ -132,7 +144,9 @@ namespace Txgy.FilesWatcher.model
catch (Exception ex)
{
//MessageBox.Show(ex.ToString());
_log.Log.ErrorFormat("UploadRealtimeFile.UploadRealtimeFileMQ() error:{0}", ex);
}
_log.Log.Debug("UploadRealtimeFile.UploadRealtimeFileMQ() < exit....");
}
}

Loading…
Cancel
Save