public void Log <TState>(Microsoft.Extensions.Logging.LogLevel logLevel, EventId eventId, TState state, Exception exception, Func <TState, Exception, string> formatter) { var msg = formatter?.Invoke(state, exception) ?? exception?.Message; if (!string.IsNullOrEmpty(msg)) { msg = $"{eventId.Name} {msg}"; switch (logLevel) { case Microsoft.Extensions.Logging.LogLevel.Trace: if (_logger.IsTraceEnable) { _logger.Trace(msg); } break; case Microsoft.Extensions.Logging.LogLevel.Debug: if (_logger.IsDebugEnable) { _logger.Debug(msg); } break; case Microsoft.Extensions.Logging.LogLevel.Information: if (_logger.IsDebugEnable) { _logger.Debug(msg); } break; case Microsoft.Extensions.Logging.LogLevel.Warning: if (_logger.IsWarnEnable) { _logger.Warn(msg, exception); } break; case Microsoft.Extensions.Logging.LogLevel.Error: if (_logger.IsErrorEnable) { _logger.Error(msg, error: exception); } break; case Microsoft.Extensions.Logging.LogLevel.Critical: if (_logger.IsErrorEnable) { _logger.Error(msg, error: exception); } break; case Microsoft.Extensions.Logging.LogLevel.None: break; default: throw new ArgumentOutOfRangeException(nameof(logLevel), logLevel, null); } } }
private async Task <string> request() { HttpClient client = new HttpClient(); string res = string.Empty; try { res = await client.GetStringAsync(Request_Query); } catch (ArgumentNullException) { log.Error("Request Query is Empty"); } catch (Exception e) { log.Error(e.Message + " Link: " + Request_Query); } if (res.Equals("{\"error\":{\"type\":\"Exception\",\"message\":\"Quota limit exceeded\",\"code\":4}}")) { log.Info("API Rate Limit waiting 2 sec."); Thread.Sleep(2000); res = await request(); } if (string.IsNullOrWhiteSpace(res)) { log.Info("Response is Empty"); } return(res); }
public void WidgetPropertyChangeHandler(string EventArgs) { try { if (EventArgs.CompareTo("DisplayName") == 0) { OnWidgetDisplayNameChanged(); } else if (EventArgs.CompareTo("IsHidden") == 0) { OnWidgetHidepropertyChanged(); } else if (EventArgs.CompareTo("IsShowInPageView2Adaptive") == 0) { OnWidgetPlacePropertyChanged(); } else if (EventArgs.CompareTo("IsGroupShowInView2Adaptive") == 0) { OnWidgetPlacePropertyChanged(); } } catch (System.Exception ex) { NLogger.Error("WidgetPropertyChangeHandler" + ex.Message); } }
public void TestErrorPass() { var message = TestContext.TestName; logger.Error(new Exception(), $"{message}", null); Assert.AreEqual($"Error|{message}", target.LastMessage); }
private void SaveAttributes(SqlConnection conn, SqlTransaction tran) { try { foreach (ZillowAttribute attribute in ZillowAttributes) { SqlCommand cmd = new SqlCommand(@"insert into ZillowAttributes (ImportTransId, Version, GroupName, AttributeName, AttributeValue, ImportedFlag, BorrowerId, CoborrowerId, LoanId) values (@a, @b, @c, @d, @e, @f, @g, @h, @i)", conn); DbHelperSQL.AddSqlParameter(cmd, "@a", SqlDbType.UniqueIdentifier, ImportTransId); DbHelperSQL.AddSqlParameter(cmd, "@b", SqlDbType.NVarChar, Helpers.FormatSqlStringValue(XmlVersion, 10)); DbHelperSQL.AddSqlParameter(cmd, "@c", SqlDbType.NVarChar, Helpers.FormatSqlStringValue(attribute.GroupName, 255)); DbHelperSQL.AddSqlParameter(cmd, "@d", SqlDbType.NVarChar, Helpers.FormatSqlStringValue(attribute.AttributeName, 255)); DbHelperSQL.AddSqlParameter(cmd, "@e", SqlDbType.NVarChar, Helpers.FormatSqlStringValue(attribute.AttributeValue, 2000)); DbHelperSQL.AddSqlParameter(cmd, "@f", SqlDbType.Bit, attribute.ImportedFlag); DbHelperSQL.AddSqlParameter(cmd, "@g", SqlDbType.Int, BorrowerId); DbHelperSQL.AddSqlParameter(cmd, "@h", SqlDbType.Int, CoborrowerId); DbHelperSQL.AddSqlParameter(cmd, "@i", SqlDbType.Int, LoanId); DbHelperSQL.ExecuteNonQuery(cmd, tran); } } catch (Exception ex) { NLogger.Error(MethodBase.GetCurrentMethod().DeclaringType.FullName, MethodBase.GetCurrentMethod().Name, ex.Message, ex); throw; } }
public void Save() { try { using (SqlConnection conn = DbHelperSQL.GetOpenConnection()) { using (SqlTransaction tran = conn.BeginTransaction(ImportTransId.ToString().Substring(0, 8))) { try { SaveImport(conn, tran); SaveAttributes(conn, tran); tran.Commit(); NLogger.Info(MethodBase.GetCurrentMethod().DeclaringType.FullName, MethodBase.GetCurrentMethod().Name, "ZillowImport (" + ImportTransId.ToString() + ") completed."); } catch (Exception ex) { tran.Rollback(ImportTransId.ToString()); NLogger.Error(MethodBase.GetCurrentMethod().DeclaringType.FullName, MethodBase.GetCurrentMethod().Name, ex.Message, ex); throw; } } } } catch (Exception ex) { NLogger.Error(MethodBase.GetCurrentMethod().DeclaringType.FullName, MethodBase.GetCurrentMethod().Name, ex.Message, ex); throw; } }
/// <summary> /// 获取hashkey所有的值 /// </summary> /// <typeparam name="T"></typeparam> /// <param name="key"></param> /// <returns></returns> public static List <T> HashGetAll <T>(string key) { try { using (ConnectionMultiplexer redis = ConnectionMultiplexer.Connect(GetConn.GetInstance().Conn())) { IDatabase db = redis.GetDatabase(); List <T> result = new List <T>(); HashEntry[] arr = db.HashGetAll(key); foreach (var item in arr) { if (!item.Value.IsNullOrEmpty) { result.Add(JsonConvert.DeserializeObject <T>(item.Value)); } } return(result); } } catch (Exception ex) { NLogger.Error(ex.ToString(), "Cache"); return(null); } }
/// <summary> /// 获取hash中的多个key的值 /// </summary> /// <typeparam name="T"></typeparam> /// <param name="key">Redis Key</param> /// <param name="listhashFields">RedisValue value</param> /// <returns></returns> public static List <T> GetHashKey <T>(string key, List <RedisValue> listhashFields) { try { using (ConnectionMultiplexer redis = ConnectionMultiplexer.Connect(GetConn.GetInstance().Conn())) { IDatabase db = redis.GetDatabase(); List <T> result = new List <T>(); if (!string.IsNullOrWhiteSpace(key) && listhashFields.Count > 0) { RedisValue[] value = db.HashGet(key, listhashFields.ToArray()); foreach (var item in value) { if (!item.IsNullOrEmpty) { result.Add(JsonConvert.DeserializeObject <T>(item)); } } } return(result); } } catch (Exception ex) { NLogger.Error(ex.ToString(), "Cache"); return(null); } }
/// <summary> /// 获取Hash中的单个key的值 /// </summary> /// <typeparam name="T"></typeparam> /// <param name="key">Redis Key</param> /// <param name="hasFildValue">RedisValue</param> /// <returns></returns> public static T GetHashKey <T>(string key, string hasFildValue) { try { using (ConnectionMultiplexer redis = ConnectionMultiplexer.Connect(GetConn.GetInstance().Conn())) { IDatabase db = redis.GetDatabase(); if (!string.IsNullOrWhiteSpace(key) && !string.IsNullOrWhiteSpace(hasFildValue)) { RedisValue value = db.HashGet(key, hasFildValue); if (!value.IsNullOrEmpty) { return(JsonConvert.DeserializeObject <T>(value)); } } return(default(T)); } } catch (Exception ex) { NLogger.Error(ex.ToString(), "Cache"); return(default(T)); } }
public void WidgetSelectionChangeHandler(string EventArg) { try { List <Guid> SelectList = _selectionService.GetSelectedWidgetGUIDs(); foreach (Guid id in SelectList) { _oldSelectedList.Remove(id); WidgetListItem Item = FindUIItemByGUID(id); if (Item != null) { Item.UpdateItemSelectInfo(true); } } if (_oldSelectedList != null) { foreach (Guid id in _oldSelectedList) { WidgetListItem Item = FindUIItemByGUID(id); if (Item != null && !Item.PlaceFlag) { Item.UpdateItemSelectInfo(false); } } } _oldSelectedList.Clear(); //_oldSelectedList = SelectList; foreach (WidgetListItem item in _control.ObjectList.Items) { if (item.IsSelected) { _oldSelectedList.Add(item.WidgetID); } } if (SelectList.Count > 0) { WidgetListItem Item22 = FindUIItemByGUID(SelectList.First()); if (Item22 != null) { // ScrollToCenterOfView(_control.Tree, Item22); _control.ObjectList.ScrollIntoView(Item22); } } RefreshToolbarCommands(); } catch (System.Exception ex) { NLogger.Error("WidgetSelectionChange" + ex.Message); } }
protected void Page_Load(object sender, EventArgs e) { try { // Read XML posted via HTTP Page.Response.ContentType = "text/xml"; StreamReader reader = new StreamReader(Page.Request.InputStream); String xml_data = reader.ReadToEnd(); // Post string response_text = string.Empty; Page.Response.StatusCode = PostLead(xml_data, out response_text) ? 200 : 500; Page.Response.Write(response_text); Page.Response.Flush(); } catch (Exception ex) { Page.Response.StatusCode = 500; Page.Response.Write(ex.Message); Page.Response.Flush(); NLogger.Error(MethodBase.GetCurrentMethod().DeclaringType.FullName, MethodBase.GetCurrentMethod().Name, ex.Message, ex); } }
public void PageChangeEventHandler(Guid EventArg) { try { if (EventArg.CompareTo(Guid.Empty) == 0) { ClearData("None page selected"); return; } if ((_Page != null) && _Page.Guid.CompareTo(EventArg) == 0) { return; } IPagePropertyData pageVM = _selectionService.GetCurrentPage(); if (pageVM != null && pageVM.EditorCanvas != null) { _expandStatusList.Clear();//Clear expand info when Change page. FlashPageData(pageVM); } } catch (System.Exception ex) { NLogger.Error("PageChangeEventHandler" + ex.Message); } }
/// <summary> /// SortedSet 排序 获取 /// </summary> /// <typeparam name="T">实体对象</typeparam> /// <param name="key">主键</param> /// <param name="start">开始 默认 0</param> /// <param name="end">结束 默认-1 </param> /// <param name="order">排序 默认降序</param> /// <returns></returns> public static List <T> SortedSetRangeByRank <T>(string key, int start = 0, int end = -1, Order order = Order.Descending) { try { using (ConnectionMultiplexer redis = ConnectionMultiplexer.Connect(GetConn.GetInstance().Conn())) { IDatabase db = redis.GetDatabase(); var list = db.SortedSetRangeByRank(key, start, end, order); if (list != null && list.Length > 0) { List <T> result = new List <T>(); foreach (var item in list) { var data = JsonHelper.DeserializeObject <T>(item.ToString()); result.Add(data); } return(result); } return(null); } } catch (Exception ex) { NLogger.Error(ex.ToString(), "Cache"); return(null); } }
private void SetfontDecoration(TextDecorationLocation type, bool setvalue) { if (Selection != null && Selection.Text.Length > 0) { TextRange rang = new TextRange(Selection.Start, Selection.End); SetfontDecoration(rang, type, setvalue); Selection.Select(rang.Start, rang.End); } else { try { foreach (Block block in Document.Blocks)//vivid { if (block is Paragraph) { Paragraph para = block as Paragraph; foreach (Run run in para.Inlines) { ChangeElementDecoration(run, type, setvalue); } } else { NLogger.Error("SetfontDecoration->Invalid Block in Document.Blocks!"); } } } catch (System.Exception ex) { System.Diagnostics.Debug.WriteLine(ex.Message); } } }
/// <summary> /// 添加缓存 /// </summary> /// <param name="key">缓存Key</param> /// <param name="value">缓存Value</param> /// <param name="expiresSliding">滑动过期时长(如果在过期时间内有操作,则以当前时间点延长过期时间)</param> /// <param name="expiressAbsoulte">绝对过期时长</param> /// <returns></returns> public bool Add(string key, object value, TimeSpan expiresSliding, TimeSpan expiressAbsoulte) { try { if (key == null) { throw new ArgumentNullException(nameof(key)); } if (value == null) { throw new ArgumentNullException(nameof(value)); } _cache.Set(key, value, new MemoryCacheEntryOptions() .SetSlidingExpiration(expiresSliding) .SetAbsoluteExpiration(expiressAbsoulte) ); return(Exists(key)); } catch (Exception ex) { NLogger.Error("添加缓存:" + ex.ToString()); return(false); } }
private bool CovertPageData(IPage page, Guid curViewID, WidgetListItem ParentItem) { try { WidgetListItem.CurViewID = curViewID; List <Guid> ALLGroupWidgetList = new List <Guid>(); CovertGroup(page, ParentItem, page.Groups, ALLGroupWidgetList); foreach (IRegion region in page.WidgetsAndMasters) { if (ALLGroupWidgetList.Contains(region.Guid)) { continue; } CovertWidget(region, page, ParentItem); } ParentItem.OrderedChildren.Sort(CompareByZorder); } catch (System.Exception ex) { NLogger.Error("CovertPageData" + ex.Message.ToString()); } return(true); }
public void Commit() { try { _dbContext.SaveChanges(); } catch (DbEntityValidationException dbEx) { var msg = string.Empty; foreach (var validationErrors in dbEx.EntityValidationErrors) { foreach (var validationError in validationErrors.ValidationErrors) { msg += string.Format("Property: {0} Error: {1}", validationError.PropertyName, validationError.ErrorMessage) + Environment.NewLine; } } var fail = new Exception(msg, dbEx); NLogger.Error(fail, fail.Message); throw fail; } finally { Dispose(); } }
/// <summary> /// Handle and process the current Tcp Client connected to the client. /// Creates a proxy request and response for the client. /// </summary> /// <param name="obj">The TcpClient connecting to the proxy server.</param> private void ProcessClient(object obj) { var client = (TcpClient)obj; try { //read the first line HTTP command using (var proxyService = new ProxyService(client, _issuerKey)) using (this.HttpTracerService) { // generate a proxy request var request = proxyService.ProcessRequest(); if (!request.SuccessfulInitializaiton) { return; } // handle response proxyService.ProcessResponse(request); // trace this proxy request this.HttpTracerService.TraceProxyRequest(request); } } catch (Exception ex) { //handle exception NLogger.Error(ex); } finally { client.Close(); } }
/// <summary> /// 修改缓存 /// </summary> /// <param name="key">缓存Key</param> /// <param name="value">新的缓存Value</param> /// <param name="expiressAbsoulte">绝对过期时长</param> /// <returns></returns> public async Task <bool> ReplaceAsync(string key, object value, TimeSpan expiressAbsoulte, string prefix = "") { try { if (key == null) { throw new ArgumentNullException(nameof(key)); } if (await ExistsAsync(key, prefix)) { if (!await RemoveAsync(key, prefix)) { return(false); } } return(await AddAsync(key, value, expiressAbsoulte, prefix)); } catch (Exception ex) { NLogger.Error("修改缓存:" + ex.ToString()); return(false); } }
public void DatabaseLogger_LogsError_DatabaseLogs() { var message = "Some entry"; var config = new DatabaseLoggingConfiguration(); config.Host = "sql.emitknowledge.com"; config.Database = "app.db"; config.Username = "******"; config.Password = "******"; config.DataProvider = DataProvider.SqlClient; config.TableName = "Log2"; Aspects.Logging.ILogger logger = new NLogger(config); logger.Error(new Exception(message)); string connectionString = $"Data Source={config.Host};Initial Catalog={config.Database}; User Id={config.Username}; Password={config.Password}"; using (SqlConnection connection = new SqlConnection(connectionString)) { connection.Open(); SqlDataReader reader = new SqlCommand(@"SELECT * FROM LogEntry;", connection).ExecuteReader(); while (reader.Read()) { Assert.Contains(message, reader["Payload"].ToString()); } reader.Close(); var command = new SqlCommand("DELETE FROM LogEntry", connection); command.ExecuteNonQuery(); } }
/// <summary> /// 带事务处理的执行数据库操作 /// </summary> /// <typeparam name="Result">返回值类型 泛型</typeparam> /// <param name="func">方法委托</param> /// <param name="commandTimeOut">超时时间, 单位为秒, 默认为30秒</param> /// <param name="dbType">数据库类型</param> /// <returns>泛型返回值</returns> public static Result ExecTran <Result>(Func <SqlSugarClient, Result> func, int commandTimeOut = 30, SqlSugarDbType dbType = SqlSugarDbType.MySql) { if (func == null) { throw new Exception("委托为null, 事务处理无意义"); } using (var db = InitDB(commandTimeOut, dbType)) { try { db.Ado.BeginTran(IsolationLevel.Unspecified); var result = func(db); db.Ado.CommitTran(); return(result); } catch (Exception ex) { db.Ado.RollbackTran(); NLogger.Error(ex); throw ex; } finally { db.Dispose(); } } }
/// <summary> /// 修改缓存 /// </summary> /// <param name="key">缓存Key</param> /// <param name="value">新的缓存Value</param> /// <param name="expiressAbsoulte">绝对过期时长</param> /// <returns></returns> public bool Replace(string key, object value, TimeSpan expiressAbsoulte, string prefix = "") { try { if (key == null) { throw new ArgumentNullException(nameof(key)); } if (Exists(key, prefix)) { if (!Remove(key, prefix)) { return(false); } } return(Add(key, value, expiressAbsoulte, prefix)); } catch (Exception ex) { NLogger.Error("修改缓存:" + ex.ToString()); return(false); } }
/// <summary> /// 执行中 的短信 /// </summary> /// <param name="tel"></param> /// <param name="dics"></param> /// <returns></returns> public bool Doing(string no) { try { var order = DalContext.Repository <Order>().TableNoTracking.Where(o => o.BillNo == no).FirstOrDefault(); if (order.OrderState < OrderStateEnum.执行中 || order.OrderState >= OrderStateEnum.务结束) { return(false); } var orderAddr = DalContext.Repository <OrderAddr>().TableNoTracking.Where(o => o.BillNo == no).FirstOrDefault(); var orderWaiter = DalContext.Repository <OrderWaiter>().TableNoTracking.Where(o => o.BillNo == no).OrderByDescending(o => o.IsLeader).FirstOrDefault(); if (IsTel(orderAddr.Tel)) { Dictionary <string, string> dics = new Dictionary <string, string>(); dics.Add("StartTime", no); dics.Add("ProductName", order.ProductName); dics.Add("ServiceNo", orderWaiter.ServiceName); return(MessageInterface.SmsSend(orderAddr.Tel, "执行中", dics)); } } catch (Exception exc) { NLogger.Error($"订单{no}'执行中'短信发送失败, {exc.Message}"); } return(false); }
void TranslateTextToControl(string sText) { sText = System.Text.RegularExpressions.Regex.Replace(sText, "&#x(0?[0-8B-F]|1[0-9A-F]|7F);", ""); if (sText.Length < 1) { return; } vPanel.Children.Clear(); using (MemoryStream ms = new MemoryStream(ASCIIEncoding.UTF8.GetBytes(sText))) { object obj = XamlReader.Load(ms); if (obj is Section) { TranlateSection(obj as Section, vPanel.Children); } else if (obj is Span) { NLogger.Error("TranslateTextToControl Invalid span\n" + sText.ToString()); } else { NLogger.Error("TranslateTextToControl Invalid object\n" + sText.ToString()); } } }
/// <summary> /// /// </summary> /// <param name="context"></param> /// <returns></returns> public override Task OnExceptionAsync(ExceptionContext context) { var request = context.HttpContext.Request; string url = request.Path + (request.QueryString.HasValue ? $"?{request.QueryString.Value}" : ""); NLogger.Error("" + url + "\r\n" + context.Exception.Message + "\r\n" + context.Exception.StackTrace + ""); //context.ExceptionHandled = true; ResultDto Meta = ResultDto.Err(); JsonResult json = new JsonResult(new { Meta } ); JsonSerializerSettings jsetting = new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore }; jsetting.Converters.Add( new Newtonsoft.Json.Converters.IsoDateTimeConverter() { DateTimeFormat = "yyyy-MM-dd HH:mm:ss" } ); json.SerializerSettings = jsetting; json.ContentType = "application/json; charset=utf-8"; context.Result = json; return(base.OnExceptionAsync(context)); }
/// <summary> /// 修改缓存 /// </summary> /// <param name="key">缓存Key</param> /// <param name="value">新的缓存Value</param> /// <param name="expiresIn">缓存时长</param> /// <param name="isSliding">是否滑动过期(如果在过期时间内有操作,则以当前时间点延长过期时间)</param> /// <returns></returns> public bool Replace(string key, object value, TimeSpan expiresIn, bool isSliding = false) { try { if (key == null) { throw new ArgumentNullException(nameof(key)); } if (value == null) { throw new ArgumentNullException(nameof(value)); } if (Exists(key)) { if (!Remove(key)) { return(false); } } return(Add(key, value, expiresIn, isSliding)); } catch (Exception ex) { NLogger.Error("修改缓存:" + ex.ToString()); return(false); } }
private async Task RunSession(FSSession session, ushort index, int count, bool needNetty) { var account = "account" + index; var password = "******"; var playerName = "player" + index; try { session.SetDestroyedHandler((sender, e) => { NLogger.Info($"session:{session.GetId()} destroyed!"); }); //注册账号 var playerprx = session.UncheckedCast(IPlayerCoPrxHelper.uncheckedCast, IPlayerCoPrxHelper.ice_staticId()); var ret = await playerprx.RegOrLoginReqAsync(account, password); NLogger.Debug("RegOrLoginReqAsync ok:" + account + ", result=" + ret); var zoneprx = session.UncheckedCast(IZoneCoPrxHelper.uncheckedCast, IZoneCoPrxHelper.ice_staticId()); await zoneprx.TestApiReqAsync(); NLogger.Debug("TestApiReqAsync ok:" + account); for (int i = 0; i < 20; ++i) { var str = Console.In.ReadLine(); switch (str) { case "1": await zoneprx.TestApiReq2Async(); break; case "13": await zoneprx.TestApiReq3Async(); break; } } NLogger.Info($"{account} playerPrx end!"); } catch (Ice.Exception ex) { NLogger.Error(account + ":" + ex.Message); } catch (System.Exception e) { NLogger.Error(account + ":" + e.ToString()); } finally { //session.Destory(); } }
public void WriteToConsoleTest() { NLogger logger = new NLogger(); logger.Fatal("Fatal message"); logger.Error("Error message"); logger.Info("Info message"); logger.Debug("Debug message"); }
/// <summary> /// /// </summary> /// <returns></returns> public ActionResult Index() { Logger.Info("日志记录成功"); Logger.Error("日志记录失败"); NLogger.Info("日志记录成功n"); NLogger.Error("日志记录失败n"); return(View()); }
public void ErrorTest() { ILogger nLogger = Substitute.For <ILogger>(); NLogger logger = new NLogger(nLogger); logger.Error("message", new object[] { }); nLogger.Received().Error("message", Arg.Any <object[]>()); }