Ejemplo n.º 1
0
 public IHttpActionResult Get()
 {
     try
     {
         var carts =
             db.Cart_Infos.Where(
                 o => !o.State && (o.OpenId == WeiChatApplicationContext.Current.WeiChatUser.OpenId))
             .OrderByDescending(o => o.CreateTime)
             .ToList();
         var val = carts.ConvertAll(v => new
         {
             Cart    = v,
             Product = (from product in db.Product_Infos
                        join photo in db.Site_Photos on product.Id equals photo.GalleryId
                        where product.Id == v.ProductID
                        select new { product.Id, product.Name, product.Price, product.State, photo.Url }).FirstOrDefault(),
             Package = db.Product_ProductAttributes.FirstOrDefault(o => o.AttributeId == v.PackageID)
         });
         return(Ok(val));
     }
     catch (Exception ex)
     {
         log.Log(LoggerLevels.Error, "Cart:" + ex.Message);
         return(BadRequest(ex.Message));
     }
 }
Ejemplo n.º 2
0
 public static void Log(string nameOfObject, LogLevel logLevel, string message)
 {
     if (!initialized)
     {
         InitLogger(logLevel);
     }
     if (LogLevelLowerOrEqualTo(logLevel))
     {
         logger.Log(nameOfObject, logLevel, message);
     }
 }
Ejemplo n.º 3
0
        public ActionResult PayNotify(int tenantId)
        {
            Action <NotifyResult> successAction = result =>
            {
                var resultLog = JsonConvert.SerializeObject(result);
                using (var context = new AppDbContext())
                {
                    var order = context.Order_Infos.FirstOrDefault(o => o.Code == result.OutTradeNo);
                    if (null != order)
                    {
                        //修改订单状态
                        order.State        = EnumOrderStatus.Overhang;
                        order.ThirdPayType = EnumThirdPayType.WX;
                        order.PaymentOn    = DateTime.Now;
                        order.UpdateTime   = DateTime.Now;
                        //需要更新订单对应的商品的已成交数
                        var lst_details = db.Order_Details.Where(p => p.OrderID == order.Id).ToList();
                        foreach (Order_Detail detail in lst_details)
                        {
                            Product_Info product = db.Product_Infos.FirstOrDefault(
                                p => p.Id == detail.ProductID);
                            product.SellCount = product.SellCount + detail.Quantity;
                        }
                        context.SaveChanges();
                        //记录支付日志
                        using (var payLogDo = new PayLogDO(order.TenantId, order.OpenId, order.ClientIpAddress, context))
                        {
                            payLogDo.AddOrderLog(order.Id, order.TotalPrice, paymentInterfaceLog: resultLog);
                        }
                    }
                    else
                    {
                        logger.Log(LoggerLevels.Error, "Order information does not exist!OrderId:" + result.OutTradeNo);
                    }
                }
                //此处编写成功处理逻辑
                logger.Log(LoggerLevels.Debug, "Success: JSON:" + resultLog);
            };
            Action <NotifyResult> failAction = result =>
            {
                //此处编写失败处理逻辑
                var failLog = JsonConvert.SerializeObject(result);
                logger.Log(LoggerLevels.Error, "Fail: JSON:" + failLog);
                using (var context = new AppDbContext())
                {
                    var order = context.Order_Infos.FirstOrDefault(o => o.Code == result.OutTradeNo);
                    //记录支付日志
                    using (var payLogDo = new PayLogDO(order.TenantId, order.OpenId, order.ClientIpAddress, context))
                    {
                        payLogDo.AddOrderLog(order.Id, order.TotalPrice, paymentInterfaceLog: failLog, errorLog: failLog);
                    }
                }
            };

            return
                (Content(WeChatApisContext.Current.TenPayV3Api.NotifyAndReurnResult(Request.InputStream, successAction,
                                                                                    failAction)));
        }
 public IEnumerable <Activity> Get([FromBody] GetTrackingTimeModel model)
 {
     try
     {
         var all_act = _dataProvider.GetAllActivities().Where(x => x.EmployeeID == model.ID && x.ActivityDate == model.Date);
         _logger.Log("GET TRACKING TIME: 200 OK, {numAct} ACTIVITIES FOUND.", LogLevel.Debug, all_act.Count());
         return(all_act);
     }
     catch (Exception e)
     {
         _logger.Log("Error occured. Exception: \n{ExceptionMessage}\n{ExceptionStackTrace}", LogLevel.Error, e.Message, e.StackTrace);
         return(null);
     }
 }
Ejemplo n.º 5
0
        public override void OnActionExecuted(ActionExecutedContext filterContext)
        {
            currentStopwatch.Stop();

            var log = string.Format("controller:{0},action:{1},execution time:{2}ms",
                                    filterContext.ActionDescriptor.ControllerDescriptor.ControllerName,
                                    filterContext.ActionDescriptor.ActionName, currentStopwatch.ElapsedMilliseconds);

            _logger.Log(LoggerLevels.Info, log);
            if (currentStopwatch.ElapsedMilliseconds > WarnThreshold)
            {
                _logger.Log(LoggerLevels.Warn, log);
            }
        }
Ejemplo n.º 6
0
        /// <summary>
        ///     记录异常日志
        /// </summary>
        /// <param name="logger">日志记录器</param>
        /// <param name="exception">异常</param>
        public static void LogException(this LoggerBase logger, Exception exception)
        {
            logger.Log(LoggerLevels.Error, exception);
            if (exception is AggregateException && (exception.InnerException != null))
            {
                var aggException = exception as AggregateException;
                if (aggException.InnerException is DbEntityValidationException)
                {
                    var sb = new StringBuilder();
                    var validationException = aggException.InnerException as DbEntityValidationException;
                    sb.AppendLine("实体验证错误。错误数:" + validationException.EntityValidationErrors.Count() + " ");
                    foreach (var validationResult in validationException.EntityValidationErrors)
                    {
                        foreach (var item in validationResult.ValidationErrors)
                        {
                            sb.AppendFormat("({0}:{1})", item.PropertyName, item.ErrorMessage);
                        }
                    }
                    logger.Log(LoggerLevels.Error, sb.ToString());
                }
            }
            else if (exception is DbEntityValidationException)
            {
                var sb = new StringBuilder();
                var validationException = exception as DbEntityValidationException;
                sb.AppendLine("实体验证错误。错误数:" + validationException.EntityValidationErrors.Count() + " ");
                foreach (var validationResult in validationException.EntityValidationErrors)
                {
                    foreach (var item in validationResult.ValidationErrors)
                    {
                        sb.AppendFormat("({0}:{1})", item.PropertyName, item.ErrorMessage);
                    }
                }
                logger.Log(LoggerLevels.Error, sb.ToString());
            }

            else if (exception is ReflectionTypeLoadException)
            {
                var refEx = exception as ReflectionTypeLoadException;
                if (refEx.LoaderExceptions.Length <= 0)
                {
                    return;
                }
                foreach (var loaderEx in refEx.LoaderExceptions)
                {
                    LogException(logger, loaderEx);
                }
            }
        }
Ejemplo n.º 7
0
 public IEnumerable <Employee> Get()
 {
     try
     {
         var allEmp = _dataProvider.GetAllEmployees();
         _logger.Log("Employees list obtained successfully.", LogLevel.Debug);
         return(allEmp);
     }
     catch (Exception e)
     {
         _logger.Log("Could not obtain employees list. Error Message: \n{ErrorMessage}\n{ErrorStackTrace}",
                     LogLevel.Error, e.Message, e.StackTrace);
         return(null);
     }
 }
 public IEnumerable <Activity> Get()
 {
     try
     {
         var act = _dataProvider.GetAllActivities();
         _logger.Log("Activities obtained successfully.", LogLevel.Debug);
         return(act);
     }
     catch (Exception e)
     {
         _logger.Log("GetAllActivities failed. \n{ExceptionMessage}\n{ExceptionStackTrace}",
                     LogLevel.Error, e.Message, e.StackTrace);
         return(null);
     }
 }
        public async Task <JsonResult> Post([FromBody] ActivityType activityType)
        {
            try
            {
                var id = await _dataProvider.CreateActivityTypeAsync(activityType);

                _logger.Log("Activity type created successfully. {@ActivityType}", LogLevel.Debug, activityType);
                return(new JsonResult(new { status = "Activity type created successfully", ActivityTypeID = id }));
            }
            catch (Exception e)
            {
                _logger.Log("Activity type creation failed. \n{ExceptionMessage}\n{ExceptionStackTrace}",
                            LogLevel.Error, e.Message, e.StackTrace);
                return(new JsonResult(new { status = "Error occured." }));
            }
        }
        /// <summary>
        /// Finds and builds project and returns the built assembly.
        /// </summary>
        /// <param name="projectPath"></param>
        /// <returns></returns>
        internal Assembly LoadEvalutionProject(string projectPath)
        {
            LoggerBase.Log("Loading project file: " + projectPath, isDebugMessage: true);
            var project = GetEvalutionProject(projectPath);

            LoggerBase.Log("Building project file", isDebugMessage: true);
//            project.SetGlobalProperty("Configuration", "Debug");
            project.Build(new MsBuildLogger());

            var outputPath = project.GetPropertyValue("OutputPath");

            LoggerBase.Log("Project file outputpath: " + (!string.IsNullOrWhiteSpace(outputPath) ? outputPath : "output path was EMPTY -- this might cause an error"), isDebugMessage: true);

            var name = project.GetPropertyValue("AssemblyName");

            LoggerBase.Log("Project file assembly name: " + name, isDebugMessage: true);

            var fullPath = Path.Combine(project.DirectoryPath, outputPath);
            var path     = Path.Combine(fullPath, name + ".dll");

            LoggerBase.Log("Loading DLL: " + path, isDebugMessage: true);

            var projectAssembly = Assembly.LoadFile(path);

            LoggerBase.Log("", isDebugMessage: true);
            return(projectAssembly);
        }
Ejemplo n.º 11
0
        /// <summary>
        /// Applies all migrations for the given repository.
        /// </summary>
        /// <param name="criteria"></param>
        public void ApplyMigrations(ApplyMigrationCriteria criteria)
        {
            var configurationStatus = GetMigrationConfigurationStatus(criteria.ProjectPath, criteria.RepoName);

            if (!configurationStatus.Enabled)
            {
                LoggerBase.Log("Migrations are not enabled, can not apply any migrations.");
                return;
            }

            if (configurationStatus.MigrationType != MigrationToUse.Manual)
            {
                LoggerBase.Log("Manual Migrations are not enabled, can not apply any migrations.");
                return;
            }

            var repoInfo = TypeHandler.FindSingleRepo(criteria.ProjectPath, criteria.RepoName);

            //if null we need to drop out.
            if (repoInfo == null)
            {
                return;
            }

            AssertRepoHasEmptyConstructor(repoInfo.RepoType);
            EnsureDbAndMigrationTableExists(criteria.ProjectPath, repoInfo.RepoType, criteria.ConfigFilePath);

            var runner = new MigrationRunner();

            runner.ApplyMigrations(criteria);

            //clean up
            ProjectEvalutionHelper.FinishedWithProject(criteria.ProjectPath);
        }
Ejemplo n.º 12
0
        /// <summary>
        /// Creates a instance of the base repo class from the given type.
        /// </summary>
        /// <param name="projectDllPath"></param>
        /// <param name="typeofRepo"></param>
        /// <param name="args"></param>
        /// <returns></returns>
        internal static BaseRepo CreateRepoBase(string projectDllPath, Type typeofRepo, params object[] args)
        {
            AssemblyLoadingHelper.Reset();
            AssemblyLoadingHelper.AddHintPath(projectDllPath);
            AppDomain.CurrentDomain.AssemblyResolve += AssemblyLoadingHelper.OnAssemblyResolve;

            var repoBase = args == null || !args.Any() ? Activator.CreateInstance(typeofRepo) : Activator.CreateInstance(typeofRepo, args);

            if (repoBase == null)
            {
                LoggerBase.Log("Couldn't create repo, must have parameterless constructor");
                return(null);
            }

            var repo = repoBase as BaseRepo;

            if (repo == null)
            {
                LoggerBase.Log("Repo created does not inherit from BaseRepo");
                return(null);
            }

            AssemblyLoadingHelper.Reset();
            AppDomain.CurrentDomain.AssemblyResolve -= AssemblyLoadingHelper.OnAssemblyResolve;
            return(repo);
        }
Ejemplo n.º 13
0
        public void ReBindValues()
        {
            try
            {
                EmailConfiguration emailConfiguration = mailService.GetEmailConfiguration();
                if (emailConfiguration != null)
                {
                    txtFrom.Text         = emailConfiguration.From;
                    txtTo.Text           = string.Join(",", emailConfiguration.To);
                    txtCC.Text           = string.Join(",", emailConfiguration.CC);
                    txtBCC.Text          = string.Join(",", emailConfiguration.BCC);
                    txtSubject.Text      = emailConfiguration.Subject;
                    webBody.DocumentText = mailService.GetEmailBody(dteDate.Value.ToShortDateString());

                    btnSendMail.Visible = true;
                }
                else
                {
                    btnSendMail.Visible = false;
                }
            }
            catch (Exception ex)
            {
                logger.Log(ex);
                throw;
            }
        }
Ejemplo n.º 14
0
        /// <summary>
        /// Automatically update the database schema to bring it up to date.
        /// </summary>
        /// <param name="criteria">creation criteria</param>
        public void UpdateDatabaseAutomatically(AutomaticUpdateCriteria criteria)
        {
            var configurationStatus = GetMigrationConfigurationStatus(criteria.ProjectFilePath, criteria.RepoName);

            if (!configurationStatus.Enabled)
            {
                LoggerBase.Log("Migrations are not enabled, can not apply any migrations.");
                return;
            }

            if (configurationStatus.MigrationType != MigrationToUse.Automatic)
            {
                LoggerBase.Log("automatic Migrations are not enabled, can not apply any migrations.");
                return;
            }

            var repoInfo = TypeHandler.FindSingleRepo(criteria.ProjectFilePath, criteria.RepoName);

            //if null we need to drop out.
            if (repoInfo == null)
            {
                return;
            }

            AssertRepoHasEmptyConstructor(repoInfo.RepoType);
            EnsureDbAndMigrationTableExists(criteria.ProjectFilePath, repoInfo.RepoType, criteria.ConfigFilePath);

            var updater = CreateSchemaUpdater(repoInfo.Assembly.Location, repoInfo.RepoType, criteria.ConfigFilePath);

            updater.Execute(true, true);

            //clean up
            ProjectEvalutionHelper.FinishedWithProject(criteria.ProjectFilePath);
        }
Ejemplo n.º 15
0
 public static void LogExceptionOrThrowIt(LoggerBase logger, LogLevel logLevel, Exception exception, string errorMessage)
 {
     if (!ExecuteIfParamIsNotNull(logger, () => logger.Log(logLevel, exception, errorMessage)))
     {
         throw new ApplicationException(errorMessage, exception);
     }
 }
Ejemplo n.º 16
0
 public IEnumerable <Project> Get()
 {
     try
     {
         var allp = _dataProvider.GetAllProjects();
         _logger.Log("Got all projects successfully.",
                     LogLevel.Debug);
         return(allp);
     }
     catch (Exception e)
     {
         _logger.Log("GetAllProjects failed. \n{ExceptionMessage}\n{ExceptionStackTrace}",
                     LogLevel.Error, e.Message, e.StackTrace);
         return(null);
     }
 }
 public Project Get(int id)
 {
     try
     {
         var p = _dataProvider.GetProject(id);
         _logger.Log("Got project by id.\n{@Project}",
                     LogLevel.Debug, p);
         return(p);
     }
     catch (Exception e)
     {
         _logger.Log("Project search by id failed. \n{ExceptionMessage}\n{ExceptionStackTrace}",
                     LogLevel.Error, e.Message, e.StackTrace);
         return(null);
     }
 }
Ejemplo n.º 18
0
 public async Task <JsonResult> Post([FromBody] Role role)
 {
     try
     {
         var id = _dataProvider.CreateRoleAsync(role);
         _logger.Log("Role created successfully. \n{@Role}",
                     LogLevel.Debug, role);
         return(new JsonResult(new { status = "Role added successfully.", RoleID = id }));
     }
     catch (Exception e)
     {
         _logger.Log("Role creation failed. \n{ExceptionMessage}\n{ExceptionStackTrace}",
                     LogLevel.Error, e.Message, e.StackTrace);
         return(new JsonResult(new { status = "Error occured." }));
     }
 }
 public JsonResult Post([FromBody] Project p)
 {
     try
     {
         _dataProvider.UpdateProject(p);
         _logger.Log("Project updated successfully. {@Project}",
                     LogLevel.Debug, p);
         return(new JsonResult(new { status = "Project updated successfully." }));
     }
     catch (Exception e)
     {
         _logger.Log("Project update failed. \n{ExceptionMessage}\n{ExceptionStackTrace}",
                     LogLevel.Error, e.Message, e.StackTrace);
         return(new JsonResult(new { status = "Error occured." }));
     }
 }
Ejemplo n.º 20
0
 public JsonResult DeleteProject(int?id)
 {
     try
     {
         _dataProvider.DeleteProject((int)id);
         _logger.Log("Project with ID {ProjectID} deleted successfully.",
                     LogLevel.Debug, id);
         return(new JsonResult(new { status = "Project deleted successfully." }));
     }
     catch (Exception e)
     {
         _logger.Log("Project deletion failed. \n{ExceptionMessage}\n{ExceptionStackTrace}",
                     LogLevel.Error, e.Message, e.StackTrace);
         return(new JsonResult(new { status = "Error occured." }));
     }
 }
Ejemplo n.º 21
0
        /// <summary>
        /// Creates a new provider with the related configuration.
        /// </summary>
        /// <param name="config"></param>
        internal ProviderBase(Configurations.DataTarget config, LoggerBase logger)
        {
            _logger = logger;

            _logger.Log(config.Name, LoggerPriorities.Verbose, "Initializing");

            _config = config;
        }
Ejemplo n.º 22
0
        public IHttpActionResult DelAddress([FromBody] User_Address model)
        {
            log.Log(LoggerLevels.Debug, "进入API[DelAddress]");
            var address = db.User_Addresses.Find(model.Id);

            if (address == null)
            {
                log.Log(LoggerLevels.Debug, "id为:" + model.Id + "数据库查询不到记录");
            }
            else
            {
                log.Log(LoggerLevels.Debug, JsonConvert.SerializeObject(address));
            }
            db.User_Addresses.Remove(address);
            db.SaveChanges();
            return(Ok());
        }
        public async Task <JsonResult> Post([FromBody] Employee emp)
        {
            try
            {
                var id = await _dataProvider.CreateEmployeeAsync(emp);

                _logger.Log("Employee Created Successfully. \n{@Employee}",
                            LogLevel.Debug, emp);
                return(new JsonResult(new { status = "Employee created successfully", EmployeeID = id }));
            }
            catch (Exception e)
            {
                _logger.Log("Employee creation failed. \n{ExceptionMessage}\n{ExceptionStackTrace}",
                            LogLevel.Error, e.Message, e.StackTrace);
                return(new JsonResult(new { status = "Error occured" }));
            }
        }
Ejemplo n.º 24
0
        public async Task <JsonResult> Post([FromBody] Project p)
        {
            try
            {
                var id = await _dataProvider.CreateProjectAsync(p);

                _logger.Log("Project created successfully. \n{@Project}",
                            LogLevel.Debug, p);
                return(new JsonResult(new { status = "Project added successfully.", ProjectID = id }));
            }
            catch (Exception e)
            {
                _logger.Log("Project creation failed. \n{ExceptionMessage}\n{ExceptionStackTrace}",
                            LogLevel.Error, e.Message, e.StackTrace);
                return(new JsonResult(new { status = "Error occured." }));
            }
        }
 public IEnumerable <Activity> GetByWeek(int year, int weekID)
 {
     try
     {
         DateTime dt            = DateTime.Parse($"{year}-01-01");
         var      timespanStart = dt + TimeSpan.FromDays(7 * (weekID - 1));
         var      timespanEnd   = dt + TimeSpan.FromDays((7 * weekID) - 1);
         _logger.Log("GetByWeek executed successfully.",
                     LogLevel.Debug);
         return(_dataProvider.GetAllActivities().Where(x => x.ActivityDate >= timespanStart && x.ActivityDate <= timespanEnd));
     }
     catch (Exception e)
     {
         _logger.Log("GetAllProjects failed. \n{ExceptionMessage}\n{ExceptionStackTrace}",
                     LogLevel.Error, e.Message, e.StackTrace);
         return(null);
     }
 }
Ejemplo n.º 26
0
 private void HiEveryFiveSeconds()
 {
     for (int i = 0; i < 10; i++)
     {
         Thread.Sleep(5000);
         Action action = () => logger.Log("Hi Avi {0}", i);
         action.BeginInvoke(null, null);
     }
 }
Ejemplo n.º 27
0
        /// <summary>
        /// Creates a CS file that inherits from BaseMigration that will execute the SQL schema changes.
        /// </summary>
        /// <param name="criteria">description of what to do and where to put the file</param>
        public void CreateScript(CreationCriteria criteria)
        {
            var configurationStatus = GetMigrationConfigurationStatus(criteria.ProjectFileLocation, criteria.RepoName);

            if (!configurationStatus.Enabled)
            {
                LoggerBase.Log("Migrations are not enabled, can not create any migrations.");
                return;
            }

            if (configurationStatus.MigrationType != MigrationToUse.Manual)
            {
                LoggerBase.Log("Manual Migrations are not enabled, can not create manual migrations.");
                return;
            }

            var repoInfo = TypeHandler.FindSingleRepo(criteria.ProjectFileLocation, criteria.RepoName);

            //if null we need to drop out.
            if (repoInfo == null)
            {
                LoggerBase.Log("Unable to find repo");
                return;
            }

            AssertRepoHasEmptyConstructor(repoInfo.RepoType);
            EnsureDbAndMigrationTableExists(criteria.ProjectFileLocation, repoInfo.RepoType, criteria.ConfigFilePath);

            //ensure that we have the case correct.
            criteria.RepoName = repoInfo.RepoType.Name;

            var configuration = TypeHandler.FindConfiguration(criteria.ProjectFileLocation, repoInfo.RepoType);

            //if null something bad happend, drop out
            if (configuration == null)
            {
                LoggerBase.Log("unable to find configuration file");
                return;
            }

            var updater = CreateSchemaUpdater(repoInfo.Assembly.Location, repoInfo.RepoType, criteria.ConfigFilePath);

            var fileMigrationHandler = new MigrationFileHandler(updater);
            var projectFileHandler   = new ProjectDteHelper();

            //set the mgiration folder form config:
            criteria.MigrationPath = configuration.RootMigrationFolder;

            var filePath = fileMigrationHandler.CreateFile(criteria);

            projectFileHandler.AddFile(criteria.ProjectFileLocation, configuration.RootMigrationFolder, filePath, showFile: true);
            LoggerBase.Log("Created migration file.");

            //clean up
            ProjectEvalutionHelper.FinishedWithProject(criteria.ProjectFileLocation);
        }
Ejemplo n.º 28
0
    /// <summary>
    /// Creates the logger for the application.
    /// </summary>
    private void InitializeLogger()
    {
        var loggers = new List <LoggerBase>();
        // we want to show logger exception after all loggers have been initialized, so "remember" these
        var loggersFailed = new Dictionary <string, Exception>();

        // create loggers based on configuration
        foreach (Configurations.Logger configLogger in Configurations.LoggerSection.GetLoggers())
        {
            if (string.IsNullOrEmpty(configLogger.Provider))
            {
                _logger.Log(_loggerTag, LoggerPriorities.Error, "Ignoring Logger without provider.");
                continue;
            }

            LoggerBase logger = null;

            // try to greate loggers based on provider name
            try
            {
                switch (configLogger.Provider.ToLower())
                {
                case "console":
                    logger = new LoggerConsole(configLogger);
                    break;

                case "file":
                    logger = new LoggerFile(configLogger);
                    break;

                case "eventlog":
                    logger = new LoggerEventLog(configLogger);
                    break;
                }
            }
            catch (Exception ex)
            {
                loggersFailed.Add(configLogger.Provider, ex);
            }

            if (logger == null)
            {
                _logger.Log(_loggerTag, LoggerPriorities.Error, "Unknown logger {0}", configLogger.Provider);
                continue;
            }

            loggers.Add(logger);
        }

        _logger = new LoggerMultiple(loggers);

        foreach (var logger in loggersFailed)
        {
            _logger.Log(_loggerTag, LoggerPriorities.Error, "Could not create logger {0}. Error: {1}", logger.Key, logger.Value);
        }
    }
Ejemplo n.º 29
0
        public override void OnActionExecuted(HttpActionExecutedContext actionExecutedContext)
        {
            currentStopwatch.Stop();
            var url = actionExecutedContext.Request.RequestUri.PathAndQuery;
            var log = string.Format("apiController:{0},action:{1},execution time:{2}ms{3}Url:{4}",
                                    actionExecutedContext.ActionContext.ActionDescriptor.ControllerDescriptor.ControllerName,
                                    actionExecutedContext.ActionContext.ActionDescriptor.ActionName,
                                    currentStopwatch.ElapsedMilliseconds,
                                    Environment.NewLine,
                                    url
                                    );

            _logger.Log(LoggerLevels.Info, log);
            if (currentStopwatch.ElapsedMilliseconds > WarnThreshold)
            {
                _logger.Log(LoggerLevels.Warn, log);
            }
            base.OnActionExecuted(actionExecutedContext);
        }
Ejemplo n.º 30
0
        protected void Application_Error(object sender, EventArgs e)
        {
            //获取异常
            var    lastError  = Server.GetLastError().GetBaseException();
            string requestStr = null;

            if (HttpContext.Current != null)
            {
                var context = HttpContext.Current;
                requestStr = string.Format("URL:{1}{0}", Environment.NewLine, context.Request.Url);
            }
            if (string.IsNullOrEmpty(requestStr))
            {
                log.Log(LoggerLevels.Error, lastError);
            }
            else
            {
                log.Log(LoggerLevels.Error, requestStr); //, lastError, requestStr);
            }
        }