Exemple #1
0
 public static void Error(LogGroups group, string message)
 {
     if (IsGroupEnabled(group))
     {
         _logger.Error(FormatMessage(group, message));
     }
 }
Exemple #2
0
        /// <summary>
        /// Every time the SDK communicates with the API (or tries to), we can generate a nice log entry to show us exactly what happened and why.
        /// Depending on the configuration options, this might log all requests, or just the ones which fail. The level of detail can also be
        /// configured depending on different development / production scenarios and PCI considerations.
        /// </summary>
        /// <param name="request"></param>
        /// <param name="response"></param>
        public void LogRequest(HttpRequestMessage request, HttpResponseMessage response)
        {
            bool success     = false;
            bool serverError = false;

            if (response != null)
            {
                success     = (int)response.StatusCode < 400 && (int)response.StatusCode > 0;
                serverError = (int)response.StatusCode >= 500;
            }

            if ((_options.LoggingOptions.LogSuccessfulRequests && success))
            {
                var message = FormatLogMessage(request, response);
                _log.Info(message);
            }
            else if ((_options.LoggingOptions.LogFailedRequests && !success))
            {
                var message = FormatLogMessage(request, response);

                if (serverError)
                {
                    _log.Error(message);
                }
                else
                {
                    _log.Warn(message);
                }
            }
        }
Exemple #3
0
        public byte[] Read(int dataSize)
        {
            var result             = new byte[dataSize];
            var incomingBytesCount = 0;

            while (true)
            {
                try
                {
                    incomingBytesCount = SamStream.Read(result, 0, dataSize);
                    break;
                }
                catch (IOException ioe)
                {
                    Log.Error(ioe, "Failed to read from the stream due to connection issues.");
                    Dispose();

                    Log.Warning("Attempting reconnect...");
                    Reconnect();
                }
            }

            if (incomingBytesCount != dataSize)
            {
                Array.Resize(ref result, incomingBytesCount);
            }

            return(result);
        }
Exemple #4
0
        /// <summary>
        /// 处理用户消息
        /// </summary>
        /// <param name="webChatAuthConfig"></param>
        /// <param name="wxConfig"></param>
        /// <param name="xml"></param>
        /// <param name="errCode">错误码</param>
        public WebChatMessage ProcessRequest(WebChatAuthConfig webChatAuthConfig, WxConfig wxConfig, string xml,
                                             int?errCode = null)
        {
            WebChatMessage refundReponse = null;

            try
            {
                if (!string.IsNullOrEmpty(Auth(webChatAuthConfig, wxConfig)))
                {
                    throw new BusinessException("签名错误", HttpStatus.Err.Id);
                }

                refundReponse = _xmlProvider.Deserialize <WebChatMessage>(xml);
                if (refundReponse == null)
                {
                    throw new BusinessException("参数错误", HttpStatus.Err.Id);
                }
            }
            catch (System.Exception e)
            {
                _logService.Error("接受用户信息错误:", e);
            }

            return(refundReponse);
        }
Exemple #5
0
 /// <summary>
 /// 添加日志
 /// </summary>
 /// <param name="context"></param>
 private void AddLog(ActionExecutingContext context)
 {
     try
     {
         byte[] byts = new byte[context.HttpContext.Request.Body.Length];
         context.HttpContext.Request.Body.Read(byts, 0, byts.Length);
         string param = System.Text.Encoding.Default.GetString(byts);
         _logService.Error($"模型校验异常,请求接口路径:{context.HttpContext.Request.Scheme},请求参数:{param}");
     }
     catch (System.Exception e)
     {
         _logService.Error("模型校验异常,处理日志异常");
     }
 }
        protected virtual void Dispose(bool disposing)
        {
            if (!_disposed)
            {
                return;
            }

            if (disposing)
            {
                if (_queryArgs != null && _queryArgs.PersistentConnection != null)
                {
                    try
                    {
                        _queryArgs.PersistentConnection.Dispose();
                        _queryArgs.PersistentConnection = null;
                    }
                    catch (Exception ex)
                    {
                        if (_log != null)
                        {
                            _log.Error("Error disposing OleDbConnection", ex);
                        }
                    }
                }
            }

            _queryArgs = null;
            _disposed  = true;
        }
Exemple #7
0
        /// <summary>
        /// Logs to internal.
        /// </summary>
        /// <param name="level">The level.</param>
        /// <param name="message">The message.</param>
        /// <param name="provider">The provider.</param>
        /// <param name="category">The category.</param>
        /// <exception cref="ArgumentOutOfRangeException">level - null</exception>
        private static void LogToInternal(LogLevel level, string message, ILogProvider provider, string category)
        {
            switch (level)
            {
            case LogLevel.FATAL:
                provider.Fatal(category, message);
                break;

            case LogLevel.ERROR:
                provider.Error(category, message);
                break;

            case LogLevel.WARNING:
                provider.Warning(category, message);
                break;

            case LogLevel.INFO:
                provider.Info(category, message);
                break;

            case LogLevel.TRACE:
                provider.Trace(category, message);
                break;

            case LogLevel.DEBUG:
                provider.Debug(category, message);
                break;

            default:
                throw new ArgumentOutOfRangeException(nameof(level), level, null);
            }
        }
Exemple #8
0
        private static Object? Decode(this CustomAttribute attribute, Type actualType, ILogProvider? log = null)
        {
            Object? obj = null;
            var args = MapCustomAtribArgs(attribute.ConstructorArguments, log);
            try
            {          
                obj = Activator.CreateInstance(actualType, args);
            } catch(Exception e)
            {
                log?.Error($"Error constructing patcher from attribute:\n{e}");
                log?.Message($"Arg info:\n    {String.Join("\n    ", attribute.ConstructorArguments.Select(ca => ca.Type.FullName))}");
                log?.Message($"Read args:\n    {String.Join("\n    ", args.Select(a => $"{a?.GetType()?.FullName} {a?.ToString()}"))}");
            }

            foreach(CANamedArgument? namedArg in attribute.NamedArguments)
            {
                var type = Type.GetType(namedArg.Type.AssemblyQualifiedName);
                if(type is null) return null;
                if(namedArg.IsField)
                {
                    FieldInfo? fld = actualType.GetFieldOfType(namedArg.Name, type);
                    if(fld is null) return null;
                    fld.SetValue(obj, namedArg.Value);
                } else if(namedArg.IsProperty)
                {
                    PropertyInfo? prop = actualType.GetPropertyOfType(namedArg.Name, type, true);
                    if(prop is null) return null;
                    prop.SetMethod!.Invoke(obj, new[] { namedArg.Value });
                }
            }
            return obj;
        }
Exemple #9
0
 public static void CallMe()
 {
     for (int i = 1; i <= 5; i++)
     {
         log.Info($"{i} - Info text");
         log.Debug($"{i} - Debug text");
         log.Warning($"{i} - Warning text");
         log.Error($"{i} - Error text");
     }
 }
Exemple #10
0
        /// <summary>
        /// 上传文件
        /// </summary>
        /// <param name="stream"></param>
        /// <param name="key">文件地址</param>
        /// <param name="ext">扩展名</param>
        /// <exception cref="Exception"></exception>
        internal virtual bool UploadFile(Stream stream, string key, string ext)
        {
            HttpWebRequest  request  = null;
            HttpWebResponse response = null;

            try
            {
                request           = (HttpWebRequest)WebRequest.Create(Utils.GetUrl(UCloudConfig, key));
                request.KeepAlive = false;
                Utils.SetHeaders(request, ext, UCloudConfig, key, "PUT");
                Utils.CopyFile(request, stream);

                response = HttpWebResponseExt.GetResponseNoException(request);
                Stream body = response.GetResponseStream();
                if (response.StatusCode != HttpStatusCode.OK)
                {
                    string e = FormatString(body);
                    LogService.Error(string.Format("{0} {1}", response.StatusDescription, e));
                    return(false);
                }
            }
            catch (Exception e)
            {
                LogService.Error(e.ToString());
                return(false);
            }
            finally
            {
                if (request != null)
                {
                    request.Abort();
                }
                if (response != null)
                {
                    response.Close();
                }
            }

            return(true);
        }
Exemple #11
0
        private MockScenario LoadScenario(string scenarioName)
        {
            var scenarioStream = _scenarioResolver.Resolve(scenarioName);

            if (scenarioStream == null)
            {
                _logProvider.Warning("scenario {scenarioName} was not found.", scenarioName);
                return(null);
            }
            else
            {
                try
                {
                    var scenarioReader = new StreamReader(scenarioStream);
                    var scenarioSource = scenarioReader.ReadToEnd();
                    var mockScenario   = _deserializer.Deserialize <MockScenario>(scenarioSource);
                    mockScenario.Name = scenarioName; //Ensure scenario name is correct.
                    _routes.Add(new RouteKey(mockScenario), new Route(mockScenario));
                    return(mockScenario);
                }
                catch (SyntaxErrorException e)
                {
                    var message = $"error parsing scenario \"{scenarioName}\": {e.Message}";
                    _logProvider.Error(e, "error parsing scenario {scenarioName}: {reason}", scenarioName, e.Message);
                    throw new System.Exception(message, e);
                }
                catch (Exception e)
                {
                    var message = $"error loading scenario \"{scenarioName}\": {e}";
                    _logProvider.Error(e, "error loading scenario \"{scenarioName}\": {reason}", scenarioName, e.Message);
                    throw new System.Exception(message, e);
                }
                finally
                {
                    scenarioStream.Dispose();
                }
            }
        }
Exemple #12
0
        public async Task <TResponse> ExecuteAsync(ServiceRequest request, Func <Task> action)
        {
            Guard.ThrowIfNull(request, nameof(request));
            Guard.ThrowIfNull(action, nameof(action));

            ServiceResponse response;

            _logger.Information(request.CorrelationId, $"{action.Method.Name} => Started");

            var timer = new Stopwatch();

            try
            {
                timer.Start();
                await action();

                timer.Stop();

                _logger.Verbose(request.CorrelationId, $"{action.Method.Name} => Execution time: {timer.ElapsedMilliseconds}.");

                response = new OkResponse(request.CorrelationId);
            }
            catch (Exception ex)
            {
                _logger.Error(request.CorrelationId, ex, $"{action.Method.Name} => Failed.");

                response = new FailedResponse(request.CorrelationId, ex, action.Method.Name);
            }
            finally
            {
                _logger.Information(request.CorrelationId, $"{action.Method.Name} => Finished.");
            }

            var convertedResponse = _converter(response);

            return(convertedResponse);
        }
Exemple #13
0
        private string WriteLog(HttpActionExecutedContext context, Exception ex)
        {
            HttpActionContext actionContext = context.ActionContext;

            // username
            string userName = GetUserName(actionContext);

            // userhostaddress
            HttpRequestMessage request         = actionContext.Request;
            IPAddress          userHostAddress = GetUserHostAddress(request);

            // useragent
            HttpHeaderValueCollection <ProductInfoHeaderValue> userAgent = null;

            if (request?.Headers?.UserAgent != null)
            {
                userAgent = request.Headers.UserAgent;
            }

            // path
            string reference = request?.RequestUri?.AbsolutePath;

            Guid         logId   = Guid.NewGuid();
            const string MESSAGE = "User: {UserName}\r\nServer: {Server}\r\nResource: {Reference}\r\nHost: {Host} Agent: {Agent}";

            if (ex is UnauthorizedAccessException)
            {
                _logger.Information(ex, "[403] " + MESSAGE, userName,
                                    reference, Environment.MachineName, userHostAddress, userAgent);
            }
            else if (ex is NotFoundApplicationException)
            {
                _logger.Information(ex, "[404] " + MESSAGE, userName,
                                    reference, Environment.MachineName, userHostAddress, userAgent);
            }
            else if (ex is ApplicationException)
            {
                _logger.Information(ex, "[400] " + MESSAGE, userName,
                                    reference, Environment.MachineName, userHostAddress, userAgent);
            }
            else
            {
                _logger.Error(ex, "[500] [{Id}] " + MESSAGE, logId, userName,
                              reference, Environment.MachineName, userHostAddress, userAgent);
            }

            return(logId.ToString());
        }
Exemple #14
0
                internal void EmitToBody(MethodDef target, ILogProvider log)
                {
                    if (!this.canEmit)
                    {
                        log.Error("Incomplete prep for emit, returning");
                        return;
                    }


                    log.Message($"Emitting opcodes");
                    var module = target.Module;
                    var body   = target.Body = new();


                    void EmitOp(Instruction instr)
                    {
                        log.Message($"Emit: {LogOp(instr)}");
                        if (instr is null)
                        {
                            return;
                        }
                        body !.Instructions.Add(instr);
                    }

                    String LogOp(Instruction instr) => instr is null ? "Null instruction" : $"{instr.OpCode.Name} ( {instr.Operand?.GetType()?.Name ?? "null"} {instr.Operand})";

                    body.KeepOldMaxStack = true;
                    foreach (var l in this.localDatas)
                    {
                        body.Variables.Add(l);
                    }
                    foreach (var em in this.instructionEmitters)
                    {
                        EmitOp(em.Emit(module));
                        foreach (var extra in em.EmitRest(module))
                        {
                            EmitOp(extra);
                        }
                    }
                    log.Message($"Finished body:\n{String.Join(Environment.NewLine, body.Instructions.Select(LogOp))}");
                }
Exemple #15
0
 public static void Error(string errMsg, Exception ex)
 {
     CheckLogProviderNotNull();
     staticLogProvider.Error(errMsg, ex);
 }
Exemple #16
0
        public IMockEngineResponse Invoke(string scenarioName, object dynamicProperties = null)
        {
            if (scenarioName == null)
            {
                throw new ArgumentNullException(nameof(scenarioName));
            }

            _logProvider.Verbose("Invoking scenario {scenarioName}", scenarioName);

            var scenario = _scenarioManager.GetScenario(scenarioName);

            if (scenario == null)
            {
                throw new ArgumentOutOfRangeException(nameof(scenarioName), $"scenario \"{scenarioName}\" was not found.");
            }

            using (var scriptEngine = new V8ScriptEngine())
            {
                scriptEngine.AllowReflection = true;

                scriptEngine.Script["scenarioName"] = scenarioName;

                SetInputParameters(scriptEngine, dynamicProperties);

                SetGlobals(scriptEngine, scenario);

                if (scenario.Global != null && !string.IsNullOrWhiteSpace(scenario.Global.Before))
                {
                    try
                    {
                        scriptEngine.Execute(scenario.Global.Before);
                    }
                    catch (Exception e)
                    {
                        throw new MockEngineException(this.Name, scenarioName, $"error executing global Before code: {e.Message}", e);
                    }
                }

                MockEngineResponse response = null;

                foreach (var action in scenario.Actions)
                {
                    try
                    {
                        if (action.When == null)
                        {
                            response = ExecuteAction(scriptEngine, scenarioName, action);
                            break;
                        }
                        else
                        {
                            var caseResult = scriptEngine.Evaluate(action.When);
                            if (caseResult is bool)
                            {
                                if ((bool)caseResult)
                                {
                                    response = ExecuteAction(scriptEngine, scenarioName, action);
                                    break;
                                }
                            }
                            else
                            {
                                _logProvider.Warning("action: {action} case expression did not return a boolean result", action);
                            }
                        }
                    }
                    catch (MockEngineException e)
                    {
                        var message = $"action: {action} exception: {e.Message}";
                        _logProvider.Error(e, "action: {action} exception: {message}", action, e.Message);
                        throw new MockEngineException(this.Name, scenarioName, message, e);
                    }
                    catch (Exception e)
                    {
                        _logProvider.Error(e, "action: {action} exception: {message}", action, e.Message);
                        throw new MockEngineException(this.Name, scenarioName, $"action: {action} exception: {e.Message}", e);
                    }
                }
                if (scenario.Global != null && !string.IsNullOrWhiteSpace(scenario.Global.After))
                {
                    try
                    {
                        scriptEngine.Execute(scenario.Global.After);
                    }
                    catch (Exception e)
                    {
                        throw new MockEngineException(this.Name, scenarioName, $"error executing global After code: {e.Message}", e);
                    }
                }

                if (response != null)
                {
                    return(response);
                }
            }

            var reasonPhrase = $"scenario: \"{scenarioName}\" did not contain any matching actions for this request.";

            _logProvider.Error("scenario: {scenarioName} did not contain any matching actions for this request.", scenarioName);

            return(new MockEngineResponse()
            {
                ReasonPhrase = reasonPhrase
            });
        }
Exemple #17
0
        /// <summary>
        /// Create a new Automapper type adapter factory
        /// </summary>
        public AutomapperTypeAdapterFactory()
        {
            var tempAssemblys = NS.Framework.Config.PlatformConfig.ServerConfig.IOCSetting.ConfigurationItems.Select(pre => pre.Value);

            //scan all assemblies finding Automapper Profile
            var tempAllAssemblys = AppDomain.CurrentDomain.GetAssemblies().Where(pre =>
                                                                                 !pre.GetName().Name.ToLower().EndsWith("fakes.test") &&
                                                                                 !pre.GetName().Name.ToLower().EndsWith("fakes") &&
                                                                                 !pre.GetName().Name.ToLower().StartsWith("system.") &&
                                                                                 !pre.GetName().Name.ToLower().StartsWith("microsoft.") &&
                                                                                 !pre.GetName().Name.ToLower().StartsWith("entity") &&
                                                                                 !pre.GetName().Name.ToLower().StartsWith("auto")
                                                                                 ).ToList();

            IList <Assembly> tempAssemblyList  = new List <Assembly>();
            List <string>    tempAssemblyNames = new List <string>();

            foreach (var tempAssembly in tempAssemblys)
            {
                tempAssemblyNames.AddRange(tempAssembly.Split(';'));
            }

            foreach (var tempAllAssembly in tempAllAssemblys)
            {
                var tempAssemblyName = tempAllAssembly.GetName().Name;

                if (tempAssemblyNames.Where(pre => pre.Trim().ToLower().Contains(tempAssemblyName.ToLower())).Count() > 0)
                {
                    tempAssemblyList.Add(tempAllAssembly);
                }
            }

            //var assemblys = AppDomain.CurrentDomain
            //                        .GetAssemblies().Where((Assembly assembly) =>
            //                        {
            //                            return tempAssemblys.Where(pre => pre.Split(';').Contains(assembly.GetName().Name)).Count() > 0;
            //                            //&& !pre.GetName().Name.ToLower().EndsWith("fakes.test")
            //                            //&& !pre.GetName().Name.ToLower().EndsWith("fakes")
            //                            //&& !pre.GetName().Name.ToLower().StartsWith("system.")
            //                            //&& !pre.GetName().Name.ToLower().StartsWith("microsoft.")
            //                            //&& !pre.GetName().Name.ToLower().StartsWith("entity")
            //                            //&& !pre.GetName().Name.ToLower().StartsWith("auto")
            //                        }).ToList();
            var profiles = tempAssemblyList.SelectMany(pre => pre.GetTypes()).Where(t => t.BaseType == typeof(DomainDtoMapProfile)).Distinct().ToList();

            int count = profiles.Count();

            try
            {
                //Mapper.Initialize(cfg =>
                //{
                //    foreach (var item in profiles)
                //    {
                //        if (item.FullName != "AutoMapper.SelfProfiler`2")
                //            cfg.AddProfile(Activator.CreateInstance(item) as Profile);
                //    }
                //});
                foreach (var item in profiles)
                {
                    var tempProfile = Activator.CreateInstance(item) as DomainDtoMapProfile;
                    tempProfile.Configure();
                }
            }
            catch (Exception ex)
            {
                ILogProvider logger = ObjectContainer.CreateInstance <ILogProvider>();
                //logger.Error("初始化Automapper的过程中出现错误:" + ex.Message);
                logger.Error("初始化mapper的过程中出现错误:" + ex.Message);
            }
        }
Exemple #18
0
 public void Error(string message)
 {
     _provider.Error(message);
 }
Exemple #19
0
 public DataTable this[string tableName]
 {
     get
     {
         if (tableName == null)
         {
             _logProvider.Error("in your call to tables[tableName], tableName cannot be null");
             throw new ArgumentNullException(nameof(tableName));
         }
         var table = this.DataSet.Tables[tableName];
         if (table == null)
         {
             var message = $"table \"{tableName} not found";
             _logProvider.Error("table \"{tableName} not found", tableName);
             throw new ArgumentOutOfRangeException(nameof(tableName), message);
         }
         return(table);
     }
 }