public Task <bool> LogRequest(string token, string ip, string url) { if (string.IsNullOrEmpty(token) && string.IsNullOrEmpty(url)) { return(Task.FromResult(false)); } var tokenEntity = Context.Set <Token>().FirstOrDefault(x => x.Id == token); if (tokenEntity == null) { return(Task.FromResult(false)); } tokenEntity.UsageCount = tokenEntity.UsageCount + 1; var log = new RequestLog { Token = token, IP = ip, Url = url }; Context.Set <RequestLog>().Add(log); return(Task.FromResult(Context.SaveChanges() > 0)); }
public RequestLog BuildForCurrentRequest() { var log = new RequestLog { Hash = _currentChain.OriginatingChain.GetHashCode(), Time = _systemTime.UtcNow(), }; if (_settings.TraceLevel == TraceLevel.Verbose) { heavyTrace(log); } if (_currentChain.OriginatingChain is RoutedChain) { log.HttpMethod = _request.HttpMethod(); log.Endpoint = _request.RelativeUrl(); } else if (_currentChain.OriginatingChain.InputType() != null) { log.Endpoint = _currentChain.OriginatingChain.InputType().FullName; log.HttpMethod = "n/a"; } else { log.Endpoint = _currentChain.OriginatingChain.Title(); log.HttpMethod = "n/a"; } return log; }
//[AbpAuthorize(AppPermissions.Pages_Tenant_RestaurantReq_EditRestReq)] public async Task EditRestReq(EditRestReqInput input) { var RestReq = await _RestReqRepository.GetAsync(input.Id); RestReq.RestSchedulesId = input.RestSchedulesId; RestReq.RequesterId = input.RequesterId; RestReq.UserId = input.UserId; var ReqStatusId = _RequestStatusRepository.GetAll().Where(a => a.StatusDesc == "Submitted").FirstOrDefault().Id; RestReq.RequestStatusID = ReqStatusId; await _RestReqRepository.UpdateAsync(RestReq); RequestLog requestLog = new RequestLog(); var userid = GetCurrentUser().Id; requestLog.RestRequestId = RestReq.Id; requestLog.RequestStatusId = (int)RestReq.RequestStatusID; requestLog.ActionDateTime = DateTime.Now; requestLog.UserId = (int)userid; await _RequestLogRepository.InsertAsync(requestLog); await UpdateSelectRestReqScheItem(input.targetItems); }
public HttpResponseMessage Post(HttpRequestMessage request) { var requestStream = request.Content.ReadAsStreamAsync().Result; using (var zip = ZipFile.Read(requestStream)) { foreach (var entry in zip) { var memory = new MemoryStream(); entry.Extract(memory); memory.Position = 0; var log = new ClientAppLog(CurrentUser, new StreamReader(memory).ReadToEnd()); log.Version = RequestLog.GetVersion(Request); IEnumerable <string> values; if (request.Headers.TryGetValues("Request-Token", out values)) { log.RequestToken = values.Implode(); } if (String.IsNullOrWhiteSpace(log.Text)) { continue; } Session.Save(log); } } return(new HttpResponseMessage(HttpStatusCode.OK)); }
private async Task LogResponse(HttpResponse resp, RequestLog log, Stopwatch timer, DbCore dbc, string ExceptionMessage = null) { bool hasException = ExceptionMessage != null; dbc.Entry(log); log.ResponseStatus = hasException ? 500 : resp.StatusCode; log.ResponseContentType = resp.Headers.GetValueOrDefault("Content-Type", ""); //ContentLength not always set. Fallback to buffer length if unset log.ResponseSize = (int)(resp.ContentLength ?? resp.Body.Length); log.Location = resp.Headers.GetValueOrDefault("Location", ""); //TODO: log.ResponseType = ???!!! //Earlier, the response.body stream was replaced with one that allows rewinding //so rewind to beginning, read it, and rewind it again. resp.Body.Seek(0, SeekOrigin.Begin); string responseAsText = await new StreamReader(resp.Body).ReadToEndAsync(); resp.Body.Seek(0, SeekOrigin.Begin); if (!responseAsText.IsNullOrWhitespace()) { log.ResponseText = responseAsText.Left(ResponseLogLength); } else if (hasException) { log.ResponseText = "Unhandled exception: "; log.ResponseText += ExceptionMessage.Left(ResponseLogLength - log.ResponseText.Length); } //Do as much work as possible before getting the time log.ResponseMs = (decimal)timer.Elapsed.TotalMilliseconds; await dbc.SaveChangesAsync(); }
private async Task <RequestLog> LogRequest(HttpRequest req, DateTime requestBegin, DbCore dbc) { RequestLog log = new RequestLog { RequestBegin = requestBegin, URL = req.GetDisplayUrl(), RequestMethod = req.Method, RequestContentType = req.Headers.GetValueOrDefault("Content-Type", ""), RequestSize = (int)(req.ContentLength ?? 0), IP = req.HttpContext.Connection.RemoteIpAddress.ToString(), UserAgent = req.Headers.GetValueOrDefault("User-Agent", ""), Referer = req.Headers.GetValueOrDefault("Referer", "") }; //Allow resetting stream back to start after reading it req.EnableRewind(); //Get the request body string requestAsText = await new StreamReader(req.Body).ReadToEndAsync(); //Save a bit of it for logging if (!requestAsText.IsNullOrWhitespace()) { log.RequestText = requestAsText.Left(RequestLogLength); } //Reset the request stream back to the beginning req.Body.Seek(0, SeekOrigin.Begin); dbc.RequestLogs.Add(log); await dbc.SaveChangesAsync(); return(log); }
public RouteInstrumentationReport AddReportLog(RequestLog report) { if (report.Failed) { IncrementExceptionCount(); } IncrementHitCount(); AddExecutionTime((long)report.ExecutionTime); _reportCache.Enqueue(report); while (_reportCache.Count > _settings.MaxRequestsPerRoute) { RequestLog r; if (_reportCache.TryDequeue(out r)) { if (r.Failed) { AddToErrorLog(r); } } } return this; }
public void Enqueue(RequestLog log) { lock (locker) { this.queue.Enqueue(log); } }
public async void WriteRequestLog(string jsonString) { try { var objToInsert = new RequestLog(); if (jsonString.Length < 2000) { objToInsert.requestJson = jsonString; } else { WriteEventLog("Dapper", "Error", "A Request Json was to long to be saved in DB"); } objToInsert.timestamp = DateTime.UtcNow; using (SqlConnection connection = new SqlConnection(builder.ConnectionString)) { await connection.InsertAsync(objToInsert); } } catch { //Fall through } }
public void does_display_if_there_are_response_headers() { var log = new RequestLog(); log.ResponseHeaders = new Header[]{new Header("a", "1"), new Header("b", "2"), new Header("c", "3")}; new ResponseHeadersTag(log).Render().ShouldBeTrue(); }
public void Store(RequestLog log) { var id = log.ChainId; _lock.Write(() => { if(_instrumentationReports.ContainsKey(id)) { var report = _instrumentationReports[id]; report.ReportUrl = _urls.UrlFor(new InstrumentationRouteDetailsInputModel { Id = log.ChainId }); report.AddReportLog(log); } else { var chain = _graph.Behaviors.FirstOrDefault(x => x.UniqueId == log.ChainId); var title = ChainVisualization.TitleForChain(chain); var report = new RouteInstrumentationReport(_settings, id, title) { ReportUrl = _urls.UrlFor(new InstrumentationRouteDetailsInputModel { Id = id }) }; report.AddReportLog(log); _instrumentationReports.Add(id, report); } }); }
public BehaviorNodeTraceTag(BehaviorNode node, RequestLog log) : base("li") { var description = Description.For(node); AddClass("node-trace").Data("node-id", node.UniqueId.ToString()); var container = Add("div").AddClass("node-trace-container"); container.Text(description.Title); var start = log.FindStep<BehaviorStart>(x => x.Correlation.Node == node); var finish = log.FindStep<BehaviorFinish>(x => x.Correlation.Node == node); if (start == null) { AddClass("gray"); return; } var exception = log.FindStep<ExceptionReport>(x => node.UniqueId.Equals(x.CorrelationId)); if (exception != null || !finish.Log.Succeeded) { AddClass("exception"); } var duration = finish.RequestTimeInMilliseconds - start.RequestTimeInMilliseconds; container.Add("span").Text(duration.ToString() + " ms").AddClass("node-trace-duration"); }
private void heavyTrace(RequestLog log) { log.RequestHeaders = _request.AllHeaderKeys().SelectMany(x => _request.GetHeader(x).Select(_ => new Header(x, _))).ToArray(); log.FormData = _request.Form; log.QueryString = _request.QueryString; }
public RequestLog BuildForCurrentRequest() { var log = new RequestLog { Hash = _currentChain.OriginatingChain.GetHashCode(), Time = _systemTime.UtcNow(), }; if (_settings.TraceLevel == TraceLevel.Verbose) { heavyTrace(log); } if (_currentChain.OriginatingChain is RoutedChain) { log.HttpMethod = _request.HttpMethod(); log.Endpoint = _request.RelativeUrl(); } else if (_currentChain.OriginatingChain.InputType() != null) { log.Endpoint = _currentChain.OriginatingChain.InputType().FullName; log.HttpMethod = "n/a"; } else { log.Endpoint = _currentChain.OriginatingChain.Title(); log.HttpMethod = "n/a"; } return(log); }
public RequestLog BuildForCurrentRequest() { var report = new ValueReport(); _requestData.WriteReport(report); var chainId = _currentChain.OriginatingChain == null ? Guid.Empty : _currentChain.OriginatingChain.UniqueId; var log = new RequestLog{ ChainId = chainId, Time = _systemTime.UtcNow(), RequestData = report, //ChainUrl = _urls.UrlFor(new ChainRequest{Id = chainId}), //DetailsUrl = _urls.UrlFor(new ChainDetailsRequest{Id = chainId}) }; if (_currentChain.OriginatingChain.Route != null) { log.HttpMethod = _request.HttpMethod(); log.Endpoint = _request.RelativeUrl(); } else if (_currentChain.OriginatingChain.InputType() != null) { log.Endpoint = _currentChain.OriginatingChain.InputType().FullName; log.HttpMethod = "n/a"; } else { log.Endpoint = ChainVisualization.TitleForChain(_currentChain.OriginatingChain); log.HttpMethod = "n/a"; } //log.ReportUrl = _urls.UrlFor(log); return log; }
protected HttpResponseMessage StartJob(Action <ISession, Config.Config, RequestLog> cmd) { var existsJob = new RequestLog(CurrentUser, Request, GetType().Name); existsJob.StartJob(Session, (x, y) => cmd(x, Config, y)); return(existsJob.ToResult(Request, Config)); }
public static void Main(string[] args) { var config = SwimbaitConfig.Get(); var environmentService = new EnvironmentService(config); //var swimbaitConfig = config.GetSection("Swimbait"); //var s = swimbaitConfig["RelayHost"]; var activity = File.ReadAllLines(environmentService.ActivityLogFilename); int counter = 1; foreach (var line in activity) { var log = RequestLog.FromCsv(line); if (log.Method == "GET") { var swimbaitResponse = UriService.GetResponse(environmentService.IpAddress, log.ActualPort, log.PathAndQuery); var yamahaResponse = UriService.GetResponse(IPAddress.Parse("192.168.1.213"), log.YamahaPort, log.PathAndQuery); var logService = new LogService(environmentService); logService.LogToDisk(counter, swimbaitResponse); logService.LogToDisk(counter, yamahaResponse); } counter++; } }
public void do_not_display_if_no_headers() { var log = new RequestLog(); log.ResponseHeaders.Any().ShouldBeFalse(); new ResponseHeadersTag(log).Render().ShouldBeFalse(); }
public HttpResponseMessage Put(ConfirmRequest request) { #if DEBUG if (request.RequestId == 0) { throw new Exception("При подтверждении должен быть указан идентификатор обновления"); } #endif //из-за изменения схемы подтверждения обновления при переходе с версии на версию идентификатор обновления //не передается if (request.RequestId == 0) { return(new HttpResponseMessage(HttpStatusCode.OK)); } var log = Session.Get <RequestLog>(request.RequestId); //если уже подтверждено значит мы получили информацию об импортированных заявках if (log.IsConfirmed) { log.Error += request.Message; } else { //записываем информацию о запросе что бы в случае ошибки повторить попытку var failsafe = Path.Combine(Config.FailsafePath, log.Id.ToString()); File.WriteAllText(failsafe, JsonConvert.SerializeObject(request)); var task = RequestLog.RunTask(Session, x => Confirm(x, log.Id, Config, request)); if (task.IsFaulted) { return(new HttpResponseMessage(HttpStatusCode.InternalServerError)); } } return(new HttpResponseMessage(HttpStatusCode.OK)); }
public void Strip_branch() { var config = new Config.Config(); config.UpdatePath = "."; var log = new RequestLog(new User(), new Version()) { Branch = "migration" }; var data = new AnalitfNetData(); var result = config.GetUpdatePath(data, log); Assert.AreEqual(".\\migration", result); data.BinUpdateChannel = "beta"; result = config.GetUpdatePath(data, log); Assert.AreEqual(".\\migration-beta", result); data.BinUpdateChannel = "migration-beta"; result = config.GetUpdatePath(data, log); Assert.AreEqual(".\\migration-beta", result); data.BinUpdateChannel = "migration"; result = config.GetUpdatePath(data, log); Assert.AreEqual(".\\migration", result); data.BinUpdateChannel = "rtm"; result = config.GetUpdatePath(data, log); Assert.AreEqual(".\\migration", result); log.Branch = "master"; data.BinUpdateChannel = "migration"; Assert.AreEqual(".\\rtm", config.GetUpdatePath(data, log)); }
public void AddLogs(int type, List <PlatformLog> logs) { using (var db = base.NewDB()) { var groups = logs.GroupBy(x => x.Time.ToGroupHour()).ToList(); var hours = groups.Select(x => x.Key).ToArray(); var existings = db.RequestLogs.Where(x => x.Type == type && hours.Contains(x.GroupHour)).ToList(); foreach (var group in groups) { foreach (var platform in group.GroupBy(x => x.Platform)) { var existing = existings.FirstOrDefault(x => x.GroupHour == group.Key && x.Platform == platform.Key); if (existing == null) { var time = platform.Max(x => x.Time); var log = new RequestLog(type, platform.Key, time, platform.Count()); db.RequestLogs.Add(log); } else { existing.Value += platform.Count(); existing.Date = DateTime.Now; } } } db.SaveChanges(); } }
private void Init() { inputStream = new CvsStream(new MemoryStream()); outputStream = new CvsStream(new MemoryStream()); this.config = SharpCvsLibConfig.GetInstance(); try { if (config.Log.DebugLog.Enabled) { requestLog = new RequestLog(); responseLog = new ResponseLog(); this.InputStream.RequestMessage.MessageEvent += new EncodedMessage.MessageHandler(requestLog.Log); this.OutputStream.ResponseMessage.MessageEvent += new EncodedMessage.MessageHandler(responseLog.Log); } } catch (Exception e) { LOGGER.Error(e); } if (null == config) { config = new SharpCvsLibConfig(); } LOGGER.Debug("Config=[" + config.ToString() + "]"); if (this.repository == null) { this.repository = DeriveWorkingDirectory(); } }
protected override async Task <HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) { var pocetak = DateTime.Now; // stopwatch? var response = await base.SendAsync(request, cancellationToken); var kraj = DateTime.Now; var log = new RequestLog { Request = JsonConvert.SerializeObject(new { request.Content, request.Headers, request.Method, request.RequestUri }), VrijemePocetka = pocetak, VrijemeKraja = kraj }; repo.Insert(log); return(response); }
public RequestLinksTag(RequestLog log) { AddHeader("Chain Details"); Add("li").Add("a").Id("chain-summary").Attr("href", "#").Text("View Summary"); Add("li").Add("span/a").Attr("href", log.DetailsUrl).Text("View Details").AddClass("external").Attr("target", "_blank"); }
internal void ReportBatch(LogBatch[] logBatchs) { if (logBatchs.Length == 0) { return; } List <RequestLog> logs = new List <RequestLog>(); foreach (LogBatch logBatch in logBatchs) { foreach (LogMessage message in logBatch.messages) { RequestLog log = new RequestLog(); log.LogLevel = logBatch.logLevel; log.Logger = logBatch.logger; log.Timestamp = message.timestamp; log.Message = message.message; log.Exception = message.exception; logs.Add(log); } } Invoker.InvokeSync <object>(Invoker.Api.LOGGERSERVICE_PUT, new object[] { logs }); }
public void Enqueue(RequestLog log) { lock (Locker) { queue.Enqueue(log); } }
public static void LogDebug(string message, string detailed = null, Dictionary <string, string> tags = null) { lock (Locker) { Console.WriteLine(message + (detailed != null ? " | " + detailed : "") + "\n\n"); var error = new RequestLog(""); error.Messages.Add(new Message(0, message)); if (detailed != null) { error.Messages.Add(new Message(40, detailed)); } error.Tags.Add(new Tag("Type", "DEBUG")); error.Tags.Add( new Tag("Memory", (System.Diagnostics.Process.GetCurrentProcess().WorkingSet64 / 1048576) + "Mb")); if (tags != null) { foreach (var key in tags.Keys) { error.Tags.Add(new Tag(key, tags[key])); } } error.Messages.Add(new Message(0, "End")); error.Response = ""; if (SplunkEnabled && splunkClient != null) { splunkClient.Enqueue(error); } } }
private void mcbHistory_SelectedIndexChanged(object sender, EventArgs e) { Debug.WriteLine("mcbHistoryCount:" + mcbHistoryCount); RequestLog siEntiy = (RequestLog)mcbHistory.SelectedItem; if (mcbHistoryCount == 2) { SQLiteConnectionStringBuilder sb = new SQLiteConnectionStringBuilder(); sb.DataSource = dbDirectory; SQLiteConnection con = new SQLiteConnection(sb.ToString()); con.Open(); RequestLog entity = con.Query <RequestLog>("select * from RequestLog where Id=" + siEntiy.Id + " order by UpdateTime desc limit 0,10").SingleOrDefault(); //RequestLog entity = con.Get<RequestLog>(siEntiy.Id); mtbUrl.Text = entity.Url; mtbBody.Text = entity.RequestBody;; BindTreeView(tvBody, mtbBody.Text); mcbRequestType.Text = siEntiy.RequestType; if (!mcbEmptyResponse.Checked) { mtbResponse.Text = siEntiy.Response + "\r\n\r\n" + mtbResponse.Text; } else { mtbResponse.Text = siEntiy.Response; } BindTreeView(tvResponse, siEntiy.Response); if (siEntiy.RequestType == "Get") { //txtRequestData.Enabled = false; //txtRequestData.BackColor = Color.Gray; //treeView2.Enabled = false; //treeView2.BackColor = Color.Gray; mtcBody.Enabled = false; mtcBody.BackColor = Color.Gray; } tvHeader.Nodes.Clear(); mgHeader.Rows.Clear(); List <RequestHeader> list = con.Query <RequestHeader>("select * from RequestHeader where RequestLogID=" + siEntiy.Id).ToList(); foreach (var item in list) { mgHeader.Rows.Add(item.Key, item.Value); tvHeader.Nodes.Add(item.Key + ":" + item.Value); } con.Close(); } else { ++mcbHistoryCount; } }
public RequestMetadata GetRequestMetadata(RequestLog source) { var entries = new List<object>(source.LogTable.Rows.Count); foreach (DataRow row in source.LogTable.Rows) { try { object entry = mEntryFactory.CreateEntry(row); if (entry != null) { entries.Add(entry); } } catch (ArgumentException exception) { Trace.TraceWarning(exception.Message); } } var commandEntries = entries.OfType<CommandEntry>(); return new RequestMetadata { Entries = entries, Statistics = new RequestMetadataStatistics { TotalCommands = commandEntries.LongCount(), TotalDuration = commandEntries.Aggregate(TimeSpan.Zero, (value, entry) => value + entry.Duration), TotalBytesReceived = commandEntries.Sum(x => x.BytesReceived), TotalBytesSent = commandEntries.Sum(x => x.BytesSent), TotalDuplicateCommands = commandEntries.LongCount(x => x.IsDuplicate) } }; }
public async Task Invoke(HttpContext context, IRequestLoggerService requestLoggerService) { var requestLog = new RequestLog() { Datetime = DateTime.UtcNow, Username = context.User.Identity.Name }; context.Request.EnableBuffering(); var buffer = new byte[Convert.ToInt32(context.Request.ContentLength)]; await context.Request.Body.ReadAsync(buffer, 0, buffer.Length); var bodyAsText = Encoding.UTF8.GetString(buffer); requestLog.Path = context.Request.Path; requestLog.QueryString = context.Request.QueryString.ToString(); requestLog.Body = bodyAsText; context.Request.Body.Position = 0; await _next(context); requestLog.StatusCode = (HttpStatusCode)context.Response.StatusCode; await requestLoggerService.Add(requestLog); PreventOverGrowth(requestLoggerService); }
static void HandleMessage(RequestLog msg) { Console.ForegroundColor = ConsoleColor.Red; Console.WriteLine("Input: {0}", msg.Input); Console.WriteLine("Output: {0}", msg.Output); Console.ResetColor(); }
private IEnumerable <LogItem> buildLogs(RequestLog log) { var stack = new Stack <BehaviorNode>(); var titles = new Cache <BehaviorNode, string>(node => Description.For(node).Title); var steps = log.AllSteps().ToArray(); foreach (var step in steps) { (step.Log as BehaviorStart).CallIfNotNull(x => stack.Push(x.Correlation.Node)); var node = findNode(step, stack, steps); yield return(new LogItem { behavior = node == null ? "Unknown" : titles[node], time = step.RequestTimeInMilliseconds, html = determineHtml(step.Log) }); (step.Log as BehaviorFinish).CallIfNotNull(x => stack.Pop()); } }
public static void BeginRequest(string msg, object request, string tripId = null) { lock (Locker) { object thread = Thread.CurrentThread.ManagedThreadId; if (requestLog == null || (threadsEnabled.ContainsKey(thread) && !threadsEnabled[thread])) { return; } if (!requestLog.ContainsKey(thread)) { var json = ""; if (request != null) { json = JsonSerializer.SerializeToString(request); } requestLog[thread] = new RequestLog(json, tripId); numBegunRequests[thread] = 0; } if (!numBegunRequests.ContainsKey(thread)) { numBegunRequests[thread] = 0; } numBegunRequests[thread] = numBegunRequests[thread] + 1; threadsEnabled[thread] = true; Log(msg, request); Tab(); } }
public void content_type_with_no_content_type_header() { var log = new RequestLog(); log.ResponseHeaders = new Header[0]; log.ContentType.ShouldEqual("Unknown"); }
public void content_type_with_a_content_type_header() { var log = new RequestLog(); log.ResponseHeaders = new Header[]{new Header(HttpResponseHeader.ContentType, MimeType.Javascript.Value)}; log.ContentType.ShouldEqual(MimeType.Javascript.Value); }
public Dictionary <string, object> get_request_Id(RequestLog query) { var dict = new Dictionary <string, object>(); var log = _cache.Find(query.Id); if (log == null) { return(dict); } var request = log.ToDictionary(); dict.Add("request", request); request.AddHeaders("request-headers", log.RequestHeaders); request.AddHeaders("response-headers", log.ResponseHeaders); var chain = _graph.Behaviors.FirstOrDefault(x => x.GetHashCode() == log.Hash); request.Add("title", chain.Title()); request.AddNameValues("querystring", log.QueryString); request.AddNameValues("form", log.FormData); request.Add("logs", buildLogs(log).ToArray()); return(dict); }
public void LogRequestChange(Request request, VandivierProductManagerContext context, [Optional] string changeNote) { IDbWriteService dbWriteService = new DbWriteService(context); RequestLog requestToLog = null; requestToLog = new RequestLog(); requestToLog.RequestId = request.Id; if (request.ProductId != null) { requestToLog.ProductId = request.ProductId; } requestToLog.ChangeNote = changeNote; requestToLog.RequestDescription = request.RequestDescription; requestToLog.RequestTypeId = request.RequestTypeId; requestToLog.StatusTypeId = request.StatusTypeId; requestToLog.StoreId = request.StoreId; requestToLog.SupplierId = request.SupplierId; requestToLog.UserId = request.UserId ?? string.Empty; requestToLog.OriginalCreatedOnDate = request.CreatedOn; requestToLog.OriginalCreatedByUser = request.CreatedBy; requestToLog.CreatedOn = DateTime.Now; requestToLog.CreatedBy = UserDto.UserId; dbWriteService.Add <RequestLog>(requestToLog); dbWriteService.SaveChanges(); }
public RequestLinksTag(RequestLog log, IUrlRegistry urls) { AddHeader("Chain Details"); Add("li").Add("a").Id("chain-summary").Attr("href", "#").Text("View Summary"); Add("li").Add("span/a").Attr("href", urls.UrlFor(new ChainDetailsRequest{Id = log.ChainId})).Text("View Details").AddClass("external").Attr("target", "_blank"); }
protected void Page_Load(object sender, EventArgs e) { // Setup title CurrentMaster.Title.TitleText = GetString("ViewRequest.Title"); CurrentMaster.Title.TitleImage = GetImageUrl("Objects/__GLOBAL__/Object.png"); guid = QueryHelper.GetGuid("guid", Guid.Empty); if (guid != Guid.Empty) { // Find the root log RequestLog log = CMSFunctions.FindRequestLog(guid); if (log != null) { // Setup the logs RequestLogs logs = log.ParentLogs; plcLogs.Controls.Add(new LiteralControl("<div><strong> " + logs.RequestURL + "</strong> (" + logs.RequestTime.ToString("hh:MM:ss") + ")</div><br />")); logFiles.Log = logs.FilesLog; logCache.Log = logs.CacheLog; logOutput.Log = logs.OutputLog; logSec.Log = logs.SecurityLog; logMac.Log = logs.MacrosLog; logSQL.Log = logs.QueryLog; logState.Log = logs.ViewStateLog; logReq.Log = logs.RequestLog; logFarm.Log = logs.WebFarmLog; } } }
public void Log <TState>(LogLevel logLevel, EventId eventId, TState state, Exception exception, Func <TState, Exception, string> formatter) { try { if (typeof(TState) == typeof(HttpContext)) { object obj = state; var context = (HttpContext)obj; string requestBody = ReadRequestStream(context.Request.Body); RequestLog log = new RequestLog() { ID = Guid.NewGuid(), Body = requestBody, Method = context.Request.Method, Url = context.Request.Path, CreateDate = DateTime.UtcNow, LastUpdated = DateTime.UtcNow }; //RepoCache.Get<RequestLog>() // .Add(log) // .Save(); } } catch (Exception) { } }
public string LogResponse(string className, string methodName, string response, string workflow, string tui) { paramFile PF = new paramFile(ParamsPath); try { string dbCon = PF.getDatabaseConnectionString(DBConstants.MainDBLog); DataOperation DO = new DataOperation(dbCon); RequestLog log = new RequestLog(); log.ClassName = className; // this.GetType().Name; log.MethodName = methodName; log.Request = ""; log.Response = response; log.TUI = tui; log.IP = IP; log.WorkFlow = workflow; DO.BeginTRansaction(); int result = DO.iteratePropertyObjectsAndInsert(log, "requestLog", false); DO.EndTRansaction(); return("success"); } catch (Exception) { return("fail"); } }
public Dictionary<string, object> get_request_Id(RequestLog query) { var dict = new Dictionary<string, object>(); var log = _cache.Find(query.Id); if (log == null) { return dict; } var request = log.ToDictionary(); dict.Add("request", request); if (log.RequestHeaders != null) request.AddHeaders("request-headers", log.RequestHeaders); if (log.ResponseHeaders != null) request.AddHeaders("response-headers", log.ResponseHeaders); var chain = _graph.Behaviors.FirstOrDefault(x => x.GetHashCode() == log.Hash); request.Add("title", chain.Title()); if (log.QueryString != null) request.AddNameValues("querystring", log.QueryString); if (log.FormData != null) request.AddNameValues("form", log.FormData); request.Add("logs", buildLogs(log).ToArray()); return dict; }
public void status_is_assumed_to_be_200_if_not_failed_and_no_explicit_status_was_recorded() { var log = new RequestLog(); log.Failed.ShouldBeFalse(); log.HttpStatus.Status.ShouldEqual(HttpStatusCode.OK); log.HttpStatus.Description.ShouldEqual("OK"); }
public void Store(RequestLog log) { _reports.Enqueue(log); while (_reports.Count > _settings.MaxRequests) { _reports.Dequeue(); } }
public void Store(RequestLog log) { _reports.Enqueue(log); while (_reports.Count > _settings.MaxRequests) { RequestLog _; _reports.TryDequeue(out _); } }
private void AddToErrorLog(RequestLog report) { _reportErrorCache.Enqueue(report); while (_reportErrorCache.Count > _settings.MaxErrorsPerRoute) { RequestLog r; _reportErrorCache.TryDequeue(out r); } }
public void use_the_last_status_written() { var log = new RequestLog(); log.AddLog(12, new HttpStatusReport{Status = HttpStatusCode.Unauthorized}); log.AddLog(15, new HttpStatusReport{Status = HttpStatusCode.NotAcceptable}); log.HttpStatus.Status.ShouldEqual(HttpStatusCode.NotAcceptable); log.HttpStatus.Description.ShouldEqual("Not Acceptable"); }
public void status_is_assumed_to_be_500_if_failed_and_no_other_explicit_status_was_recorded() { var log = new RequestLog(); log.Failed = true; log.HttpStatus.Status.ShouldEqual(HttpStatusCode.InternalServerError); log.HttpStatus.Description.ShouldEqual("Internal Server Error"); }
public void SetUp() { theLog = new RequestLog(); theNode = new FakeNode(); _tag = new Lazy<HtmlTag>(() => { return new BehaviorNodeTraceTag(theNode, theLog); }); }
public void Store(RequestLog log) { log.SessionTag = CurrentSessionTag; _reports.Enqueue(log); while (_reports.Count > _settings.MaxRequests) { RequestLog _; _reports.TryDequeue(out _); } }
public TracingOutlineTag(RequestLog log) { AddHeader("Tracing"); log.AllSteps().Each(x => { var node = addNode(x); node.Container.Add("span").AddClass("node-trace-duration").Text(x.RequestTimeInMilliseconds + " ms"); }); }
public void add_log() { var log = new RequestLog(); var stringMessage = new StringMessage("something"); log.AddLog(123.45, stringMessage); log.AddLog(234, "something"); log.AllSteps() .ShouldHaveTheSameElementsAs(new RequestStep(123.45, stringMessage), new RequestStep(234, "something")); }
public ResponseHeadersTag(RequestLog log) : base(ElementId, Heading) { if (!log.ResponseHeaders.Any()) { Render(false); return; } var detailsTag = new DetailsTableTag(); log.ResponseHeaders.OrderBy(x => x.Name).Each(header => detailsTag.AddDetail(header.Name, header.Value)); AppendContent(detailsTag); }
public void builds_the_log() { var theLog = new RequestLog(); var builder = MockRepository.GenerateStub<IRequestLogBuilder>(); builder.Stub(x => x.BuildForCurrentRequest()).Return(theLog); BindingScenario<FakeRequestModel>.For(x => { x.Service(builder); x.BindPropertyWith(theBinder, model => model.CurrentRequest); }).Model.CurrentRequest.ShouldBeTheSameAs(theLog); }
public void has_a_unique_id() { var log1 = new RequestLog(); var log2 = new RequestLog(); var log3 = new RequestLog(); log1.Id.ShouldNotEqual(Guid.Empty); log2.Id.ShouldNotEqual(Guid.Empty); log3.Id.ShouldNotEqual(Guid.Empty); log1.Id.ShouldNotEqual(log2.Id); log1.Id.ShouldNotEqual(log3.Id); log2.Id.ShouldNotEqual(log3.Id); }
private void writeLog(RequestLog log) { AddBodyRow(row => { row.Cell().Add("a").Text(log.LocalTime).Attr("href", log.ReportUrl); row.Cell(log.Endpoint); row.Cell(log.HttpMethod); var statusCell = row.Cell(); statusCell.Add("span").AddClass("http-status-code").Text(log.HttpStatus.Status.ToString()); statusCell.Add("span").AddClass("http-status-description").Text(log.HttpStatus.Description); row.Cell(log.ContentType); row.Cell(Math.Ceiling(log.ExecutionTime).ToString()).AddClass("number"); }); }
public RequestLogDataOutlineTag(RequestLog log, BehaviorChain chain) { AddHeader("Data"); log.RequestData.Reports.Where(x => x.Values.Any()).Each( report => { AddNode(report.Header(), report.ElementId()); }); if (log.ResponseHeaders.Any()) { AddNode(ResponseHeadersTag.Heading, ResponseHeadersTag.ElementId); } }
public HttpRequestVisualization get_request_details_Id(RequestLog request) { RequestLog log = _cache.Find(request.Id); if (log == null) { return new HttpRequestVisualization(null, null, _urls) { RedirectTo = FubuContinuation.RedirectTo<RequestVisualizationFubuDiagnostics>(x => x.get_requests_missing()) }; } BehaviorChain chain = _graph.Behaviors.FirstOrDefault(x => x.UniqueId == log.ChainId); return new HttpRequestVisualization(log, chain, _urls); }