public void Example() { var profiler = MiniProfiler.StartNew(); var myList = new List <string> { "A", "B", "C", "E" }; using (profiler.Step("Doing a collection of repeated work")) using (var aggregateTimer1 = profiler.Step("Doing part 1")) using (var aggregateTimer2 = profiler.Step("Doing part 2")) { foreach (var listItem in myList) { using (new Timing(profiler, aggregateTimer1, listItem)) { Method1(listItem); } using (new Timing(profiler, aggregateTimer2, listItem)) { Method2(listItem); } } } profiler.Stop(); Console.WriteLine(profiler.RenderPlainText()); }
private async Task TraceRequests(HttpContext context) { var profiler = MiniProfiler.StartNew("Tracing"); using (profiler.Step("Request")) { context.Response.OnStarting( state => { var httpContext = (HttpContext)state; profiler.Stop(); var profilerText = profiler.RenderPlainText().Replace("\n", " ").Replace("\r", " ").ToString(); httpContext.Response.Headers.Add(HeaderName, new[] { profilerText }); return(Task.FromResult(0)); }, context); await this._next(context); } this._logger.LogInformation( "Request {method} {url} => {statusCode} \n{profiler}", context.Request?.Method, context.Request?.Path.Value, context.Response?.StatusCode, profiler.RenderPlainText()); }
public void TestCompletenessReportGenerationSmard() { MiniProfiler profiler = MiniProfiler.StartNew(nameof(TestCompletenessReportGenerationSmard)); IList <CompletenessReport> crlist = new List <CompletenessReport>(); foreach (string boFile in Directory.GetFiles("Energiemenge/completeness", "50hz_prognose*.json")) { using (MiniProfiler.Current.Step($"Processing file {boFile}")) { JObject json; using (StreamReader r = new StreamReader(boFile)) { string jsonString = r.ReadToEnd(); json = JsonConvert.DeserializeObject <JObject>(jsonString); } Energiemenge em = (Energiemenge)BoMapper.MapObject(json, LenientParsing.Strict); CompletenessReport cr = em.GetCompletenessReport(); crlist.Add(cr); if (boFile.Contains("onshore.json")) { Assert.IsNotNull(cr.UserProperties); Assert.AreEqual <string>("yippi yippi yeah", cr.UserProperties["meineUp0"].Value <string>()); Assert.AreEqual <string>("krawall und remmidemmi", cr.UserProperties["meineUp1"].Value <string>()); } } } string resultString = JsonConvert.SerializeObject(crlist, new StringEnumConverter()); profiler.Stop(); System.Diagnostics.Debug.WriteLine($"Profiler results: {profiler.RenderPlainText()}"); }
protected void Application_BeginRequest(object sender, EventArgs e) { if (Request.IsLocal) { MiniProfiler.StartNew(); } }
public async Task RegisterSdk() { Register.RegisterWithSdk(); try { var profiler = MiniProfiler.StartNew("Test Trace"); using (profiler.Step("Start")) { await ListBuckets(); } profiler.Stop(); var awsTiming = profiler.GetTimingHierarchy().FirstOrDefault(x => string.Equals(x.Name, "AWS SDK - S3.ListBuckets")); Assert.NotNull(awsTiming); } finally { Register.DeregisterWithSdk(); } { var profiler = MiniProfiler.StartNew("Test Trace"); using (profiler.Step("Start")) { await ListBuckets(); } profiler.Stop(); var awsTiming = profiler.GetTimingHierarchy().FirstOrDefault(x => string.Equals(x.Name, "AWS SDK - S3.ListBuckets")); Assert.Null(awsTiming); } }
static void TestAutoFac() { var overallProcess = new Stopwatch(); overallProcess.Restart(); var profiler = MiniProfiler.StartNew("TestAutoFac"); using (profiler.Step("Main Work")) { var container = ContainerAutofacRegister.Configure(); Console.WriteLine("################## Auto face Ioc ###################"); using (var scope = container.BeginLifetimeScope()) { var hotelSvc = scope.Resolve <IHotelServices>(); var hh = hotelSvc.GetHotelAll().Result; foreach (var h in hotelSvc.GetHotelAll().Result) { Console.WriteLine($"{h.HotelId} - {h.Name} Status : {h.IsActive}"); } } Console.WriteLine("####################################################"); } overallProcess.Stop(); Console.WriteLine($"Elapsed Time {overallProcess.Elapsed} "); }
public void OnActionExecuting(ActionExecutingContext context) { MiniProfiler.StartNew(); if (MiniProfiler.Current != null) { Stack <IDisposable> stack; if (context.ActionDescriptor.Properties.ContainsKey(StackKey)) { stack = context.ActionDescriptor.Properties[StackKey] as Stack <IDisposable>; } else { stack = new Stack <IDisposable>(); context.ActionDescriptor.Properties[StackKey] = (object)stack; } MiniProfiler current = MiniProfiler.Current; if (current != null) { string controllerName = context.Controller.GetType().Name; string actionName = context.ActionDescriptor.DisplayName; stack.Push(MiniProfiler.Current.Step("Controller: " + controllerName + actionName)); } } }
static async Task Main(string[] args) { var profiler = MiniProfiler.StartNew("My Profiler Name"); using (profiler.Step("Main Work")) { // Do some work... Console.WriteLine("Hello World!"); var calc = new Calculator(); var x = calc.Add(2, calc.Divide(6, 2)); var d = await calc.LongTask(x); Console.WriteLine(d); } using (profiler.Step("Second Work")) { // Do some work... Console.WriteLine("Hello World!"); var calc = new Calculator(); var d = calc.Add(2, 3); Console.WriteLine(d); } Console.WriteLine(profiler.RenderPlainText()); }
public RequestScope(IRequestContext context) { _context = context; _miniProfiler = MiniProfiler.StartNew("Hot Chocolate GraphQL Query"); _queryTimer = new Stopwatch(); _queryTimer.Start(); }
protected void Application_BeginRequest() { if (Request.IsLocal) { MiniProfiler.StartNew(); } }
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IHostingEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } app.UseSwagger(); app.UseSwaggerUI(c => { c.SwaggerEndpoint("/swagger/v1/swagger.json", "MiniProfiler Test API"); c.IndexStream = () => { //return File.OpenRead("index.html"); // haaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaack 😛 var mockContext = new DefaultHttpContext(); var miniProfiler = MiniProfiler.StartNew("dummy"); var miniProfilerScriptInclude = miniProfiler.RenderIncludes(mockContext, RenderPosition.Left, true, true, 15, true, false).Value.Replace("<script", "<script data-authorized=\"true\""); using (var reader = new StreamReader(File.OpenRead("index.html"))) { var fileContent = reader.ReadToEnd(); var editedContent = fileContent.Replace("%replace_with_miniprofiler%", miniProfilerScriptInclude); return(new MemoryStream(Encoding.UTF8.GetBytes(editedContent))); } }; }); app.UseMiniProfiler(); app.UseMvc(); }
public void Intercept(IInvocation invocation) { PropertyInfo property = invocation.TargetType.GetProperty("Connection"); DbConnection conn = (DbConnection)property.GetValue(invocation.InvocationTarget); MiniProfiler mp = MiniProfiler.Current; if (mp == null) { mp = MiniProfiler.StartNew($"{invocation.TargetType}-{invocation.Method.Name}"); } conn = new StackExchange.Profiling.Data.ProfiledDbConnection(conn, MiniProfiler.Current); property.SetValue(invocation.InvocationTarget, conn); invocation.Proceed(); mp.Stop(); if (mp.Root != null) { if (mp.Root.CustomTimings.ContainsKey("sql")) { List <CustomTiming> list = mp.Root.CustomTimings["sql"]; StringBuilder sb = new StringBuilder(); sb.AppendLine($"【{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff")} {mp.Name}】"); foreach (var item in list) { if (item.ExecuteType == "Open" || item.ExecuteType == "Close") { continue; } sb.AppendLine($"{(item.Errored ? "【ERROR】" : "")}CommandString:{item.CommandString}\r\nExecuteType:{item.ExecuteType}\r\nDurationMilliseconds:{item.DurationMilliseconds}ms"); } Console.WriteLine(sb); } } }
private void EnsureProfilerStarted() { if (GetProfilerCurrent() == null) { MiniProfiler.StartNew(); } }
protected void Application_BeginRequest() { if (ShouldProfile()) { MiniProfiler.StartNew(); } }
public static void TestMultiThreaded() { var mp = MiniProfiler.StartNew("Locking"); void doWork() => Thread.Sleep(new Random().Next(1, 50)); using (mp.Step("outer")) { System.Threading.Tasks.Parallel.For(0, 5, i => { doWork(); using (mp.Step("step " + i)) { using (mp.CustomTiming("MyCustom", "test command")) { doWork(); } using (mp.Step("sub-step" + i)) { doWork(); } } }); } }
public async System.Threading.Tasks.Task HandleChangeAsync(IWpfTextView textView) { await ThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync(); try { var profiler = MiniProfiler.StartNew(nameof(HandleChangeAsync)); profiler.Storage = new NLogStorage(LogManager.GetLogger("profiler")); using (profiler.Step("HandleChangeCode")) { SnapshotPoint caretPosition = textView.Caret.Position.BufferPosition; Microsoft.CodeAnalysis.Document roslynDocument = caretPosition.Snapshot.GetOpenDocumentInCurrentContextWithChanges(); if (roslynDocument == null) { OutputWindowLogger.WriteLn($"Unable to get c# file to process. Name {caretPosition.Snapshot.ContentType.DisplayName}"); return; } await GotoAsyncPackage.Storage.AnalyzeAndUpdateSingleAsync(roslynDocument); } } catch (Exception ex) { LogManager.GetLogger("error").Error(ex, "CSharpFileContentOnChange.HandleChange"); OutputWindowLogger.WriteLn($"Exception occured during handling csharp file change: {ex.Message}"); } }
private static async Task Run(SolutionRunnerArguments args) { var assembly = Assembly.GetEntryAssembly() ?? throw new InvalidOperationException("No entry Assembly found!"); var solutionType = assembly .DefinedTypes .Where(t => typeof(ISolution).IsAssignableFrom(t) && !t.IsAbstract && !t.IsInterface && t.IsPublic) .FirstOrDefault(t => t.Name.Equals(args.Problem, StringComparison.OrdinalIgnoreCase)); if (solutionType is null) { await Console.Error.WriteLineAsync("Solution not implemented!"); return; } if (Activator.CreateInstance(solutionType) is not ISolution solution) { await Console.Error.WriteLineAsync("Solution not an ISolution!"); return; } var profiler = MiniProfiler.StartNew(solutionType.Name); var context = await CreateSolutionContext(assembly, solutionType.Name, args.UseTestData); using (profiler.Step("Run")) await solution.Run(context); Console.WriteLine(); Console.WriteLine(profiler.RenderPlainText()); }
protected async override Task OnInitializedAsync() { _profiler = MiniProfiler.StartNew(nameof(OnInitializedAsync)); using (_profiler.Step(nameof(StartAsync))) { await StartAsync(); } Console.WriteLine(_profiler.RenderPlainText()); }
protected void Application_BeginRequest() { // You can decide whether to profile here, or it can be done in ActionFilters, etc. // We're doing it here so profiling happens ASAP to account for as much time as possible. if (Request.IsLocal) // Example of conditional profiling, you could just call MiniProfiler.StartNew(); { MiniProfiler.StartNew(); } }
public IActionResult About() { var profiler = MiniProfiler.StartNew("Profiler on the Home Controller"); using (profiler.Step("Some Work")) { Thread.Sleep(100); ViewData["Message"] = "Your application description page."; } return(View()); }
protected void Application_BeginRequest(object sender, EventArgs e) { // set a unique id to the current request Trace.CorrelationManager.ActivityId = Guid.NewGuid(); if (Request.IsLocal) { MiniProfiler.StartNew(); } }
protected void Application_BeginRequest(object sender, EventArgs e) { HttpContext.Current.Response.Headers.Remove("Server"); if (GaneStaticAppExtensions.MiniProfilerEnabled) { // mini profiler MiniProfiler.StartNew(); } }
public async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next) { var profiler = MiniProfiler.StartNew("StartNew"); using (profiler.Step("Level1")) { //执行Action await next(); } WriteLog(profiler); }
public MiniProfiler GetProfiler() { if (profiler == null) { lock (instanceLock) if (profiler == null) { profiler = MiniProfiler.StartNew($"contained {Interlocked.Increment(ref index)}"); } } return(profiler); }
private static void OnAcquireRequestState(object sender, EventArgs e) { var app = (HttpApplication)sender; if (!MiniProfilerStarted(app) && ShouldProfile(app)) { MiniProfiler.StartNew(); if (app.Context != null && app.Context.Items != null) { app.Context.Items[MP_KEY] = true; } } }
static void SimpleUsage() { var proxyFactory = new ProfilingProxyFactory(); IRepository repository = new Repository(); IRepository repositoryProxy = proxyFactory.CreateProxy(repository); IService service = new Service(repositoryProxy); IService serviceProxy = proxyFactory.CreateProxy(service); MiniProfiler.StartNew(nameof(SimpleUsage)); serviceProxy.DoWork(); Console.WriteLine(MiniProfiler.Current.RenderPlainText()); }
/// <summary> /// 新增加Application_BeginRequest方法,添加MiniProfiler启动方法 /// </summary> protected void Application_BeginRequest() { MiniProfiler profiler = null; if (Request.IsLocal) { profiler = MiniProfiler.StartNew(); } using (profiler.Step("Application_BeginRequest")) { //Todo } }
public async Task Invoke(HttpContext context) { var profiler = MiniProfiler.StartNew($"Request - {context.TraceIdentifier} ('{context.Request.Path}')"); try { await _next.Invoke(context); } finally { profiler.Stop(); _log.LogInformation(profiler.RenderPlainText()); } }
static void Main(string[] args) { var profiler = MiniProfiler.StartNew("Contrived Console Main"); using (profiler.Step("Doing Stuff")) { System.Console.Write("Hello "); var program = new Program(); program.Run(); System.Console.WriteLine("World!"); } profiler.Stop(); System.Console.WriteLine(profiler.RenderPlainText()); }
/// <summary> /// The application begin request event. /// </summary> protected void Application_BeginRequest() { MiniProfiler profiler = null; // 可以在此處設置決定是否要對此請求進行概要分析,例如對使用者檢查“IsSystemAdmin”標誌,或類似情況; 這也可以在動作過濾器中完成,但這很簡單實用; 只為大多數用戶返回null。對於我們的測試,我們只會針對本地請求進行分析(似乎合理) if (Request.IsLocal) { profiler = MiniProfiler.StartNew(); } using (profiler.Step("Application_BeginRequest")) { // 您可以立即開始分析您的代碼 } }