LogServer.cs 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305
  1. using Cksoft.Data;
  2. using Cksoft.Data.Repository;
  3. using Cksoft.Unity;
  4. using DllEapDal;
  5. using DllEapEntity;
  6. using DllHsms;
  7. using Microsoft.Extensions.Logging;
  8. using RabbitMQ.Client;
  9. using RabbitMQ.Client.Events;
  10. using System;
  11. using System.Collections.Generic;
  12. using System.IO;
  13. using System.Linq;
  14. namespace DllLogServer
  15. {
  16. public class LogServer:ILogServer
  17. {
  18. private ILogger loger = null;
  19. private long CurrCount = 0;
  20. private IModel CurrQueueChannel = null;
  21. private string CurrRecQueueName = "hello";//接收队列名称 hsmsreceive+机台编号
  22. private List<ServerInfo> CurrInfo = new List<ServerInfo>();//记录错误信息
  23. private int CurrStatus = -1;//未启动状态
  24. private string CurrFileDir="";//日志文件主路径
  25. public string CurrShareFileDir = "";
  26. public LogServer(ILogger<LogServer> loger)
  27. {
  28. this.loger = loger;
  29. }
  30. //开始接收队列线程
  31. public int StartRecQueue(ref string errorinfo)
  32. {
  33. try
  34. {
  35. //注册通道
  36. CurrQueueChannel = RegeditChannel(ref errorinfo);
  37. if (CurrQueueChannel == null)
  38. {
  39. errorinfo = "注册队列通道发生错误,错误信息为:" + errorinfo;
  40. return -1;
  41. }
  42. //清空接收队列
  43. //int result = ClearRecQueue(ref errorinfo);
  44. //if (result < 0)
  45. //{
  46. // errorinfo = "清空接收队列发生错误,错误信息为:" + errorinfo;
  47. // return -1;
  48. //}
  49. CurrQueueChannel.QueueDeclare(CurrRecQueueName, false, false, false, null);
  50. //BasicQos函数是针对通道的,必须放在注册消费者前执行,否则注册的消费者会接受多条信息
  51. CurrQueueChannel.BasicQos(0, 1, false);
  52. var consumer = new EventingBasicConsumer(CurrQueueChannel);
  53. CurrQueueChannel.BasicConsume(queue: CurrRecQueueName,
  54. autoAck: false, //是否不要手动应答(no manual Ack),ture自动应答,自动删除处理消息;false手动应答,服务器的消息会等待应答结果才消除
  55. consumer: consumer);
  56. consumer.Received += QueueReceive;
  57. return 1;
  58. }
  59. catch (Exception ex)
  60. {
  61. errorinfo = ex.Message.ToString();
  62. return -1;
  63. }
  64. }
  65. //注册通道
  66. private IModel RegeditChannel(ref string errorinfo)
  67. {
  68. try
  69. {
  70. var factory = new ConnectionFactory();
  71. factory.HostName = AppConfigurtaionServices.Configuration["rabbitmq:IPAddress"];
  72. factory.UserName = AppConfigurtaionServices.Configuration["rabbitmq:UserName"];
  73. factory.Password = AppConfigurtaionServices.Configuration["rabbitmq:Password"];
  74. factory.VirtualHost = AppConfigurtaionServices.Configuration["rabbitmq:VirtualHost"];
  75. var connection = factory.CreateConnection();
  76. var channel = connection.CreateModel();
  77. CurrShareFileDir = AppConfigurtaionServices.Configuration["ShareFileDir"];
  78. return channel;
  79. }
  80. catch (Exception ex)
  81. {
  82. errorinfo = ex.Message.ToString();
  83. return null;
  84. }
  85. }
  86. private int ClearRecQueue(ref string errorinfo)
  87. {
  88. try
  89. {
  90. CurrQueueChannel.QueueDelete(CurrRecQueueName, true, false);
  91. return 1;
  92. }
  93. catch (Exception ex)
  94. {
  95. errorinfo = ex.Message.ToString();
  96. return -1;
  97. }
  98. }
  99. private void QueueReceive(object model, BasicDeliverEventArgs ea)
  100. {
  101. CurrCount++;
  102. string errorinfo = "";
  103. int result = WriteLog(ea.Body, ref errorinfo);
  104. if (result <= 0)
  105. {
  106. //写本地日志
  107. SetText(errorinfo);
  108. }
  109. CurrQueueChannel.BasicAck(deliveryTag: ea.DeliveryTag, multiple: false);
  110. }
  111. private int WriteLog(byte[] datas, ref string errorinfo)
  112. {
  113. try
  114. {
  115. HsmsLog log = EntityHelper.DeSerializeBytes<HsmsLog>(datas);
  116. int result = log.RecoverData(CurrShareFileDir, ref errorinfo);
  117. if (result <= 0)
  118. return -1;
  119. int ftype = log.FType;// int.Parse(row["ftype"].ToString());
  120. int mcaid = log.MacID;// int.Parse(row["mcaid"].ToString());
  121. string logstr = log.Log;// row["log"].ToString();
  122. string fcode = log.MacCode;// row["fcode"].ToString();
  123. Block orgblock = log.OrgBlock;//通讯块
  124. if(orgblock!=null&&orgblock.AllLen>1000)
  125. {
  126. int aaa = 100;
  127. }
  128. if (orgblock != null)
  129. {
  130. //如果是测试指令,则不记录日志
  131. if (orgblock.GetBlockS(ref errorinfo) == 0)
  132. return 1;
  133. // UpdateVersion(orgblock, mcaid);
  134. }
  135. DateTime occurtime = log.OccurTime;//发生时间
  136. string filename = GetLogFile(mcaid, fcode, ref errorinfo);
  137. if (filename == "")
  138. return -1;
  139. logstr = $"发生时间:{occurtime.ToString("yyyy-MM-dd HH:mm:ss.fff")} 机台ID:{mcaid} 机台编号:{fcode} 机台IP:{log.macOrder.IPAddress} 信息:{logstr}";
  140. FileStream fs;
  141. StreamWriter sw;
  142. if (File.Exists(filename))
  143. {
  144. //验证文件是否存在,有则追加,无则创建
  145. fs = new FileStream(filename, FileMode.Append, FileAccess.Write);
  146. }
  147. else
  148. {
  149. fs = new FileStream(filename, FileMode.Create, FileAccess.Write);
  150. }
  151. sw = new StreamWriter(fs);
  152. sw.WriteLine(logstr);
  153. if (orgblock != null)
  154. {
  155. //打印指令数据
  156. logstr = orgblock.GetLog(log.Log);
  157. sw.WriteLine(logstr);
  158. }
  159. sw.Close();
  160. fs.Close();
  161. return 1;
  162. }
  163. catch (Exception ex)
  164. {
  165. errorinfo = ex.Message.ToString();
  166. return -1;
  167. }
  168. }
  169. private void UpdateVersion(Block orgblock,int macid)
  170. {
  171. IDatabase db = null;
  172. try
  173. {
  174. string errorinfo = "";
  175. int s = orgblock.GetBlockS(ref errorinfo);
  176. int f = orgblock.GetBlockF(ref errorinfo);
  177. if (!(s == 1 && f == 2))
  178. return;
  179. List<OrderData> datas = orgblock.GetOrderData(ref errorinfo);
  180. OrderData l = datas.Where(t => t.ParentID == 0).FirstOrDefault();
  181. List<OrderData> tempdatas = datas.Where(t => t.ParentID == l.ID).OrderBy(t => t.FNum).ToList();
  182. db = DbFactory.Base("eap");
  183. Machine mac = db.FindEntity<Machine>(macid);
  184. if (mac.FVersion == tempdatas[1].FContent)
  185. {
  186. return;
  187. }
  188. db.BeginTrans();
  189. mac.FName = tempdatas[0].FContent;
  190. mac.FVersion = tempdatas[1].FContent;
  191. db.UpdateFor<Machine>(mac, "");
  192. db.Commit();
  193. }
  194. catch(Exception ex)
  195. {
  196. loger.LogError(ex.ToString());
  197. }
  198. finally
  199. {
  200. if (db != null)
  201. db.Close();
  202. }
  203. }
  204. private string GetLogFile(int mcaid, string code, ref string errorinfo)
  205. {
  206. try
  207. {
  208. //每天1个日志
  209. string sFilePath = $"{CurrFileDir}{Path.DirectorySeparatorChar}log{DateTime.Now.ToString("yyyyMMdd")}";// CurrFileDir + "log" + DateTime.Now.ToString("yyyyMMdd");
  210. string sFileName = $"{code}_{mcaid}.log";
  211. sFileName = sFilePath + Path.DirectorySeparatorChar + sFileName; //文件的绝对路径
  212. if (!Directory.Exists(sFilePath))//验证路径是否存在
  213. {
  214. Directory.CreateDirectory(sFilePath);
  215. //不存在则创建
  216. }
  217. return sFileName;
  218. }
  219. catch (Exception ex)
  220. {
  221. errorinfo = ex.Message.ToString();
  222. return "";
  223. }
  224. }
  225. public void SetText(string str)
  226. {
  227. this.loger.LogError(str);
  228. if (CurrInfo.Count > 100)
  229. CurrInfo.Clear();
  230. int id = 1;
  231. if (CurrInfo.Count > 0)
  232. {
  233. id = CurrInfo.Max(t => t.ID);
  234. id++;
  235. }
  236. ServerInfo entity = new ServerInfo();
  237. entity.ID = id;
  238. entity.Info = str;
  239. CurrInfo.Add(entity);
  240. }
  241. public int Start(ref string errorinfo)
  242. {
  243. try
  244. {
  245. CurrStatus = -1;
  246. CurrRecQueueName = AppConfigurtaionServices.Configuration["rabbitmq:mqname"];
  247. CurrFileDir = AppConfigurtaionServices.Configuration["FileDir"];
  248. int result = StartRecQueue(ref errorinfo);
  249. if (result < 0)
  250. {
  251. errorinfo = $"启动失败,错误信息为:{errorinfo}";
  252. SetText(errorinfo);
  253. return -1;
  254. }
  255. CurrStatus = 1;
  256. SetText("启动成功。");
  257. return 1;
  258. }
  259. catch (Exception ex)
  260. {
  261. errorinfo = ex.Message.ToString();
  262. SetText(errorinfo);
  263. return -1;
  264. }
  265. }
  266. public long GetAccount()
  267. {
  268. return CurrCount;
  269. }
  270. public int GetStatus(ref string errorinfo)
  271. {
  272. if (CurrStatus <= 0 && CurrInfo.Count > 0)
  273. {
  274. errorinfo = CurrInfo.Last().Info;
  275. }
  276. return CurrStatus;
  277. }
  278. public List<ServerInfo> GetInfo()
  279. {
  280. return CurrInfo;
  281. }
  282. public int Stop(ref string errorinfo)
  283. {
  284. try
  285. {
  286. CurrStatus = -1;
  287. if (CurrQueueChannel != null)
  288. CurrQueueChannel.Close();
  289. SetText("停止服务成功。");
  290. return 1;
  291. }
  292. catch (Exception ex)
  293. {
  294. SetText(ex.Message.ToString());
  295. return -1;
  296. }
  297. }
  298. }
  299. }