コード例 #1
0
        public void Log <TState>(ML.LogLevel logLevel, ML.EventId eventId, TState state, Exception exception, Func <TState, Exception, string> formatter)
        {
            var msg = formatter(state, exception);

            switch (logLevel)
            {
            case ML.LogLevel.Critical:
                logger.Fatal(msg);
                return;

            case ML.LogLevel.Debug:
                logger.Debug(msg);
                return;

            case ML.LogLevel.Error:
                logger.Error(msg);
                return;

            case ML.LogLevel.Information:
                logger.Info(msg);
                return;

            case ML.LogLevel.Trace:
                logger.Trace(msg);
                return;

            case ML.LogLevel.Warning:
                logger.Warn(msg);
                return;
            }
        }
コード例 #2
0
        private bool Create2BOrder(decimal price, string pid, string name, Guid vipUserId,
                                   int count, string batchCode)
        {
            var success = false;

            try
            {
                var result = VipBaoYangPackageService.CreateOrder(price, pid, name, vipUserId, count, batchCode);
                if (result != null && result.OrderId > 0)
                {
                    VipBaoYangPackageService.ExecuteOrderProcess(new ExecuteOrderProcessRequest()
                    {
                        OrderId          = result.OrderId,
                        OrderProcessEnum = OrderProcessEnum.GeneralCompleteToHome,
                        CreateBy         = vipUserId.ToString()
                    });
                    logger.Info($"创建买断制2B订单{result.OrderId}成功, 一共{count}个产品数量, 关联批次号:{batchCode}");
                    success = dbScopeManager.Execute(conn => DALVipBaoYangPackage.UpdateRedemptionCode(conn, batchCode, result.OrderId));
                }
                else
                {
                    logger.Error($"创建买断制2B订单失败, 一共{count}个产品数量, 批次号:{batchCode}");
                }
            }
            catch (Exception ex)
            {
                logger.Error(ex.Message, ex);
            }
            return(success);
        }
コード例 #3
0
        public bool SaveProductInfoByPid(string pid, string cpremark, bool isAuto, string vehicleLevel)
        {
            bool result = false;

            try
            {
                int isAutometic = isAuto ? 1 : 0;
                #region 车型信息变更 则删除原有车型信息配置
                bool configNotChange = DalProductVehicleInfo.IsExistProductVehicleTypeConfig(pid, vehicleLevel);
                bool?deleteResult    = null;
                if (!configNotChange)
                {
                    Func <SqlConnection, bool> deleteAction = (connection) => DalProductVehicleInfo.DeleteOldProductVehicleTypeConfig(connection, pid);
                    deleteResult = dbManager.Execute(deleteAction);
                    if (deleteResult != true)
                    {
                        throw new Exception("删除旧车型配置失败");
                    }
                }
                #endregion
                Func <SqlConnection, bool> action = (connection) => DalProductVehicleInfo.SaveProductInfoByPid(connection, pid, cpremark, isAutometic, vehicleLevel);
                result = dbManager.Execute(action);
            }
            catch (Exception e)
            {
                logger.Info($"SaveProductInfoByPid;ErrorMessage:{e.Message};ErrorStackTrace:{e.StackTrace}");
                Monitor.ExceptionMonitor.AddNewMonitor("编辑页保存车型级别异常", e, "保存数据异常", MonitorLevel.Critial, MonitorModule.Other);
                throw e;
            }

            return(result);
        }
コード例 #4
0
        /// <summary>
        /// 上传喷漆打折配置
        /// 存在则更新,不存在则添加
        /// </summary>
        /// <param name="models"></param>
        /// <param name="user"></param>
        /// <returns></returns>
        public bool UploadPaintDiscountConfig
            (List <PaintDiscountConfigModel> models, string user)
        {
            var result = false;

            if (models != null && models.Any())
            {
                Logger.Info($"导入喷漆打折配置 开始,导入人{user}");
                foreach (var model in models)
                {
                    var isExist = IsExistPaintDiscountConfig(model);
                    result = isExist ? UpdatePaintDiscountConfig(model, user) : AddPaintDiscountConfig(model, user);
                }
                Logger.Info($"导入喷漆打折配置 结束,导入人{user}");
            }
            return(result);
        }
コード例 #5
0
 private static void LogPrint(LoggingCommon.ILog log)
 {
     log.Info("info message");
     log.Error(new InvalidDataException("just testing"));
     log.Debug("debug message");
     log.Warn("warn message");
     log.Error("error message");
     log.Fatal("fatal message");
 }
コード例 #6
0
        /// <summary>
        /// 消息輸出
        /// </summary>
        /// <param name="message">消息</param>
        /// <param name="level">級別</param>
        /// <param name="exception">異常對象</param>
        public void Output(string message, MessageLevel level, Exception exception)
        {
            Common.Logging.ILog logger = LogManager.GetLogger(GetType());
            switch (level)
            {
            case MessageLevel.Trace:
                if (logger.IsTraceEnabled)
                {
                    logger.Trace(message, exception);
                }
                break;

            case MessageLevel.Debug:
                if (logger.IsDebugEnabled)
                {
                    logger.Debug(message, exception);
                }
                break;

            case MessageLevel.Info:
                if (logger.IsInfoEnabled)
                {
                    logger.Info(message, exception);
                }
                break;

            case MessageLevel.Warn:
                if (logger.IsWarnEnabled)
                {
                    logger.Warn(message, exception);
                }
                break;

            case MessageLevel.Error:
                if (logger.IsErrorEnabled)
                {
                    logger.Error(message, exception);
                }
                break;

            case MessageLevel.Fatal:
                if (logger.IsFatalEnabled)
                {
                    logger.Fatal(message, exception);
                }
                break;
            }
        }
コード例 #7
0
        public static void LogEx(this Common.Logging.ILog log, Common.Logging.LogLevel level, Action <TraceRecord> traceAction, [CallerMemberName] string member = "", [CallerLineNumber] int line = 0)
        {
            // Check if this log level is enabled
            if (level == LogLevel.Trace && log.IsTraceEnabled == false ||
                level == LogLevel.Debug && log.IsDebugEnabled == false ||
                level == LogLevel.Info && (log.IsInfoEnabled == false) ||
                level == LogLevel.Warn && (log.IsWarnEnabled == false) ||
                level == LogLevel.Error && (log.IsErrorEnabled == false) ||
                level == LogLevel.Fatal && (log.IsFatalEnabled == false))
            {
                return;
            }

            TraceRecord tr = new TraceRecord()
            {
                Level = level
            };

            traceAction(tr);
            string message = String.Format("{0}() line {1}: {2}.{3}", member, line, tr.Message, (tr.Data != null) ? Newtonsoft.Json.JsonConvert.SerializeObject(tr.Data) : "");

            switch (level)
            {
            case LogLevel.Trace: log.Trace(message, tr.Exception); break;

            case LogLevel.Debug: log.Debug(message, tr.Exception); break;

            case LogLevel.Error: log.Error(message, tr.Exception); break;

            case LogLevel.Fatal: log.Fatal(message, tr.Exception); break;

            case LogLevel.Info: log.Info(message, tr.Exception); break;

            case LogLevel.Warn: log.Warn(message, tr.Exception); break;
            }
        }
コード例 #8
0
 public void Info(object obj)
 {
     _log.Info(obj);
 }
コード例 #9
0
        /// <summary>
        /// 调用接口筛选pid
        /// </summary>
        /// <param name="catalogId"></param>
        /// <param name="onSale"></param>
        /// <param name="isDaifa"></param>
        /// <param name="stockOut"></param>
        /// <param name="hasPintuanPrice"></param>
        /// <param name="keyWord"></param>
        /// <param name="keyWordSearchType"></param>
        /// <param name="page"></param>
        /// <param name="pageSize"></param>
        /// <returns></returns>
        static async Task <OperationResult <PagedModel <string> > > GetPidsByFilter(string catalogId, int onSale,
                                                                                    int isDaifa, int stockOut, int hasPintuanPrice, string keyWord, int keyWordSearchType, int page, int pageSize, string ProductName = "")
        {
            using (var client = new ShopProductClient())
            {
                var dics = new Dictionary <string, ProductCommonQuery>();

                #region 查询条件
                if (!string.IsNullOrWhiteSpace(catalogId))
                {
                    dics.Add(nameof(ProductCommonQueryModel.CategoryOid), new ProductCommonQuery
                    {
                        CompareType = CompareType.Equal,
                        Value       = catalogId
                    });
                }
                else
                {
                    dics.Add("NodeNo", new ProductCommonQuery
                    {
                        CompareType = CompareType.Equal,
                        Value       = 28349
                    });
                }

                if (!string.IsNullOrWhiteSpace(ProductName))
                {
                    dics.Add(nameof(ProductCommonQueryModel.ProductName), new ProductCommonQuery
                    {
                        CompareType = CompareType.Equal,
                        Value       = ProductName
                    });
                }

                if (onSale != -1)
                {
                    dics.Add(nameof(ProductCommonQueryModel.IsOnSale), new ProductCommonQuery
                    {
                        CompareType = CompareType.Equal,
                        Value       = (onSale == 1)
                    });
                }
                if (isDaifa != -1)
                {
                    dics.Add(nameof(ProductCommonQueryModel.IsDaiFa), new ProductCommonQuery
                    {
                        CompareType = CompareType.Equal,
                        Value       = (isDaifa == 1)
                    });
                }
                if (stockOut != -1)
                {
                    dics.Add(nameof(ProductCommonQueryModel.Stockout), new ProductCommonQuery
                    {
                        CompareType = CompareType.Equal,
                        Value       = (stockOut == 1)
                    });
                }
                if (hasPintuanPrice != -1)
                {
                    dics.Add(nameof(ProductCommonQueryModel.IsPinTuanProduct), new ProductCommonQuery
                    {
                        CompareType = CompareType.Equal,
                        Value       = (hasPintuanPrice == 1)
                    });
                }
                if (!string.IsNullOrWhiteSpace(keyWord) &&
                    keyWordSearchType >= 1)
                {
                    if (keyWordSearchType == 1)
                    {
                        dics.Add(nameof(ProductCommonQueryModel.ProductName), new ProductCommonQuery
                        {
                            CompareType = CompareType.Equal,
                            Value       = keyWord
                        });
                    }
                    else
                    {
                        dics.Add(nameof(ProductCommonQueryModel.Pid), new ProductCommonQuery
                        {
                            CompareType = CompareType.Equal,
                            Value       = keyWord
                        });
                    }
                }
                #endregion

                var inputProp = new ProductCommonQueryRequest
                {
                    AndQuerys = dics,
                    PageIndex = page,
                    PageSize  = pageSize
                };

                logger.Info($"{nameof(CarProductPriceManager)}.{nameof(GetPidsByFilter)} 调用接口ProductCommonQueryAsync 入参:{JsonHelper.Serialize(inputProp)}");
                var res = await client.ProductCommonQueryAsync(inputProp);

                logger.Info($"{nameof(CarProductPriceManager)}.{nameof(GetPidsByFilter)} 调用接口ProductCommonQueryAsync 出参:res={JsonHelper.Serialize(res)} 入参:{JsonHelper.Serialize(inputProp)} ");

                res.ThrowIfException();

                return(res);
            }
        }
コード例 #10
0
        public void Execute(IJobExecutionContext context)
        {
            try
            {
                const int pageSize  = 800;
                decimal   num       = ProductCacheDal.SelectSkuProductCount();
                var       pageNum   = Convert.ToInt32(Math.Ceiling(num / pageSize));
                bool      issuccess = true;
                string    key       = "";
                Logger.Info($"{JobBatch}=>刷新缓存服务开始.一共{num}个产品.一共{pageNum}批次.");
                Stopwatch watch = new Stopwatch();
                watch.Start();

                if (DateTime.Now.Hour >= 2 && DateTime.Now.Hour <= 4)
                {
                    using (var cacheclient = new CacheClient())
                    {
                        var keyresult = cacheclient.GenerateProdutCacheKeyPrefix();
                        keyresult.ThrowIfException(true);
                        key = keyresult.Result;
                    }
                }

                var client = new CacheClient();
                for (var i = 1; i <= pageNum + 1; i++)
                {
                    Thread.Sleep(5);
                    var result = client.RefreshProductCacheByPageNumAndKeyPrefix(i, pageSize, JobBatch, key);
                    Logger.Info($"{JobBatch}=>{i}批次刷新{(result.Result ? "成功" : "失败")}.用时{result.ElapsedMilliseconds}");

                    if (!result.Success || !result.Result) //失败重新创建client
                    {
                        Thread.Sleep(1000);
                        client = new CacheClient();
                        var result2 = client.RefreshProductCacheByPageNumAndKeyPrefix(i, pageSize, JobBatch, key);
                        Logger.Info($"{JobBatch}=>{i}批次重试刷新{(result2.Result ? "成功" : "失败")}.用时{result2.ElapsedMilliseconds}");

                        if (!result2.Success) //失败重新创建client
                        {
                            client = new CacheClient();
                        }
                    }
                    issuccess = issuccess && result.Result;
                }

                using (var cacheclient = new CacheClient())
                {
                    var setresult = cacheclient.SetProdutCacheKeyPrefix(key);
                    if (!setresult.Success && setresult.ErrorCode != "keyPrefix")
                    {
                        Logger.Warn($"刷新产品缓存,换key失败。{setresult.ErrorMessage}", setresult.Exception);
                    }
                    Logger.Info($"{JobBatch}=>刷新产品缓存.换key.{setresult.Result};key=>{key}");
                }

                watch.Stop();
                if (issuccess)
                {
                    Logger.Info($"{JobBatch}=>刷新成功用时{watch.ElapsedMilliseconds}");
                }
                else
                {
                    Logger.Error($"{JobBatch}=>刷新失败用时{watch.ElapsedMilliseconds}");
                }
            }
            catch (Exception e)
            {
                Logger.Error($"{JobBatch}=>刷新产品缓存异常", e);
            }
            JobBatch++;
        }
コード例 #11
0
        public Core.DatabaseGeneratorResult Generate(Core.Database database)
        {
            System.Text.StringBuilder finalSQL = new StringBuilder();

            database.UserName = String.IsNullOrWhiteSpace(database.UserName) ? string.Format("{0}_user", database.Name) : database.UserName;
            database.Password = String.IsNullOrWhiteSpace(database.Password) ? GeneratePassword() : database.Password;

            LOG.InfoFormat("Generating database sql creation script.");

            finalSQL.AppendFormat(@"IF EXISTS (SELECT * FROM sys.databases WHERE name = '{0}')
BEGIN
    DROP DATABASE WHERE name = '{0}'
END

CREATE DATABASE [{0}];
", database.Name);

            //log: generating database user/login and assign roles
            finalSQL.AppendFormat(@"CREATE LOGIN [{0}] WITH PASSWORD='******', 
DEFAULT_DATABASE=[{2}], CHECK_POLICY=OFF

CREATE USER [{0}] FOR LOGIN [{0}]
EXEC sp_addrolemember N'db_datareader', N'{2}'
EXEC sp_addrolemember N'db_datawriter', N'{2}'


", database.UserName, database.Password, database.Name);

            finalSQL.AppendLine(ROBOT_BLOCKS_TAG);
            LOG.Info("Generating database.");

            foreach (Core.Table t in database.Tables)
            {
                LOG.Info(m => m("Generating Table: {0}", t.Name));

                System.Text.StringBuilder columnDefinitions = new StringBuilder();
                bool first = true;
                foreach (Core.Column c in t.Columns)
                {
                    string columnSQL = GetColumnDefinition(c);
                    if (!first)
                    {
                        columnDefinitions.AppendFormat(@",
{0}", columnSQL);
                    }
                    else
                    {
                        first = false;
                        columnDefinitions.AppendFormat(@"{0}", columnSQL);
                    }
                }

                finalSQL.AppendLine();
                finalSQL.AppendFormat("-- creating table {0}", t.Name);
                finalSQL.AppendLine();
                finalSQL.AppendFormat(@"CREATE TABLE {0}
(
{1}
);
                               ", t.Name, columnDefinitions);

                //generate indices on this table
                finalSQL.AppendLine();

                if (t.Indices.Any())
                {
                    finalSQL.AppendLine(string.Format("-- indexes for {0}", t.Name));
                }
                foreach (Core.Index index in t.Indices)
                {
                    finalSQL.AppendFormat(@"CREATE {0} INDEX IX_{1}_{2}
ON {1} ({3});
",
                                          GetIndexTypeAsString(index),
                                          t.Name,
                                          String.Join("_", index.ColumnNames),
                                          String.Join(",", index.ColumnNames));
                }
            }

            //generate foreign keys
            foreach (Core.Table t in database.Tables)
            {
                //generate cascading rules on record deletion on table
                finalSQL.AppendLine();
                if (t.Relationships.Any())
                {
                    finalSQL.AppendLine(string.Format("-- fk constraints for {0}", t.Name));
                }
                foreach (Core.Relationship relationship in t.Relationships)
                {
                    string onDeleteRule = string.Empty;
                    if (relationship.IsRequired)
                    {
                        onDeleteRule = "ON DELETE CASCADE";
                    }
                    else
                    {
                        onDeleteRule = "ON DELETE SET NULL";
                    }

                    finalSQL.AppendFormat(@"ALTER TABLE {0}
ADD CONSTRAINT fk_{0}_{1}
FOREIGN KEY ({2})
REFERENCES {1}({3}) {4}
",
                                          relationship.FromTable,
                                          relationship.ToTable,
                                          relationship.FromColumnNamed,
                                          relationship.ToColumnNamed,
                                          onDeleteRule);
                }
            }

            return(new Core.DatabaseGeneratorResult()
            {
                IsSuccessful = true,
                Output = finalSQL.ToString()
            });
        }
コード例 #12
0
 /// <summary>
 /// Log a message string with the Info level.
 /// </summary>
 /// <param name="message">The message.</param>
 public void Info(string message)
 {
     _logger.Info(message);
 }
コード例 #13
0
        private void Write(LogEntity log)
        {
            var workType = LogManager.MatchLogWorkType(log.AppName, log.ModelName, log.BusinessName, log.Lable, log.ServerName);

            if (workType == LogWorkType.Local || workType == LogWorkType.LocalAndBuffer)
            {
                switch (log.Level)
                {
                case LogLevel.DEBUG:
                    if (LogManager.MatchLogLevel(log.Level, log.AppName, log.ModelName, log.BusinessName, log.Lable, log.ServerName))
                    {
                        loggerForDebug.Debug(log.ToString());
                    }
                    break;

                case LogLevel.ERROR:
                    if (LogManager.MatchLogLevel(log.Level, log.AppName, log.ModelName, log.BusinessName, log.Lable, log.ServerName))
                    {
                        loggerForError.Error(log.ToString());
                    }
                    break;

                case LogLevel.WARN:
                    if (LogManager.MatchLogLevel(log.Level, log.AppName, log.ModelName, log.BusinessName, log.Lable, log.ServerName))
                    {
                        loggerForWarn.Warn(log.ToString());
                    }
                    break;

                case LogLevel.INFO:
                    if (LogManager.MatchLogLevel(log.Level, log.AppName, log.ModelName, log.BusinessName, log.Lable, log.ServerName))
                    {
                        loggerForInfo.Info(log.ToString());
                    }
                    break;
                }
            }

            if (workType == LogWorkType.Buffer || workType == LogWorkType.LocalAndBuffer)
            {
                if (BufferServiceManager.HasInited && BufferServiceManager.DispatcherService.IsRunning)
                {
                    switch (log.Level)
                    {
                    case LogLevel.DEBUG:
                        if (LogManager.MatchLogLevel(log.Level, log.AppName, log.ModelName, log.BusinessName, log.Lable, log.ServerName))
                        {
                            BufferServiceManager.TransportService.Transport(log);
                        }
                        break;

                    case LogLevel.ERROR:
                        if (LogManager.MatchLogLevel(log.Level, log.AppName, log.ModelName, log.BusinessName, log.Lable, log.ServerName))
                        {
                            BufferServiceManager.TransportService.Transport(log);
                        }
                        break;

                    case LogLevel.WARN:
                        if (LogManager.MatchLogLevel(log.Level, log.AppName, log.ModelName, log.BusinessName, log.Lable, log.ServerName))
                        {
                            BufferServiceManager.TransportService.Transport(log);
                        }
                        break;

                    case LogLevel.INFO:
                        if (LogManager.MatchLogLevel(log.Level, log.AppName, log.ModelName, log.BusinessName, log.Lable, log.ServerName))
                        {
                            BufferServiceManager.TransportService.Transport(log);
                        }
                        break;
                    }
                }
            }
        }