/// <summary> /// 开始日志监测 /// </summary> /// <param name="data"></param> private static void BeginMonitor(RouteData data) { if (!LogRecorder.LogMonitor) { return; } try { LogRecorder.BeginMonitor(data.Uri.ToString()); LogRecorder.BeginStepMonitor("HTTP"); var args = new StringBuilder(); args.Append("Headers:"); args.Append(JsonConvert.SerializeObject(data.Headers)); LogRecorder.MonitorTrace(args.ToString()); LogRecorder.MonitorTrace($"Method:{data.HttpMethod}"); } catch (Exception e) { LogRecorder.MonitorTrace(e.Message); LogRecorder.Exception(e); } finally { LogRecorder.EndStepMonitor(); } }
/// <summary> /// 开始计数 /// </summary> /// <returns></returns> private static void EndMonitor(RouteData data) { if (!LogRecorder.LogMonitor) { return; } try { if (!string.IsNullOrWhiteSpace(data.Uri.Query)) { LogRecorder.MonitorTrace($"Query:{data.Uri.Query}"); } if (!string.IsNullOrWhiteSpace(data.Form)) { LogRecorder.MonitorTrace($"Form:{data.Form}"); } if (!string.IsNullOrWhiteSpace(data.Context)) { LogRecorder.MonitorTrace("Context:" + data.Context); } LogRecorder.MonitorTrace($"Status : {data.Status}"); LogRecorder.MonitorTrace($"Result:{data.ResultMessage}"); } catch (Exception e) { LogRecorder.MonitorTrace(e.Message); LogRecorder.Exception(e); } finally { LogRecorder.EndMonitor(); } }
private Task <HttpResponseMessage> DoEnd(Task <HttpResponseMessage> t1, HttpRequestMessage request, CancellationToken cancellationToken) { try { t1.Wait(cancellationToken); HttpResponseMessage result; if (t1.IsCanceled) { LogRecorder.MonitorTrace("操作被取消"); result = request.ToResponse(ApiResult.Error(-7, "服务器正忙", "操作被取消")); LogRecorder.EndMonitor(); return(Task <HttpResponseMessage> .Factory.StartNew(() => result, cancellationToken)); } if (t1.IsFaulted) { LogRecorder.MonitorTrace(t1.Exception?.Message); LogRecorder.Exception(t1.Exception); result = request.ToResponse(ApiResult.Error(-1, "未知错误", t1.Exception?.Message)); } else { result = t1.Result; } return(Task <HttpResponseMessage> .Factory.StartNew(delegate { OnEnd(request, result, cancellationToken); return result; }, cancellationToken)); } finally { IocHelper.DisposeScope(); } }
/// <summary> /// 关闭连接 /// </summary> public void Close() { if (_connection == null) { return; } try { lock (LockData) { if (_connection.State == ConnectionState.Open) { //Trace.WriteLine("Close Connection", "MySqlDataBase"); _connection.Close(); } Connections.Remove(_connection); LogRecorder.MonitorTrace($"未关闭总数{Connections.Count}"); _connection = null; } } catch (Exception exception) { _connection?.Dispose(); Debug.WriteLine("Close Error", "MySqlDataBase"); LogRecorder.Error(exception.ToString()); } finally { if (_default == this) { _default = null; } } }
Task <HttpResponseMessage> DoEnd(Task <HttpResponseMessage> t1, HttpRequestMessage request, CancellationToken cancellationToken) { t1.Wait(cancellationToken); HttpResponseMessage result; if (t1.IsCanceled) { LogRecorder.MonitorTrace("操作被取消"); result = request.ToResponse(ApiResult.Error(ErrorCode.Ignore, "服务器正忙", "操作被取消")); LogRecorder.EndAllStepMonitor(); LogRecorder.EndMonitor(); return(Task <HttpResponseMessage> .Factory.StartNew(() => result, cancellationToken)); } if (t1.IsFaulted) { LogRecorder.MonitorTrace(t1.Exception?.Message); LogRecorder.Exception(t1.Exception); result = request.ToResponse(ApiResult.Error(ErrorCode.UnknowError, "未知错误", t1.Exception?.Message)); } else { result = t1.Result; } /* * result.ContinueWith((task, state) => , null, * TaskContinuationOptions.AttachedToParent | TaskContinuationOptions.ExecuteSynchronously); */ return(Task <HttpResponseMessage> .Factory.StartNew(() => { OnEnd(request, result, cancellationToken); return result; }, cancellationToken)); }
private void ProcessRequest() { LogRecorder.BeginStepMonitor("LoadAuthority"); var canDo = LoadAuthority(); LogRecorder.MonitorTrace(canDo.ToString()); LogRecorder.EndStepMonitor(); if (!canDo) { ModelContext.LastMessage = "非法访问"; return; } LogRecorder.BeginStepMonitor("Prepare"); OnPrepare(); LogRecorder.EndStepMonitor(); LogRecorder.BeginStepMonitor("CheckCanDo"); canDo = IsPublicPage || CheckCanDo(); LogRecorder.MonitorTrace(canDo.ToString()); LogRecorder.EndStepMonitor(); if (!canDo) { return; } LogRecorder.BeginStepMonitor("OnPageLoaded"); OnPageLoaded(); LogRecorder.EndStepMonitor(); }
private void ApiCallByMonitor(ref ZSocket socket, ApiCallItem item) { using (MonitorScope.CreateScope(item.ApiName)) { LogRecorder.MonitorTrace($"Caller:{item.Caller}"); LogRecorder.MonitorTrace($"GlobalId:{item.GlobalId}"); LogRecorder.MonitorTrace(JsonConvert.SerializeObject(item)); ZeroOperatorStateType state; Prepare(item); using (MonitorScope.CreateScope("Do")) { state = ExecCommand(item); } if (state != ZeroOperatorStateType.Ok) { Interlocked.Increment(ref ErrorCount); } else { Interlocked.Increment(ref SuccessCount); } LogRecorder.MonitorTrace(item.Result); if (!SendResult(ref socket, item, state)) { ZeroTrace.WriteError(item.ApiName, "SendResult"); } End(item); } }
/// <summary> /// 开始时的处理 /// </summary> /// <returns>如果返回内容不为空,直接返回,后续的处理不再继续</returns> Task <HttpResponseMessage> IHttpSystemHandler.OnBegin(HttpRequestMessage request, CancellationToken cancellationToken) { if (!LogRecorder.LogMonitor) { return(null); } LogRecorder.BeginMonitor(request.RequestUri.ToString()); try { var args = new StringBuilder(); args.Append("Headers:"); foreach (var head in request.Headers) { args.Append($"【{head.Key}】{head.Value.LinkToString('|')}"); } LogRecorder.MonitorTrace(args.ToString()); LogRecorder.MonitorTrace($"Method:{request.Method}"); LogRecorder.MonitorTrace($"QueryString:{request.RequestUri.Query}"); RecordRequestToCode(request); } catch (Exception e) { LogRecorder.Exception(e); } return(null); }
/// <summary> /// 序列化到错误内容 /// </summary> /// <param name="code"></param> /// <param name="message"></param> /// <param name="message2"></param> /// <returns></returns> private string ToErrorString(int code, string message, string message2 = null) { Error = code; Message = $"调用异常:{message}.{message2}"; LogRecorder.MonitorTrace(Message); return(Message); }
/// <summary> /// 页面操作处理入口 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> protected void Page_Load(object sender, EventArgs e) { CurrentPageName = GetFriendPageUrl(); LogRecorder.BeginMonitor(CurrentPageName); LogRecorder.MonitorTrace(Request.Url.AbsolutePath); LogRequestInfo(); try { ProcessRequest(); } catch (Exception exception) { LogRecorder.EndStepMonitor(); LogRecorder.BeginStepMonitor("Exception"); LogRecorder.MonitorTrace(exception.Message); LogRecorder.Exception(exception); Debug.WriteLine(exception); OnFailed(exception); LogRecorder.EndStepMonitor(); } LogRecorder.BeginStepMonitor("Result"); OnResult(); LogRecorder.EndStepMonitor(); LogRecorder.EndMonitor(); }
/// <summary> /// 页面操作处理入口 /// </summary> protected override void OnPageLoaded() { IsFailed = false; Message = null; State = 0; try { DoActin(_action); } catch (AgebullBusinessException exception) { IsFailed = true; Message = exception.Message; } catch (Exception exception) { IsFailed = true; State = 3; Message = "*--系统内部错误--*"; Debug.WriteLine(exception); LogRecorder.Error(exception.StackTrace); LogRecorder.Error(exception.ToString()); LogRecorder.MonitorTrace("Exception:" + exception.Message); } }
/// <summary> /// 远程调用 /// </summary> /// <returns></returns> private string CallHttp() { // 当前请求调用的模型对应的主机名称 string httpHost; // 当前请求调用的Api名称 var httpApi = Data.RouteHost == HostConfig.DefaultHost ? Data.Uri.PathAndQuery : $"{Data.ApiName}{Data.Uri.Query}"; // 查找主机 if (Data.RouteHost.Hosts.Length == 1) { httpHost = Data.RouteHost.Hosts[0]; } else { lock (Data.RouteHost) { //平均分配 httpHost = Data.RouteHost.Hosts[Data.RouteHost.Next]; if (++Data.RouteHost.Next >= Data.RouteHost.Hosts.Length) { Data.RouteHost.Next = 0; } } } // 远程调用 var caller = new HttpApiCaller(httpHost) { Bearer = $"Bearer {ApiContext.RequestContext.Bear}" }; var req = caller.CreateRequest(httpApi, Data.HttpMethod, Request, Data); LogRecorder.BeginStepMonitor("内部HTTP调用"); LogRecorder.MonitorTrace($"Url:{req.RequestUri.PathAndQuery}"); LogRecorder.MonitorTrace($"Auth:{caller.Bearer}"); try { // 远程调用状态 Data.ResultMessage = caller.GetResult(req, out var webStatus); LogRecorder.MonitorTrace(webStatus.ToString()); if (webStatus != WebExceptionStatus.Success) { Data.Status = RouteStatus.RemoteError; } } catch (Exception ex) { LogRecorder.Exception(ex); LogRecorder.MonitorTrace($"发生异常:{ex.Message}"); Data.ResultMessage = RouteRuntime.NetworkError; Data.Status = RouteStatus.RemoteError; } finally { LogRecorder.MonitorTrace(Data.ResultMessage); LogRecorder.EndStepMonitor(); } return(Data.ResultMessage); }
/// <summary> /// 通过Post调用 /// </summary> /// <param name="apiName"></param> /// <param name="form"></param> /// <returns></returns> public ApiValueResult Post(string apiName, string form) { LogRecorder.BeginStepMonitor("内部API调用" + ToUrl(apiName)); string ctx = string.IsNullOrEmpty(Bearer) ? null : $"Bearer {Bearer}"; LogRecorder.MonitorTrace(ctx); LogRecorder.MonitorTrace("Arguments:" + form); HttpWebRequest req = (HttpWebRequest)WebRequest.Create(ToUrl(apiName)); req.Method = "POST"; req.ContentType = "application/x-www-form-urlencoded"; req.Headers.Add(HttpRequestHeader.Authorization, ctx); try { using (Stream rs = req.GetRequestStream()) { byte[] formData = Encoding.UTF8.GetBytes(form); rs.Write(formData, 0, formData.Length); } } catch (Exception ex) { LogRecorder.Exception(ex); LogRecorder.EndStepMonitor(); return(ErrorResult(-3)); } using (MonitorScope.CreateScope("Caller Remote")) { return(GetResult(req)); } }
public TResponse DoTrans <TRequest, TResponse>(TRequest request) where TRequest : IHospProxyRequestModel, new() where TResponse : IHospProxyResponseModel, new() { try { using (MonitorScope.CreateScope(MethodBase.GetCurrentMethod().Name)) { var soapRequest = request.ConvertToHospRequest(); LogRecorder.MonitorTrace(new { doCode = soapRequest.code, doRequest = soapRequest.json }.ToJson()); var soapClient = GenerateSoapClient <AppServiceCommonSoap>(); var soapResult = soapClient.DoTransAsync(soapRequest.code, soapRequest.json).Result; LogRecorder.MonitorTrace(new { doCode = soapRequest.code, doResponse = soapResult }.ToJson()); var result = JsonConvert.DeserializeObject <TResponse>(soapResult.FormatHospResult()); LogRecorder.MonitorTrace(new { doCode = soapRequest.code, doFormatResult = soapResult }.ToJson()); return(result); } } catch (Exception ex) { throw ex; } }
/// <summary> /// 通过Post调用 /// </summary> /// <param name="apiName"></param> /// <param name="form"></param> /// <returns></returns> public ApiValueResult <string> Post(string apiName, string form) { LogRecorder.BeginStepMonitor("内部API调用" + ToUrl(apiName)); var ctx = string.IsNullOrEmpty(Bearer) ? null : $"Bearer {Bearer}"; LogRecorder.MonitorTrace(ctx); LogRecorder.MonitorTrace("Arguments:" + form); var req = (HttpWebRequest)WebRequest.Create(ToUrl(apiName)); req.Method = "POST"; req.ContentType = "application/x-www-form-urlencoded"; req.Headers.Add(HttpRequestHeader.Authorization, ctx); try { using (var rs = req.GetRequestStream()) { var formData = Encoding.UTF8.GetBytes(form); rs.Write(formData, 0, formData.Length); } } catch (Exception e) { LogRecorder.Exception(e); LogRecorder.EndStepMonitor(); return(ApiValueResult <string> .ErrorResult(ErrorCode.NetworkError)); } return(GetResult(req)); }
/// <summary> /// 检查设备标识 /// </summary> /// <returns> /// 0:表示通过验证,可以继续 /// 1:令牌为空 /// 2:令牌是伪造的 /// </returns> private int CheckDeviceId(string token) { if (Request.RequestUri.LocalPath == "/v1/oauth/getdid") { return(ErrorCode.Success); } IBearValidater checker = IocHelper.Create <IBearValidater>(); ApiResult <LoginUserInfo> result; try { result = checker.ValidateDeviceId(token); } catch (Exception ex) { LogRecorder.Exception(ex); return(ErrorCode.Success); } if (!result.Success) { return(result.Status.ErrorCode); } CreateApiContext(result.ResultData, token); LogRecorder.MonitorTrace("Authorization:匿名用户"); return(ErrorCode.Success); }
/// <summary> /// 检查设备标识 /// </summary> /// <returns> /// 0:表示通过验证,可以继续 /// 1:令牌为空 /// 2:令牌是伪造的 /// </returns> private int CheckDeviceId(HttpRequestMessage request, string token) { if (string.IsNullOrWhiteSpace(token) || token.Contains('.') || token.Length <= 33) { return(ErrorCode.DenyAccess); } for (var index = 1; index < token.Length; index++) { var ch = token[index]; if ((ch >= '0' && ch <= '9') || (ch >= 'A' && ch <= 'Z') || (ch >= 'a' && ch <= 'z') || ch == '_') { continue; } return(ErrorCode.DenyAccess); } var checker = IocHelper.Create <IBearValidater>(); ApiResult <LoginUserInfo> result; try { result = checker.ValidateDeviceId(token); } catch (Exception e) { LogRecorder.Exception(e); return(0); //ErrorCode.Auth_Device_Unknow; } if (!result.Result) { return(result.Status.ErrorCode); } CreateApiContext(result.ResultData, token); LogRecorder.MonitorTrace("Authorization:匿名用户"); return(0); }
/// <summary> /// 序列化到错误内容 /// </summary> /// <param name="code"></param> /// <param name="message"></param> /// <param name="message2"></param> /// <returns></returns> private string ToErrorString(int code, string message, string message2 = null) { LogRecorder.MonitorTrace($"调用异常:{message}.{message2}"); var result = ApiResult.Error(code, RemoteUrl + message, message2); result.Status.Point = "web api gateway"; return(JsonConvert.SerializeObject(result)); }
/// <summary> /// 缓存当前上下文 /// </summary> public void Cache() { LogRecorder.MonitorTrace(JsonConvert.SerializeObject(this)); using (RedisProxy proxy = new RedisProxy()) { proxy.Set(GetCacheKey(RequestInfo.RequestId), this); } }
/// <summary> /// 准备 /// </summary> /// <param name="service">当前服务</param> /// <param name="message">当前消息</param> /// <param name="tag">扩展信息</param> /// <returns></returns> Task <bool> IMessageMiddleware.Prepare(IService service, IInlineMessage message, object tag) { if (LogRecorder.LogMonitor) { LogRecorder.BeginMonitor($"{message.Topic}/{message.Title}"); LogRecorder.MonitorTrace(() => JsonConvert.SerializeObject(message, Formatting.Indented)); } return(Task.FromResult(true)); }
/// <summary> /// 状态改变后的统一处理(unityStateChanged不设置为true时不会产生作用--基于性能的考虑) /// </summary> /// <param name="data">数据</param> /// <param name="cmd">命令</param> protected void OnStateChanged(TData data, BusinessCommandType cmd) { if (!unityStateChanged) { return; } LogRecorder.MonitorTrace("OnStateChanged"); OnInnerCommand(data, cmd); DoStateChanged(data); }
/// <summary> /// 载入用户账号信息 /// </summary> protected bool LoadAuthority() { ModelContext.PowerChecker.ReloadLoginUserInfo(); if (!CheckLogined()) { LogRecorder.MonitorTrace($"非法用户:{Request.RawUrl}"); return(false); } LogRecorder.MonitorTrace($"当前用户:{LoginUser.RealName}({LoginUser.Id})**{LoginUser.RealName}"); if (IsPublicPage) { LogRecorder.MonitorTrace("公共页面"); PagePower = new SimpleRolePower { Id = -1, PageItemId = -1, Power = 1, RoleId = LoginUser.RoleId }; } else { PageItem = ModelContext.PowerChecker.LoadPageConfig(CurrentPageName); if (PageItem == null) { LogRecorder.MonitorTrace("非法页面"); return(false); } if (PageItem.IsHide) { LogRecorder.MonitorTrace("隐藏页面"); PagePower = new SimpleRolePower { Id = -1, PageItemId = -1, Power = 1, RoleId = LoginUser.RoleId }; } else { PagePower = ModelContext.PowerChecker.LoadPagePower(ModelContext.LoginUser, PageItem); if (PagePower == null) { LogRecorder.MonitorTrace("非法访问"); return(false); } LogRecorder.MonitorTrace("授权访问"); } } ModelContext.PageItem = PageItem; ModelContext.CurrentPagePower = PagePower; return(true); }
/// <summary> /// 页面处理结束 /// </summary> protected override void OnResult() { Response.Clear(); try { if (string.IsNullOrWhiteSpace(CustomJson)) { #if NewJson var msg = string.IsNullOrEmpty(Message) ? (IsFailed ? BusinessContext.Current.LastMessage ?? "操作失败" : "操作成功") : Message.Replace('\"', '\''); if (AjaxResult == null) { AjaxResult = new AjaxResult { State = State, Succeed = !IsFailed, Message = msg, Message2 = Message2 }; } else { AjaxResult.Message = msg; AjaxResult.Message2 = Message2; AjaxResult.Succeed = !IsFailed; AjaxResult.State = State; } CustomJson = JsonConvert.SerializeObject(AjaxResult); #else var json = new StringBuilder(); json.AppendFormat(@"{{""succeed"":{0}", this.IsFailed ? "false" : "true"); json.AppendFormat(@",""message"":""{0}""", string.IsNullOrEmpty(this.Message) ? (this.IsFailed ? "操作失败" : "操作成功") : this.Message.Replace('\"', '\'')); if (!string.IsNullOrWhiteSpace(this.ResultData)) { json.AppendFormat(@",{0}", this.ResultData); } json.Append('}'); this.CustomJson = json.ToString(); #endif } Response.Write(CustomJson); } catch (Exception exception) { LogRecorder.Error(exception.ToString()); Debug.WriteLine(exception); Response.Write(@"{""succeed"":false,""message"":""***系统内部错误**""}"); } LogRecorder.MonitorTrace(CustomJson); }
/// <summary> /// 方法执行异常记录日志 /// </summary> /// <param name="invocation"></param> protected void AfterProceed(IInvocation invocation) { try { invocation.Proceed();//异常拦截 } catch (Exception ex) { LogRecorder.MonitorTrace($"异常信息:{JsonConvert.SerializeObject(ex)}"); } }
/// <summary> /// 远程调用 /// </summary> /// <returns></returns> private async Task <string> CallHttp() { var host = Data.RouteHost as HttpHost; if (host == null) { LogRecorder.MonitorTrace("Host Type Failed"); return(Data.ResultMessage); } // 当前请求调用的模型对应的主机名称 string httpHost; // 当前请求调用的Api名称 var httpApi = host == HttpHost.DefaultHost ? Data.Uri.PathAndQuery : $"{Data.ApiName}{Data.Uri.Query}"; // 查找主机 if (host.Hosts.Length == 1) { httpHost = host.Hosts[0]; } else { lock (host) { //平均分配 httpHost = host.Hosts[host.Next]; if (++host.Next >= host.Hosts.Length) { host.Next = 0; } } } // 远程调用 using (MonitorScope.CreateScope("CallHttp")) { var caller = new HttpApiCaller(httpHost) { Bearer = $"Bearer {ApiContext.RequestContext.Bear}" }; caller.CreateRequest(httpApi, Data.HttpMethod, Request, Data); Data.ResultMessage = await caller.Call(); Data.Status = caller.Status; LogRecorder.MonitorTrace(caller.Status.ToString()); LogRecorder.MonitorTrace(Data.ResultMessage); } return(Data.ResultMessage); }
/// <summary> /// 远程调用 /// </summary> /// <returns></returns> private string CallZero() { var values = new Dictionary <string, string>(); //参数解析 foreach (var query in Request.Query.Keys) { if (!values.ContainsKey(query)) { values.Add(query, Request.Query[query]); } } if (Data.HttpMethod == "POST") { if (Request.ContentLength > 0) { foreach (var form in Request.Form.Keys) { if (!values.ContainsKey(form)) { values.Add(form, Request.Form[form]); } } } } LogRecorder.BeginStepMonitor("内部Zero调用"); LogRecorder.MonitorTrace($"Station:{Data.HostName}"); LogRecorder.MonitorTrace($"Command:{Data.ApiName}"); // 远程调用状态 try { Data.ResultMessage = StationProgram.Call(Data.HostName, Data.ApiName, JsonConvert.SerializeObject(values)); } catch (Exception ex) { LogRecorder.Exception(ex); LogRecorder.MonitorTrace($"发生异常:{ex.Message}"); Data.ResultMessage = RouteRuntime.NetworkError; Data.Status = RouteStatus.RemoteError; } finally { LogRecorder.MonitorTrace(Data.ResultMessage); LogRecorder.EndStepMonitor(); } return(Data.ResultMessage); }
/// <summary> /// 准备 /// </summary> /// <param name="message">当前消息</param> /// <returns></returns> Task IMessageMiddleware.OnEnd(IInlineMessage message) { if (LogRecorder.LogMonitor) { LogRecorder.MonitorTrace("[State] {0} [Result]{1}", message.State, message.Result); if (message.Trace != null) { LogRecorder.MonitorTrace(() => $"[Trace] {message.Trace.ToJson()}"); } var root = LogRecorder.EndMonitor(); LogRecorder.TraceMonitor(root); } return(Task.CompletedTask); }
private void Prepare() { LogRecorder.MonitorTrace($"Station:{Station},Command:{Commmand}"); foreach (var handler in _handlers) { try { handler.Prepare(this); } catch (Exception e) { ZeroTrace.WriteException(Station, e, "PreActions", Commmand); } } }
/// <summary> /// 构造上下文 /// </summary> private void CreateApiContext(LoginUserInfo customer, string token) { ApiContext.SetCustomer(customer); ApiContext.SetRequestContext(new CallContext { Bear = token, Os = customer.Os, Browser = customer.Browser, RequestId = Guid.NewGuid(), ServiceKey = System.Configuration.ConfigurationManager.AppSettings["ServiceKey"], UserId = customer.UserId }); ApiContext.Current.Cache(); LogRecorder.MonitorTrace(JsonConvert.SerializeObject(customer)); }
private void End() { foreach (var handler in _handlers) { try { handler.End(this); } catch (Exception e) { ZeroTrace.WriteException(Station, e, "EndActions", Commmand); } } CheckStateResult(); LogRecorder.MonitorTrace($"Result:{Result}"); }