public void Info() { YmatouLoggingService.InitLogService(); YmatouLoggingService.Debug("{0}", "test log4net debug"); YmatouLoggingService.Info("{0}", "test log4net debug"); YmatouLoggingService.Error("{0}", "test log4net debug"); }
public bool Execute() { bool successful = true; var tasks = container.ResolveAll <BootstrapperTask>().OrderBy(t => t.Order).ToList(); foreach (var task in tasks) { YmatouLoggingService.Debug("YmatouFramework.Bootstrapper 开始执行 '{0}' ({1})", task.GetType().FullName, task.Description); try { if (task.Execute() == TaskContinuation.Break) { YmatouLoggingService.Error("YmatouFramework.Bootstrapper 执行中断 '{0}' ({1})", task.GetType().FullName, task.Description); successful = false; break; } } catch (Exception ex) { successful = false; YmatouLoggingService.Error("YmatouFramework.Bootstrapper 执行出错 '{0}',异常信息:{1}", task.GetType().FullName, ex.ToString()); } } ; return(successful); }
public static T GetConfig <T>(string fileName, T defVal) { object instance = null; string fileFullName = GetConfigFileFullName(fileName); if (ConfigCache.TryGetValue(fileFullName, out instance)) { return((T)instance); } lock (Locker) { if (ConfigCache.TryGetValue(fileFullName, out instance)) { return((T)instance); } if (!File.Exists(fileFullName)) { TryCreateConfig(fileName, defVal); return(defVal); } XmlDocument doc = new XmlDocument(); try { doc.Load(fileFullName); } catch (Exception ex) { string errMsg = string.Format("加载配置文件 {0} 失败!使用默认配置文件!,异常信息:{1}", fileFullName, ex); YmatouLoggingService.Error(errMsg); return(defVal); } ConfigFileWatcher configFileWatcher = null; if (!ConfigFileWatcherCache.TryGetValue(fileFullName, out configFileWatcher)) { ConfigFileWatcherCache.Add(fileFullName, new ConfigFileWatcher(fileFullName, OnConfigChanged)); } XmlSerializer xmlSerializer = new XmlSerializer(typeof(T)); using (StringReader sr = new StringReader(doc.OuterXml)) { try { instance = (T)xmlSerializer.Deserialize(sr); ConfigCache.Add(fileFullName, instance); return((T)instance); } catch (Exception ex) { YmatouLoggingService.Debug("反序列化异常,类型名称:{0},异常信息:{1}", typeof(T).Name, ex.ToString()); return(defVal); } } } }
private void Log <TResult>( DbCommand command, DbCommandInterceptionContext <TResult> interceptionContext, string sqlType = null, string desc = null) { if (interceptionContext.Exception != null) { YmatouLoggingService.Error("sql {0},{1}, {2} -> failed with exception {3}", sqlType, desc, command.CommandText.Replace(Environment.NewLine, ""), interceptionContext.Exception); } else { YmatouLoggingService.Info("sql {0} ,{1},{2}", sqlType, desc, command.CommandText.Replace(Environment.NewLine, "")); } }
protected override void InternalDispose() { container.ResolveAll <BootstrapperTask>().OrderByDescending(t => t.Order).Each(task => { try { YmatouLoggingService.Debug("YmatouFramework.Bootstrapper 开始清理 '{0}' ({1})", task.GetType().FullName, task.Description); task.Dispose(); } catch (Exception ex) { YmatouLoggingService.Error("YmatouFramework.Bootstrapper 清理出错 '{0}',异常信息:{1}", task.GetType().FullName, ex.ToString()); } }); }
public void Stop() { lock (this) { try { if (!init || PQStatus == Status.NoInit) { return; } //清除队列数据 if (PQ != null) { PQ.Clear(); } //暴力终止 if (PQ.Count > 0) { foreach (var thObj in thList) { thObj.Join(10); } foreach (var thObj in thList) { try { thObj.Abort(); } catch (ThreadAbortException e) { } catch (ThreadInterruptedException ex) { } } thList.Clear(); } PQStatus = Status.Stop; init = false; } catch (QueueException e) { YmatouLoggingService.Error("终止服务错误:{0},{1},{2}", "BBQW", e.Message, e.StackTrace); } } }
public static DbConnection Builder(DbConfigure cfg) { try { YmtSystemAssert.AssertArgumentNotNull(cfg, "DbConfigure 不能为空"); var factory = DbProviderFactories.GetFactory(cfg.Provider); var connection = factory.CreateConnection(); connection.ConnectionString = cfg.Connection; //LocalFileCfg.GetLocalCfgValueByFile<string>("db.cfg", ValueFormart.CJsv, @"Data Source=YMT-LIGUO\LIGUO;Initial Catalog=Ymt_Test_7;Persist Security Info=True;User ID=sa;Password=123@#$123asd"); //TODO:这里可以设置其他链接属性 return(connection); } catch (Exception ex) { YmatouLoggingService.Error("创建链接对象异常 {0}", ex.ToString()); throw; } }
private static bool EnsureConfigDirectoryExists() { if (Directory.Exists(LocalConfigDirectory)) { return(true); } try { Directory.CreateDirectory(LocalConfigDirectory); return(true); } catch (Exception ex) { string errMsg = string.Format("创建目录 {0} 失败!异常信息:{1}", LocalConfigDirectory, ex); YmatouLoggingService.Error(errMsg); return(false); } }
private static T GetInstance <T>(string name = "") { try { if (string.IsNullOrEmpty(name)) { return(YmatouBootstrapperFramework.Container.Resolve <T>()); } else { return(YmatouBootstrapperFramework.Container.Resolve <T>(name)); } } catch (Exception ex) { YmatouLoggingService.Error("YmatouFramework.LocalServiceLocator 不能解析 '{0}',异常信息:{1}", typeof(T).FullName, ex.ToString()); throw; } }
private static void TryCreateConfig <T>(string fileName, T defVal) { if (!EnsureConfigDirectoryExists()) { return; } string fileFullName = GetConfigFileFullName(fileName); if (File.Exists(fileFullName)) { return; } if (defVal == null) { return; } XmlWriterSettings settings = new XmlWriterSettings(); settings.Encoding = Encoding.UTF8; settings.Indent = true; XmlSerializer xs = new XmlSerializer(typeof(T), (string)null); using (FileStream fs = new FileStream(fileFullName, FileMode.Create)) { using (XmlWriter xw = XmlWriter.Create(fs, settings)) { try { xs.Serialize(xw, defVal); } catch (Exception ex) { YmatouLoggingService.Error("序列化异常,类型名称:{0},异常信息:{1}", typeof(T).Name, ex.ToString()); } } } }
public static void Handler(this Exception ex) { YmatouLoggingService.Error("Handler ", ex); }
public static void Handler(this Exception ex, string formart, params object[] args) { YmatouLoggingService.Error(formart + "," + ex.ToString(), args); }
public static void Handler(this Exception ex, string message = "") { YmatouLoggingService.Error(message, ex); }
public ExecuteResult <int> Commit(int retry = 0, bool lockd = false) { var tmpRetry = retry; var fail = false; var result = 0; do { try { result = base.SaveChanges(); fail = false; YmatouLoggingService.Debug("Db Context Commit {0}", result); return(ExecuteResult <int> .CreateSuccess(result, "提交成功")); } catch (DbEntityValidationException ex) { ex.EntityValidationErrors.Each(_e => { var errs = _e.Entry.GetValidationResult().ValidationErrors.ValidationErrorAppendToString(); YmatouLoggingService.Error("entity:{0},Validation fail:{1}", _e.Entry.Entity.GetType().Name, errs); }); return(ExecuteResult <int> .CreateFaile(0, "Db Context Commit fail")); } catch (DbUpdateConcurrencyException ex) { fail = true; ex.Entries .Each(entry => { if (entry != null) { if (entry.State == EntityState.Added || entry.State == EntityState.Modified) { //Context中实体的值覆盖db中实体的值 var currentVal = entry.CurrentValues; //当前值 var dbVal = entry.GetDatabaseValues(); //获取数据库中的值 entry.OriginalValues.SetValues(dbVal); //entry.CurrentValues.SetValues(dbVal.Clone()); entry.State = EntityState.Modified; } else { //数据库中的覆盖entity中的值 entry.Reload(); } } }, errorHandler: err => { YmatouLoggingService.Error("重试异常 {0}", err.ToString()); }); var _ex = ex.GetBaseException() as SqlException; if (_ex != null && (_ex.Number == 2627 || _ex.Number == 515)) { YmatouLoggingService.Debug("EFUnitOfWork DbUpdateConcurrencyException repeat insert,{0}", _ex.Message); } else { YmatouLoggingService.Error( "EFUnitOfWork DbUpdateConcurrencyException entity : {0},err:{1},重试 {2} 次", ex.Entries.TrySerializeEntity(), ex.ToString(), tmpRetry); } } // catch (DbUpdateException ex) // { // fail = true; // result = -1; // var _ex = ex.GetBaseException() as SqlException; // if (_ex != null && (_ex.Number == 2627 || _ex.Number == 515)) // YmatouLoggingService.Debug("EFUnitOfWork DbUpdateException repeat insert,{0}", _ex.Message); // else // YmatouLoggingService.Error("EFUnitOfWork DbUpdateException entity : {0},err:{1},重试 {2} 次", // ex.Entries.TrySerializeEntity(), // ex.ToString(), tmpRetry); // throw; // } } while (fail && tmpRetry-- > 0); return(new ExecuteResult <int>(fail == false, fail == false ? "执行成功" : "更新失败", result)); }
public async Task <ExecuteResult <int> > AsyncCommit(int retry = 0) { var tmpRetry = retry; bool fail; var result = 0; do { try { result = await base.SaveChangesAsync().ConfigureAwait(false); fail = false; return(await Task.Factory.StartNew(() => ExecuteResult <int> .CreateSuccess(result, "已提交"))); } catch (DbEntityValidationException ex) { ex.EntityValidationErrors.Each(_e => { var errs = _e.Entry.GetValidationResult().ValidationErrors.ValidationErrorAppendToString(); YmatouLoggingService.Error("实体:{0},验证错误:{1}", _e.Entry.Entity.GetType().Name, errs); }); return(ExecuteResult <int> .CreateFaile(0, "提交失败")); } catch (DbUpdateConcurrencyException ex) { fail = true; ex.Entries.Each(entry => { if (entry != null) { if (entry.State == EntityState.Added || entry.State == EntityState.Modified) { //Context中实体的值覆盖db中实体的值 var currentVal = entry.CurrentValues; //当前值 var dbVal = entry.GetDatabaseValues(); //获取数据库中的值 entry.OriginalValues.SetValues(dbVal); entry.CurrentValues.SetValues(dbVal.Clone()); entry.State = EntityState.Modified; } else { //数据库中的覆盖entity中的值 entry.Reload(); } } }); var _ex = ex.GetBaseException() as SqlException; if (_ex != null && (_ex.Number == 2627 || _ex.Number == 515)) { YmatouLoggingService.Debug("EFUnitOfWork DbUpdateConcurrencyException repeat insert,{0}", _ex.Message); } else { YmatouLoggingService.Error("EFUnitOfWork DbUpdateConcurrencyException entity : {0},err:{1},重试 {2} 次", ex.Entries.TrySerializeEntity(), ex.ToString(), tmpRetry); } } // catch (DbUpdateException ex) // { // fail = true; // var _ex = ex.GetBaseException() as SqlException; // if (_ex != null && (_ex.Number == 2627 || _ex.Number == 515)) // YmatouLoggingService.Debug("EFUnitOfWork DbUpdateException repeat insert,{0}", _ex.Message); // else // YmatouLoggingService.Error("EFUnitOfWork DbUpdateException entity : {0},err:{1},重试 {2} 次", // ex.Entries.TrySerializeEntity(), // ex.ToString(), tmpRetry); // } } while (fail && tmpRetry-- > 0); return(await Task.Factory.StartNew(() => new ExecuteResult <int>(fail == false, fail == false ? "执行成功" : "提交失败", result))); }
private void Consumer() { while (PQStatus == Status.RunIng) { try { var itemCount = PQ.Count; if (itemCount > 0) { var list = new List <Object>(); lock (PQ) { //启用了消费阀值 && 当前队列项数大于等于消费阀值 if (pqSetting.ConsumerItemCount > 0 && itemCount >= pqSetting.ConsumerItemCount) { for (var i = 0; i < pqSetting.ConsumerItemCount; i++) { var v = PQ.Dequeue().Value; if (v != null) { list.Add(v); } } } else if (itemCount < pqSetting.ConsumerItemCount) { for (var i = 0; i < itemCount; i++) { var v = PQ.Dequeue().Value; if (v != null) { list.Add(v); } } } } if (list.Count > 0) { var _watch = Stopwatch.StartNew(); YmatouLoggingService.Debug("开始消费,qNmame->{0},itemCount->{1}", pqSetting.QName, list.Count); try { //lock(list) pqSetting.ConsumeAction(list); } catch (QueueException e) { YmatouLoggingService.Debug(string.Format("PQService客户端消费错误,pqName->{0},msg->{1},stack->{2}", pqSetting.QName, e.Message, e.StackTrace)); } YmatouLoggingService.Debug("结束消费,qNmame->{0},itemCount->{1},runTime->{2} ms", pqSetting.QName, list.Count, _watch.ElapsedMilliseconds); _watch.Reset(); var _listQv = list.ConvertAll <PQValue <K, V> >(e => { return(e as PQValue <K, V>); }); if (_listQv != null && _listQv.Count > 0) { var consumerNotCount = _listQv.Where(e => e != null && e.ConsumerResult == QueueItemConsumerStats.NoConsumer); var consumerFailCount = _listQv.Where(e => e != null && e.ConsumerResult == QueueItemConsumerStats.Fail); var tmpConsumerNotCount = consumerNotCount.Count(); var tmpconsumerFailCount = consumerFailCount.Count(); var consumerOkCount = _listQv.Count - tmpConsumerNotCount - tmpconsumerFailCount; #if DEBUG YmatouLoggingService.Debug("消费结果:总共->{0},未消费->{1},成功->{2},失败->{3}", list.Count, tmpConsumerNotCount, consumerOkCount, tmpconsumerFailCount); #else QueueLogs.DebugFormat("消费结果:总共->{0},未消费->{1},成功->{2},失败->{3}", list.Count, tmpConsumerNotCount, consumerOkCount, tmpconsumerFailCount); #endif if (tmpConsumerNotCount > 0) { foreach (var o in consumerNotCount) { PQ.Enqueue(o.Key, o); } } if (tmpconsumerFailCount > 0) { if (pqSetting.CFS == ConsumerFailStrategy.Delet) { } else if (pqSetting.CFS == ConsumerFailStrategy.PersistenceEnqueue) { } else if (pqSetting.CFS == ConsumerFailStrategy.ClientHandleFail) { } else if (pqSetting.CFS == ConsumerFailStrategy.AgainEnqueue) { foreach (var o in consumerFailCount) { //消费失败次数累计 var tmpCount = o.ConsumerCount; Interlocked.Add(ref tmpCount, 1); o.ConsumerCount = tmpCount; if (o.ConsumerCount <= 3) { PQ.Enqueue(o.Key, o); } } } } } } } } catch (QueueException ex) { YmatouLoggingService.Error(string.Format("PQService 服务端错误,pqName->{0},msg->{1},stack->{2}", pqSetting.QName, ex.Message, ex.StackTrace)); } finally { Thread.Sleep(pqSetting.ScanningTime); } } }