LogService.cs 11 KB

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