public void OnException(ExceptionContext filterContext) { ExceptionDetail exceptionDetail = new ExceptionDetail() { ExceptionMessage = filterContext.Exception.Message, StackTrace = filterContext.Exception.StackTrace, ControllerName = filterContext.RouteData.Values["controller"].ToString(), ActionName = filterContext.RouteData.Values["action"].ToString(), Date = DateTime.Now }; using (LoggerContext db = new LoggerContext()) { db.ExceptionDetails.Add(exceptionDetail); db.SaveChanges(); } filterContext.ExceptionHandled = true; }
public async Task <ValidatedResult <TResponse> > PublishAsync <TResponse>(IAsyncNotification asynchNotifcation) { using (LoggerContext.DecorateWithUser()) { _logger.Debug("Publish {@validationResult} for {User}", asynchNotifcation); } var validationSummary = _requestValidator.Validate(asynchNotifcation); var validationResult = new ValidatedResult <TResponse> { ValidationSummary = validationSummary }; if (validationSummary.IsValid) { await _mediator.PublishAsync(asynchNotifcation); } return(await Task.FromResult(validationResult)); }
public bool[] GetTwoAnswers(int questionIndex) { using (var xmlReader = XmlReader.Create(_xmlUrl)) { var result = new bool[4] { true, true, true, true }; var questions = new XmlQuestionRepository(xmlReader).GetAll(); var correctAnswerIndex = questions[questionIndex].Answers.ToList().IndexOf(questions[questionIndex].CorrectAnswer); result[correctAnswerIndex] = false; using (var context = new LoggerContext()) { var log = context.UserAnswerLogs.Where(l => l.QuestionNumber == questionIndex).FirstOrDefault(); if (log == null) { var rand = new Random(); int i = rand.Next(4); while (i == correctAnswerIndex) { i = rand.Next(4); } result[i] = false; } else { var stats = new int[] { log.FirstAnswerCount, log.SecondAnswerCount, log.ThirdAnswerCount, log.FourthAnswerCount, }; int indexOfMax = 0; int max = -1; for (int i = 0; i < 4; i++) { if (stats[i] >= max && i != correctAnswerIndex) { indexOfMax = i; max = stats[i]; } } result[indexOfMax] = false; } } return(result); } }
private ValidatedResult <TResponse> GetValidatedResult <TResponse>(IRequest <TResponse> request, ValidationSummary validationSummary) { var validationResult = new ValidatedResult <TResponse> { ValidationSummary = validationSummary }; if (validationSummary.IsValid) { var response = GetResult(request); validationResult.Result = response; } using (LoggerContext.DecorateWithUser()) { _logger.Debug("Response {@validationResult} for {User}", request); } return(validationResult); }
public void Add(LoggerContext logType, string LogMessage, string LogauxField = "", string LogauxField2 = "") { if (LogMessage.Length == 0) { return; } string errortypeDescription = string.Empty; switch (logType) { case LoggerContext.Info: errortypeDescription = "Info"; break; case LoggerContext.Error: errortypeDescription = "Error"; break; case LoggerContext.Fatal: errortypeDescription = "Fatal"; break; case LoggerContext.Warn: errortypeDescription = "Warning"; break; default: errortypeDescription = "Info"; break; } string log = string.Format("\"Type\":\"{0}\",\"Message\":\"{1}\",\"AuxField1\":\"{2}\",\"AuxField2\":\"{3}\",\"LogID\":{4} ", errortypeDescription, LogMessage, LogauxField, LogauxField2, logCounter); _Logging.Add(log); Console.WriteLine(log); logCounter += 1; }
internal static LoggerContext CreateDatabase(string connectionString) { if (connectionString is null) { throw new ArgumentNullException("Connectonstring can not be null"); } var dbContext = new LoggerContext(connectionString); if (!File.Exists(connectionString)) { var dir = new FileInfo(connectionString).Directory.FullName; if (!Directory.Exists(dir)) { Directory.CreateDirectory(dir); } File.Create(connectionString).Close(); dbContext.Database.Migrate(); return(dbContext); } return(dbContext); }
public override void OnException(HttpActionExecutedContext actionExecutedContext) { var httpActionContext = actionExecutedContext.ActionContext; var userEmail = ConverterBll.Email(httpActionContext.RequestContext); var location = ConverterBll.Location(httpActionContext); LoggerContext.Log(location, new LogUserInfoSurragateType() { UserKey = userEmail, LogKategori = "", LogTuru = LogTuru.Hata, LogIcerik = actionExecutedContext.Exception.Message }); #region Respose Düzenleme //actionExecutedContext.Response = actionExecutedContext.Request.CreateErrorResponse(HttpStatusCode.InternalServerError, actionExecutedContext.Exception.Message); //actionExecutedContext.Response.Headers.Add("HataID", logkaydi.ID.ToString()); #endregion base.OnException(actionExecutedContext); }
private void Process(TMessage message) { _log.Debug(LoggerContext.New(Name), "thread pool info."); string messageTag = _tagMessageProvider(message); if (string.IsNullOrEmpty(messageTag)) { _handleMessage(message); return; } Receive(message); if (!NeedToHandle(message)) { return; } Preprocess(message); Child child = GetOrCreateRouterItem(messageTag); child.Producer.Produce(message); }
public static void InsertItem(SqlServerLoggingItem item) { using (LoggerContext ctx = new LoggerContext()) { try { var x = item.Api ?? ""; ctx.Database.ExecuteSqlCommand($"INSERT INTO BACKEND_LOG(TST,USERNAME,API,APP,ENDPOINT,QUERY,TIMING,STATUSCODE) " + $"VALUES (CURRENT_TIMESTAMP,@Username,@Api,@App,@Endpoint,@Query,@Timing,@StatusCode)", new SqlParameter("@Username", item.Username ?? ""), new SqlParameter("@Api", item.Api ?? ""), new SqlParameter("@App", item.App ?? ""), new SqlParameter("@Endpoint", item.Endpoint ?? ""), new SqlParameter("@Query", item.Query ?? ""), new SqlParameter("@Timing", item.Timing), new SqlParameter("@StatusCode", item.StatusCode)); } catch (Exception ex) { Console.WriteLine($"Failed to insert log entry: {ex}"); } } }
public void OnActionExecuted(ActionExecutedContext filterContext) { log4net.ILog logger = log4net.LogManager.GetLogger(typeof(HomeController)); //Declaring Log4Net Database.SetInitializer <LoggerContext>(new DropCreateDatabaseIfModelChanges <LoggerContext>()); ReauesDetail reauesDetail = new ReauesDetail() { Requesttime = filterContext.HttpContext.Request.TimedOutToken.ToString(), RequestURI = filterContext.HttpContext.Request.Url.ToString(), Querystring = filterContext.HttpContext.Handler.ToString(), StatusCode = filterContext.HttpContext.Response.StatusCode.ToString() }; using (LoggerContext db = new LoggerContext()) { db.ReauesDetails.Add(reauesDetail); db.SaveChanges(); logger.Info(reauesDetail); } filterContext.ExceptionHandled = true; }
/// <summary> /// Starts the transport. /// </summary> public void Start() { if (RoutableTransportMode == RoutableTransportMode.OnDemand) { int workersThreads; int ioThreads; ThreadPool.GetMaxThreads(out workersThreads, out ioThreads); ThreadPool.SetMaxThreads(100 * Environment.ProcessorCount, ioThreads); ThreadPool.SetMinThreads(50, 50); } CheckConfiguration(); CreateQueuesIfNecessary(); if (ErrorQueue != null) { _errorQueue = new MessageQueue(MsmqUtilities.GetFullPath(ErrorQueue)); } if (!string.IsNullOrEmpty(InputQueue)) { IPluginQueue inputQueue = PluginQueueFactory.Create(InputQueue); IPluginQueue commandQueue = PluginQueueFactory.Create(UiCommandInputQueue); if (PurgeOnStartup) { inputQueue.Purge(); commandQueue.Purge(); } Logger.Info(LoggerContext.New(inputQueue.Name), "starting..."); Logger.Info(LoggerContext.New(commandQueue.Name), "starting..."); var factory = new MsmqRouterFactory(Logger, TimeSpan.FromSeconds(SecondsToWaitForMessage), GetTransactionTypeForSend, GetTransactionTypeForReceive()); _inputQueueRouter = CreateAndStartMainMessageConsumer(factory); _uiQueueRouter = CreateAndStartUiMessageConsumer(factory); Logger.Info(LoggerContext.New(inputQueue.Name), "started."); Logger.Info(LoggerContext.New(commandQueue.Name), "started."); _queue = inputQueue; } }
public async Task <RepositoryResult <Behavior> > Create(Behavior behavior) { var result = new RepositoryResult <Behavior>(); try { using (LoggerContext context = new LoggerContext()) { await context.Behaviors.AddAsync(behavior); await context.SaveChangesAsync(); result.Entitie = behavior; return(result); } } catch (Exception ex) { result.Sucess = false; result.Entitie = behavior; result.ErrorMessage = ex.Message; return(result); } }
//protected ISiteInstance SiteInstance { get; set; } public LoggerController(LoggerContext loggerContext) // , ISiteInstance siteInstance//SiteInstance site, { //this.Site = site; this.db = loggerContext; //this.SiteInstance = siteInstance; }
public SpearController(LoggerContext context) { _context = context; }
private void ProcessMessage(MessageEx message) { var m = message.Message; _messageId = m.Id; if (IsTransactional) { if (HandledMaxRetries(m.Id)) { Logger.Error(LoggerContext.New(message.MessageOrigin.Name), string.Format("Message has failed the maximum number of times allowed, ID={0}.", m.Id)); MoveToErrorQueue(message); return; } } //exceptions here will cause a rollback - which is what we want. if (StartedMessageProcessing != null) { StartedMessageProcessing(this, null); } TransportMessage result = Convert(m); if (SkipDeserialization) { result.BodyStream = m.BodyStream; } else { try { result.Body = Extract(m); } catch (TypeNotFoundWhileDeserializationException e) { Logger.Warn(LoggerContext.New(message.MessageOrigin.Name, result), "Could not extract message data.", e); OnFinishedMessageProcessing(message); return; } catch (Exception e) { Logger.Error(LoggerContext.New(message.MessageOrigin.Name, result), "Could not extract message data.", e); MoveToErrorQueue(message); OnFinishedMessageProcessing(message); // don't care about failures here return; } } //care about failures here var exceptionNotThrown = OnTransportMessageReceived(result, message); //and here var otherExNotThrown = OnFinishedMessageProcessing(message); //but need to abort takes precedence - failures aren't counted here, //so messages aren't moved to the error queue. if (_needToAbort) { throw new AbortHandlingCurrentMessageException(); } if (!(exceptionNotThrown && otherExNotThrown)) //cause rollback { throw new ApplicationException("Exception occured while processing message."); } }
public OrderController(ILogger <OrderController> logger, LoggerContext context, IOrderService service, IHttpContextAccessor httpContextAccessor) : base(logger, httpContextAccessor) { _context = context; _service = service; }
public StatsModel(LoggerContext context) { _context = context; }
public Repository(LoggerContext dbContext, ILogger <T> logger) { this._dbContext = dbContext; _logger = logger; this.Table = dbContext.Set <T>(); }
public DbQuestionRepository(LoggerContext context) { _context = context; }
public ErrorLogController(ILogger <ErrorLogController> logger, LoggerContext context, IErrorLogService service) { _logger = logger; _context = context; _service = service; }
//public static ILogAgent LoggerInstance() //{ // return new NLogAgent(); //} //public static ILogAgent LoggerInstance(string loggerName) //{ // return new NLogAgent(loggerName); //} public static ILogAgent LoggerInstance(LoggerContext loggerContext) { return(new NLogAgent(loggerContext)); }
public void Test1() { var context = new LoggerContext(); var log = context.EventLogs.Find(1); }
public LoggerController(LoggerContext context) { this._context = context; }
public LoggerRepository(LoggerContext context) { _context = context; }
public override void Execute() { WriteLiteral("\r\n"); #line 13 "..\..\Dashboard\Pages\Html\Logging.cshtml" Layout = new LayoutPage("Logs"); var loggerContext = new LoggerContext(); string jobId = Util.GetFileNameFromURL(RequestPath); if (!int.TryParse(Query("from"), out int from) || !int.TryParse(Query("count"), out int perPage)) { from = 0; perPage = 10; } var totalLogs = loggerContext.GetCounterValue(Storage.GetConnection(), jobId); var jobLogs = loggerContext.GetLogMessagesByJobId(Storage.GetConnection(), jobId, ++from, perPage); var pager = new Pager(from, perPage, totalLogs); #line default #line hidden WriteLiteral("\r\n<div class=\"row\">\r\n <div class=\"col-md-3\">\r\n "); #line 34 "..\..\Dashboard\Pages\Html\Logging.cshtml" Write(Html.JobsSidebar()); #line default #line hidden WriteLiteral("\r\n </div>\r\n <div class=\"col-md-9\">\r\n <h1 class=\"page-header\">Logs</h" + "1>\r\n"); #line 38 "..\..\Dashboard\Pages\Html\Logging.cshtml" if (!jobLogs.Any()) { #line default #line hidden WriteLiteral(" <div class=\"logs\">\r\n There are no logs found y" + "et.\r\n </div>\r\n"); #line 44 "..\..\Dashboard\Pages\Html\Logging.cshtml" } else { #line default #line hidden WriteLiteral(" <div class=\"table-responsive\">\r\n "); #line 48 "..\..\Dashboard\Pages\Html\Logging.cshtml" Write(Html.PerPageSelector(pager)); #line default #line hidden WriteLiteral(@" <table class=""table""> <thead> <tr> <th class=""min-width"">Log Level</th> <th>Message</th> <th class=""min-width align-right"">Date</th> </tr> </thead> <tbody> "); #line 58 "..\..\Dashboard\Pages\Html\Logging.cshtml" foreach (var log in jobLogs) { var logColor = Util.GetColorByLogLevel(log.LogLevel); #line default #line hidden WriteLiteral(" <tr class=\"js-jobs-list-row\">\r\n " + " <td class=\"min-width\">\r\n " + " <span class=\"badge\" style=\"background-color: rgba("); #line 64 "..\..\Dashboard\Pages\Html\Logging.cshtml" Write(logColor.R); #line default #line hidden WriteLiteral(", "); #line 64 "..\..\Dashboard\Pages\Html\Logging.cshtml" Write(logColor.G); #line default #line hidden WriteLiteral(", "); #line 64 "..\..\Dashboard\Pages\Html\Logging.cshtml" Write(logColor.B); #line default #line hidden WriteLiteral(", "); #line 64 "..\..\Dashboard\Pages\Html\Logging.cshtml" Write(logColor.A); #line default #line hidden WriteLiteral(");\">\r\n <span class=\"text-center\" style" + "=\"text-decoration: none;\">"); #line 65 "..\..\Dashboard\Pages\Html\Logging.cshtml" Write(log.LogLevel); #line default #line hidden WriteLiteral("</span>\r\n </span>\r\n " + " </td>\r\n <td>"); #line 68 "..\..\Dashboard\Pages\Html\Logging.cshtml" Write(log.Message); #line default #line hidden WriteLiteral("</td>\r\n <td class=\"min-width align-right\">"); #line 69 "..\..\Dashboard\Pages\Html\Logging.cshtml" Write(Html.RelativeTime(@log.DateCreation)); #line default #line hidden WriteLiteral("</td>\r\n </tr>\r\n"); #line 71 "..\..\Dashboard\Pages\Html\Logging.cshtml" } #line default #line hidden WriteLiteral(" </tbody>\r\n </table>\r\n " + " "); #line 74 "..\..\Dashboard\Pages\Html\Logging.cshtml" Write(Html.Paginator(pager)); #line default #line hidden WriteLiteral("\r\n </div>\r\n"); #line 76 "..\..\Dashboard\Pages\Html\Logging.cshtml" } #line default #line hidden WriteLiteral(" </div>\r\n</div>"); }
public DbExceptionDetailRepository(LoggerContext context) { _context = context; }
public DbPlayerStatisticsRepository(LoggerContext context) { _context = context; }
protected virtual void ConsumeCore(Action <TMessage> handleMessage) { var @while = While ?? (_ => true); Func <IObservable <TMessage> > takeWhile = () => _messageSource.Iterate(handleMessage, _scheduler, s => _log.Info(LoggerContext.New(Name), s)).TakeWhile(m => @while(m)); _observable = takeWhile.ToSelfRepairingHotObservable(e => { }); _subscription = _observable.Subscribe(new CompositeObserver(_observers)); }
public static void init(LoggerContext context) { logger.loggerContext = context; }
// Methods public static void Run(Window window = null) { // Loger var loggerContext = LoggerContext.Initialize(new Log4netLoggerFactory()); var logger = new Logger <Application>(); // Execute try { // AppSettings var appSettings = SettingsHelper.GetAllAppSettings(); if (appSettings == null) { throw new InvalidOperationException("appSettings=null"); } // Variables var appName = appSettings["appName"]; var appVersion = appSettings["appVersion"]; var listenUrl = appSettings["appListen"]; var hostingFilename = @"*.Hosting.json"; var servicesFilename = @"*.Services.dll"; // Context var autofacContext = new AutofacContext(hostingFilename); var aspnetContext = string.IsNullOrEmpty(listenUrl) == false ? new AspnetContext(autofacContext, listenUrl, servicesFilename) : null; var windowContext = new WindowContext(autofacContext, window); Action startAction = () => { aspnetContext?.Start(); windowContext?.Start(); }; Action endAction = () => { windowContext?.Dispose(); aspnetContext?.Dispose(); autofacContext?.Dispose(); loggerContext?.Dispose(); }; // Run logger.Info("========================================"); logger.Info(string.Format("Application started: appName={0}, appVersion={1}", appName, appVersion)); startAction.Invoke(); System.Windows.Application.Current.Exit += (s, e) => { endAction.Invoke(); logger.Info("Application ended"); logger.Info("========================================"); }; // Setting System.Windows.Application.Current.MainWindow.Title = string.Format("{0} ({1})", appName, appVersion); } catch (Exception exception) { // Error while (exception?.InnerException != null) { exception = exception.InnerException; } logger.Info(string.Format("Application error: exception={0}", exception?.Message), exception); logger.Info("========================================"); // Notify System.Windows.MessageBox.Show(string.Format("Application error: exception={0}", exception?.Message), "Application error"); } }