/// <summary> /// 通过Socket发送日志 /// </summary> /// <param name="level">日志级别</param> /// <param name="beginMark">Stocket信息头</param> /// <param name="endMark">Socket信息尾</param> /// <param name="logRequest">日志请求</param> private static void SendMessage(LogLevel level, string beginMark, string endMark, LogRequest logRequest) { var pack = new StringPackageInfo(level.ToString(), logRequest.ToJson(), null); var msg = $"{beginMark}{pack.ToJson()}{endMark}"; client.Send(Encoding.UTF8.GetBytes(msg)); }
/// <summary> /// 通过Http发送日志 /// </summary> private static void SendMessage(LogLevel level, string appId, string secrect, LogRequest logRequest, string host, string port = "80") { try { var url = $"http://{host}:{port}/api/LogService/{level.ToString()}"; url.WithHeaders(new { AppId = appId, Secrect = secrect }).PostJsonAsync(logRequest).ReceiveJson(); } catch { } }
/// <summary> /// 创建读取任务 /// </summary> public static void CreatReadTask(bool isTcp = true) { if (ReadLogTask == null) { ReadLogTask = Task.Run(() => { while (true) { //连接成功了才开始读取 if (isTcp) { ResetEvent.WaitOne(); } var item = MSHLogger.LoggingEvents.Take(); if (item == null) { continue; } //将日志发送到服务器 var serverHost = item.Properties["ServerHost"].ToString(); var serverPort = item.Properties["ServerPort"].ToString(); var mode = item.Properties["Mode"]; var appId = item.Properties["AppId"].ToString(); var secrect = item.Properties["Secrect"].ToString(); var defaultBusinessPosition = item.Properties["DefaultBusinessPosition"]; var beginMark = item.Properties["BeginMark"]; var endMark = item.Properties["EndMark"]; List <string> traceInfos = new List <string>(); if (item.LocationInformation?.StackFrames?.Length >= 1) { foreach (var frame in item.LocationInformation?.StackFrames) { traceInfos.Add($"在类:{frame.ClassName} 方法:{frame.Method} 行:{frame.LineNumber}"); } } var logData = item.MessageObject as LogData; if (logData == null) { continue; } var logRequest = new LogRequest() { AppId = appId.ToString(), BusinessPosition = logData.BusinessPosition ?? $"{defaultBusinessPosition}", Content = logData.Message, CreatTime = item.TimeStamp, TraceInfo = logData.TraceInfo, RequestId = logData.RequestId, }; Console.WriteLine($"开始发送日志请求:{logRequest.ToJson()}"); if (mode.ToString().ToLower().Equals("tcp")) { SendMessage(MapLogLevel(item.Level), $"{beginMark}", $"{endMark}", logRequest); } if (mode.ToString().ToLower().Equals("http")) { SendMessage(MapLogLevel(item.Level), appId, secrect, logRequest, serverHost, serverPort); } } }); } }