public void Update(ITurnProvider turnProvider) { objectPositionCache.Clear(); using (PerformanceMeter.Start($"Map_UpdateCells_Early[{turnProvider.CurrentTurn}]")) { UpdateCells(UpdateOrder.Early); } mapLightLevelProcessor.ResetLightLevel(this); mapLightLevelProcessor.UpdateLightLevel(this); using (PerformanceMeter.Start($"Map_UpdateCells_Medium[{turnProvider.CurrentTurn}]")) { UpdateCells(UpdateOrder.Medium); } using (PerformanceMeter.Start($"Map_UpdateCells_Late[{turnProvider.CurrentTurn}]")) { UpdateCells(UpdateOrder.Late); } using (PerformanceMeter.Start($"Map_PostUpdateCells[{turnProvider.CurrentTurn}]")) { PostUpdateCells(); } }
public ActionResult <string> WatchingMethodWithExecutedCommands(uint value) { // create custom data (anonymous class) var testClass = new { TestInternalClass = new { Key = 1, Value = "2" }, Value = "3" }; // method performance info will reach with HttpContextAccessor and custom data // custom "CustomDataCommand" will be executed after performance watching is completed (work with method calls custom data) using (PerformanceMeter <PerformanceMeterController> .WatchingMethod(nameof(WatchingMethodWithExecutedCommands)) .WithSettingData .CallerFrom(_httpContextAccessor) .CallerSourceData() .CustomData(nameof(value), value) .CustomData(nameof(testClass), testClass) .WithExecutingOnComplete .Command(new CustomDataCommand()) .Command(new ExecutedCommand("bla-bla-bla")) .Action((pi) => { Debug.WriteLine($"Class name: {pi.ClassName}"); }) .Start()) { return(Ok($"{value}")); } }
public ActionResult SimpleStartWatchingWithIgnored() { using var pm = PerformanceMeter <PerformanceMeterController> .StartWatching(); // put your code with some logic here // sleep 1 sec Thread.Sleep(1000); // ignore this block in performance watching using (pm.Ignore()) { Thread.Sleep(5000); } // skip this step with minSaveMs (do not save the step results, but take into account its duration) using (pm.StepIf("Skipped step", minSaveMs: 1000)) { Thread.Sleep(999); } // execute action without performance watching pm.Executing().WithoutWatching().Start(() => Thread.Sleep(2000)); return(Ok()); }
public ActionResult <string> StartWatchingWithCallerNameFromAttribute([FromBody] string value) { // the method’s performance info will be amended with the caller's name (if internal HttpContextAccessor is null) using var pm = PerformanceMeter <PerformanceMeterController> .StartWatching(); return(Ok(value)); }
public static void Configure() { LogManager.Initialize(new LogProvider()); LogManager.GetLog(nameof(GameConfigurator)).Info($"Starting game. Version {Assembly.GetExecutingAssembly().GetName().Version}"); var config = LoadConfiguration(); ConfigurationManager.InitializeConfiguration(config); ImagesStorage.Current.Load(); IoC.Configure(); DialogsManager.Initialize(new DialogsProvider(IoC.Container.Resolve <IApplicationController>())); ItemsGeneratorManager.Initialize(new ItemsGenerator( config.ItemGenerator, ImagesStorage.Current, new AncientSpellsProvider())); DungeonMapGenerator.Initialize(ImagesStorage.Current, Settings.Current.DebugWriteMapToFile); #if DEBUG PerformanceMeter.Initialize(@".\Performance.log"); #endif }
private static void ActivityMethod() { using (var rootPm = new PerformanceMeter("Root activity", String.Empty)) { Class1 c11; using (new PerformanceMeter("create instance", rootPm)) { c11 = new Class1(); } using (new PerformanceMeter("Call Method 1 in loop", rootPm)) { for (int i = 0; i < 30; i++) { c11.Method1(); } } using (new PerformanceMeter("Call Method 2 in loop", rootPm)) { for (int i = 0; i < 60; i++) { c11.Method2(); } } Thread.Sleep(200); } }
public ActionResult SimpleStartWatchingWithSteps() { //using var pm = PerformanceMeter<PerformanceMeterController>.StartWatching(); using (var pm = PerformanceMeter <PerformanceMeterController> .WatchingMethod() .WithSettingData .CustomData("coins", 1) .CustomData("Coins sets", new { Gold = "Many", Silver = 5 }) .Start()) { // put your code with some logic here // add "Step 1" using (pm.Step("Step 1")) { Thread.Sleep(1000); } // skip this step with minSavems (not save, but consider duration in method performance watching) using (pm.StepIf("Skipped step", minSaveMs: 100)) { Thread.Sleep(10); } // ignore this block in performance watching using (pm.Ignore()) { Thread.Sleep(5000); } // add "Step 2" with custom data using (var pmStep = pm.Step("Step 2").AddCustomData("step2 custom data", "data!")) { // add "Step 3 in Step 2" using (pm.Step("Step 3 in Step 2")) { Thread.Sleep(1000); } // execute action without performance watching pm.Executing().WithoutWatching().Start(() => Thread.Sleep(2000)); // add custom data to "Step 2" pmStep.AddCustomData("step2 another custom data", "data2!"); // get and remove custom data from "Step 2" var customData = pmStep.GetAndRemoveCustomData <string>("step2 custom data"); Debug.WriteLine($"{customData}!!!"); // get custom data from "Step 2" (without removing) var anotherCustomData = pmStep.GetCustomData <string>("step2 another custom data"); } return(Ok()); } }
private static void Process(int i, PerformanceMeter parent) { using (PerformanceMeter pmeter = new PerformanceMeter("Process", parent)) using (ResourceMeter meter = new ResourceMeter(resourceName)) { Thread.Sleep(20); } }
public ActionResult SimpleStartWatchingFuncMethod() { using var pm = PerformanceMeter <PerformanceMeterController> .StartWatching(SimpleStartWatchingFuncMethod); // put your code with some logic here return(Ok()); }
public ActionResult <string> GetThreadSleepFromActionPerformance() { using (PerformanceMeter <Thread> .WatchingMethod <int>(Thread.Sleep).Start()) { Thread.Sleep(1000); } return(Ok(PerformanceMeter <Thread> .PerformanceInfo.MethodCalls.FirstOrDefault(ta => ta.MethodName == nameof(Thread.Sleep))?.Elapsed)); }
/// <summary> /// Private constructor for <see cref="PerformanceInfoStep{TClass}"/>. /// </summary> private PerformanceInfoStep(PerformanceMeter<TClass> performanceMeter, string stepName, double minSaveMs = -1) { this._performanceMeter = performanceMeter; this._stepName = stepName; this._minSaveMs = minSaveMs; this._innerStopwatch.Start(); this._dateStart = DateTime.UtcNow - this._innerStopwatch.Elapsed; }
/// <summary> /// Executes the Unchase.FluentPerformanceMeter-wrapped middleware. /// </summary> /// <param name="context">The <see cref="HttpContext"/> for the current request.</param> /// <returns>A task that represents the execution of the MiniProfiler-wrapped middleware.</returns> /// <exception cref="ArgumentNullException">Throws when <paramref name="context"/> is <c>null</c>.</exception> public async Task Invoke(HttpContext context) { _ = context ?? throw new ArgumentNullException(nameof(context)); if (PerformanceMeterCommonMethods.ShouldWatching(context.Request, Options)) { var controllerActionDescriptor = (context.Features[typeof(IEndpointFeature)] as IEndpointFeature)?.Endpoint?.Metadata?.GetMetadata <ControllerActionDescriptor>(); if (controllerActionDescriptor != null) { if (PerformanceMeterCommonMethods.CheckExcludedMethods(controllerActionDescriptor, Options)) { await _next(context); // don't watching, only relay } if (PerformanceMeterCommonMethods.CheckAnnotatedAttribute(controllerActionDescriptor, Options, typeof(WatchingPerformanceAttribute))) { await _next(context); // don't watching, only relay } if (PerformanceMeterCommonMethods.CheckIgnoreMethodPerformanceAttribute(controllerActionDescriptor, Options)) { await _next(context); // don't watching, only relay } if (controllerActionDescriptor.ControllerTypeInfo.UnderlyingSystemType != typeof(TClass)) { await _next(context); // don't watching, only relay } var performanceMeterBuilder = PerformanceMeter <TClass> .WatchingMethod(controllerActionDescriptor.ActionName) .WithSettingData; // add custom data from custom attributes performanceMeterBuilder = performanceMeterBuilder.AddCustomDataFromCustomAttributes(context, controllerActionDescriptor, Options); using (performanceMeterBuilder.Start()) { // execute the pipe await _next(context); } } else { // don't watching, only relay await _next(context); } } else { // don't watching, only relay await _next(context); } }
public ActionResult SimpleStartWatching() { using (PerformanceMeter <PerformanceMeterController> .StartWatching()) { // put your code with some logic here return(Ok()); } }
public ActionResult PublicTestGetSimpleMethodWithActionAndIterations(uint iterations = 1) { using var pm = PerformanceMeter <PerformanceMeterController> .StartWatching(); // execute an action that throws the exception to be handled by the exception handler pm.Executing() .Start(() => Debug.WriteLine($"Iterations: {iterations}"), iterations); return(Ok()); }
public ActionResult SimpleWatchingMethodStart() { //using var pm = PerformanceMeter<PerformanceMeterController>.WatchingMethod().Start(); using (PerformanceMeter <PerformanceMeterController> .WatchingMethod().Start()) { //put your code with some logic here return(Ok()); } }
public void PerformanceMeterStartWaychingPublicVoidMethodWithHttpContectAccessorReturnsSuccess() { // Arrange PerformanceMeter <PublicClass> performanceMeter = null; // Act using (performanceMeter = PerformanceMeter <PublicClass> .WatchingMethod(nameof(PublicClass.PublicVoidMethod)) .WithSettingData .CallerFrom(_httpContextAccessor) .Start()) { // Arrange var performanceInfo = PerformanceMeter <PublicClass> .PerformanceInfo; var methodCurrentActivity = performanceInfo.CurrentActivity.Find(ca => ca.Method == performanceMeter.MethodInfo); var methodTotalActivity = performanceInfo.TotalActivity.Find(ca => ca.Method == performanceMeter.MethodInfo); var methodCalls = performanceInfo.MethodCalls.Find(ca => ca.Method == performanceMeter.MethodInfo); // Assert performanceInfo.ClassName.Should().EndWith(typeof(PublicClass).Name, "class name should be known"); performanceInfo.MethodNames.Count.Should().Be(typeof(PublicClass) .GetMethods(BindingFlags.Instance | BindingFlags.Public | BindingFlags.Static | BindingFlags.DeclaredOnly) .Where(mi => !mi.IsSpecialName && mi.GetCustomAttribute <IgnoreMethodPerformanceAttribute>() == null) .Count()); methodCurrentActivity.Should().NotBeNull(); methodCurrentActivity.CallsCount.Should().Be(1); methodTotalActivity.Should().NotBeNull(); methodTotalActivity.CallsCount.Should().Be(0); methodCalls.Should().BeNull(); } // Arrange var performanceInfoAfterDispose = PerformanceMeter <PublicClass> .PerformanceInfo; var methodCurrentActivityAfterDispose = performanceInfoAfterDispose.CurrentActivity.Find(ca => ca.Method == performanceMeter.MethodInfo); var methodTotalActivityAfterDispose = performanceInfoAfterDispose.TotalActivity.Find(ca => ca.Method == performanceMeter.MethodInfo); var methodCallsAfterDispose = performanceInfoAfterDispose.MethodCalls.Find(ca => ca.Method == performanceMeter.MethodInfo); // Assert methodCurrentActivityAfterDispose.Should().NotBeNull(); methodCurrentActivityAfterDispose.CallsCount.Should().Be(0); methodTotalActivityAfterDispose.Should().NotBeNull(); methodTotalActivityAfterDispose.CallsCount.Should().Be(1); methodCallsAfterDispose.Should().NotBeNull(); methodCallsAfterDispose.Method.Should().BeSameAs(performanceMeter.MethodInfo); methodCallsAfterDispose.MethodName.Should().Be(nameof(PublicClass.PublicVoidMethod)); methodCallsAfterDispose.Elapsed.Should().BeGreaterThan(new TimeSpan()); methodCallsAfterDispose.Caller.Should().Be(_httpContextAccessor.HttpContext.Connection.RemoteIpAddress.ToString()); }
public ActionResult PublicTestGetSimpleMethodWithActionThrowsException() { using var pm = PerformanceMeter <PerformanceMeterController> .StartWatching(); // execute an action that throws the exception to be handled by the exception handler pm.Executing() .WithExceptionHandler((ex) => Debug.WriteLine(ex.Message)) .Start(() => throw new Exception(PerformanceMeter <PerformanceMeterController> .Print())); return(Ok()); }
/// <summary> /// Register <see cref="PerformanceDiagnosticObserverBase"/> services. /// </summary> /// <param name="services"><see cref="IServiceCollection"/>.</param> /// <param name="configureOptions">An <see cref="Action{PerformanceMeterOptions}"/> to configure options for Unchase.FluentPerformanceMeter.</param> public static IServiceCollection AddPerformanceDiagnosticObserver <TClass>(this IServiceCollection services, Action <PerformanceMeterMvcOptions <TClass> > configureOptions = null) where TClass : ControllerBase { if (configureOptions != null) { services.Configure(configureOptions); } services.Configure <PerformanceMeterMvcOptions <TClass> >(o => PerformanceMeter <TClass> .Configure(o)); services.TryAddEnumerable( ServiceDescriptor.Transient <PerformanceDiagnosticObserverBase, PerformanceDiagnosticObserver <TClass> >()); return(services); }
public ActionResult SimpleStartWatchingWithActionThrowsCustomException() { using var pm = PerformanceMeter <PerformanceMeterController> .StartWatching(); // put your code with some logic here // execute action throws custom Exception with exception handler pm.Executing <CustomException>() .WithExceptionHandler((ex) => { Debug.WriteLine("Custom exception was occured!"); }) .Start(() => throw new CustomException("Action exception!!!")); return(Ok()); }
/// <summary> /// Static constructor. /// </summary> static PerformanceMeterController() { // set cache time for PerformanceMeterController class PerformanceMeter <PerformanceMeterController> .SetMethodCallsCacheTime(5); // add common custom data (string) to class performance information PerformanceMeter <PerformanceMeterController> .AddCustomData("Tag", "CustomTag"); // add common custom data (anonymous class) to class performance information PerformanceMeter <PerformanceMeterController> .AddCustomData("Custom anonymous class", new { Name = "Custom Name", Value = 1 }); // set default exception handler for PerformanceMeterController class PerformanceMeter <PerformanceMeterController> .SetDefaultExceptionHandler((ex) => Debug.WriteLine(ex.Message)); }
public ActionResult <string> StartWatchingWithCallerName([FromBody] string value) { // the method’s performance info will be amended with the caller's name (if internal HttpContextAccessor is null) using var pm = PerformanceMeter <PerformanceMeterController> .WatchingMethod() .WithSettingData .CallerSourceData() .CallerFrom("Test caller") .Start(); pm.StopWatching(); // stop watching here (or you can use "pm.Dispose();") Thread.Sleep(2000); return(Ok(value)); }
public ActionResult <string> WatchingMethodUsingDI(uint value) { // method performance info will reach with HttpContextAccessor (required for DI) using (PerformanceMeter <PerformanceMeterController> .WatchingMethod(nameof(WatchingMethodUsingDI)) .WithSettingData .CallerFrom(_httpContextAccessor) .Start()) { // adds step to PerformanceMeter using DI AddStepWithDI(); return(Ok($"{value}")); } }
public ActionResult SimpleStartWatchingWithThrowsExceptions() { using var pm = PerformanceMeter <PerformanceMeterController> .StartWatching(); // execute an action that throws the exception to be handled by the exception handler pm.Executing() .WithExceptionHandler((ex) => Debug.WriteLine(ex.Message)) .Start(() => throw new Exception("Exception")); // execute action throws custom Exception with exception handler pm.Executing <CustomException>() .WithExceptionHandler((ex) => { Debug.WriteLine(ex.Message); }) .Start(() => throw new CustomException("Custom exception was occured!")); return(Ok()); }
public ActionResult WatchingMethodWithExecutedCommand() { // custom "ExecutedCommand" will be executed after performance watching is completed using (PerformanceMeter <PerformanceMeterController> .WatchingMethod() .WithExecutingOnComplete .Command(new ExecutedCommand("bla-bla-bla")) .Action((pi) => { Debug.WriteLine($"Class name: {pi.ClassName}"); }) .Start()) { return(Ok()); } }
/// <summary> /// Constructor for <see cref="SettingsBuilder{TClass}"/>. /// </summary> /// <param name="performanceMeter"><see cref="PerformanceMeter{TClass}"/>.</param> public SettingsBuilder(PerformanceMeter <TClass> performanceMeter) { this.PerformanceMeter = performanceMeter; foreach (var performanceCustomDataAttribute in performanceMeter.MethodInfo.GetCustomAttributes(typeof(MethodCustomDataAttribute), false)) { if (performanceCustomDataAttribute is MethodCustomDataAttribute customDataAttribute) { AddCustomData(customDataAttribute.Key, customDataAttribute.Value); } } foreach (var methodCallerAttribute in performanceMeter.MethodInfo.GetCustomAttributes(typeof(MethodCallerAttribute), false)) { if (methodCallerAttribute is MethodCallerAttribute caller) { WithCaller(caller.Caller); } } }
public ActionResult <long> WatchingMethodStartWithCorrelationIdAndFakeServiceSteps() { // generate correlationId (for example) var correlationId = Guid.NewGuid(); var parameterForMethod2 = "parameter"; // start performance watching with correlationId and caller source data using (PerformanceMeter <PerformanceMeterController> .WatchingMethod() .WithSettingData .CustomData("corellationId", correlationId) .CallerSourceData() .Start()) { // add step with calling FakeService.FakeMethod2 with custom data (corellationId) using (PerformanceMeter <FakeService> .WatchingMethod(nameof(FakeService.FakeMethod1)) .WithSettingData .CustomData("corellationId", correlationId) .CustomData("fake service method 1 step", 1) .CallerSourceData() .Start()) { FakeService.FakeMethod1(); } // add step with calling FakeService.FakeMethod2 with custom data (corellationId and perameter for FakeMethod2) using (PerformanceMeter <FakeService> .WatchingMethod(nameof(FakeService.FakeMethod2)) .WithSettingData .CustomData("corellationId", correlationId) .CustomData("fake service method 2 step", 2) .CustomData("method parameter", parameterForMethod2) .CallerSourceData() .Start()) { FakeService.FakeMethod2(parameterForMethod2); } } return(Ok(PerformanceMeter <FakeService> .PerformanceInfo.MethodCalls.Where(mc => mc.MethodName.StartsWith("Fake")).Sum(mc => mc.Elapsed.TotalMilliseconds))); }
public void OnBeforeAction(HttpContext httpContext, ActionDescriptor actionDescriptor) { var controllerActionDescriptor = (ControllerActionDescriptor)actionDescriptor; if (!controllerActionDescriptor.MethodInfo.GetCustomAttributes(typeof(WatchingWithDiagnosticSourceAttribute), false).Any() && !controllerActionDescriptor.ControllerTypeInfo.GetCustomAttributes(typeof(WatchingWithDiagnosticSourceAttribute), false).Any()) { return; } if (controllerActionDescriptor.MethodInfo.GetCustomAttributes(typeof(IgnoreMethodPerformanceAttribute), false).Any()) { return; } var performanceMeterBuilder = PerformanceMeter <TClass> .WatchingMethod(controllerActionDescriptor.ActionName) .WithSettingData; // add custom data from attributes foreach (MethodCustomDataAttribute methodCustomData in controllerActionDescriptor.MethodInfo.GetCustomAttributes(typeof(MethodCustomDataAttribute), false)) { performanceMeterBuilder = performanceMeterBuilder.CustomData(methodCustomData.Key, methodCustomData.Value); } if (httpContext.Request.QueryString.HasValue) { performanceMeterBuilder = performanceMeterBuilder.CustomData("queryString", httpContext.Request.QueryString.Value); } if (httpContext.User.Identity.IsAuthenticated) { performanceMeterBuilder = performanceMeterBuilder.CustomData("userIdentityName", httpContext.User.Identity.Name); } // add caller from attributes performanceMeterBuilder = performanceMeterBuilder.CallerFrom(httpContext.Connection?.RemoteIpAddress?.ToString() ?? httpContext.Connection?.LocalIpAddress?.ToString()); foreach (MethodCallerAttribute methodCaller in controllerActionDescriptor.MethodInfo.GetCustomAttributes(typeof(MethodCallerAttribute), false)) { performanceMeterBuilder = performanceMeterBuilder.CallerFrom(methodCaller.Caller); } httpContext.Items["PerformanceMeter"] = performanceMeterBuilder.Start(); }
public ActionResult <string> SimpleStartWatchingWithoutWatching() { //using var pm = PerformanceMeter<PerformanceMeterController>.StartWatching(); using (var pm = PerformanceMeter <PerformanceMeterController> .StartWatching()) { // put your code with some logic here // sleep 1 sec Thread.Sleep(1000); // execute action without watching pm.Executing() .WithoutWatching() .Start(() => Thread.Sleep(2000)); // execute action with sleeping 500 ms pm.Inline(() => { Thread.Sleep(500); Debug.WriteLine("Sleep 500 ms"); }); // execute action without watching pm.InlineIgnored(() => { Thread.Sleep(100); Debug.WriteLine("Sleep 1000 ms"); }); // execute Func<string> returns string var result = pm.Executing() .Start(() => { Thread.Sleep(2000); return("1"); }); return(Ok(result)); } }
public void SaveGame() { var turn = CurrentGame.Game.CurrentTurn; Log.Debug($"Saving started on turn {turn}"); SaveData gameData; SaveData dataData; using (PerformanceMeter.Start($"Saving_GetSaveData[{turn}]")) { var gameDataBuilder = CurrentGame.Game.GetSaveData(); gameData = gameDataBuilder.ConvertRawData(new JsonDataSerializer()); var dataDataBuilder = GameData.Current.GetSaveData(); dataData = dataDataBuilder.ConvertRawData(new JsonDataSerializer()); } var gameSaveData = new GameSaveData { Version = GetGameVersion(), Game = gameData, Data = dataData }; string json; using (PerformanceMeter.Start($"Saving_Serialization[{turn}]")) { json = JsonConvert.SerializeObject(gameSaveData); } using (PerformanceMeter.Start($"Saving_Writing[{turn}]")) { WriteSaveFile(json); } Log.Debug("Saving finished"); }
/// <summary> /// Register Unchase.FluentPerformanceMeter services. /// </summary> /// <param name="services"><see cref="IServiceCollection"/>.</param> /// <param name="configureOptions">An <see cref="Action{PerformanceMeterMvcOptions}"/> to configure options for Unchase.FluentPerformanceMeter.</param> public static IServiceCollection AddPerformanceMeter <TClass>(this IServiceCollection services, Action <PerformanceMeterMvcOptions <TClass> > configureOptions = null) where TClass : ControllerBase { // ensure that IHttpContextAccessor was added services.AddHttpContextAccessor(); if (configureOptions != null) { services.Configure(configureOptions); } services.Configure <PerformanceMeterMvcOptions <TClass> >(o => { PerformanceMeter <TClass> .Configure(o); }); services.AddScoped(typeof(PerformanceMeter <TClass>), serviceProvider => { var httpContext = serviceProvider.GetRequiredService <IHttpContextAccessor>()?.HttpContext; return(httpContext?.Items[$"PerformanceMeter{httpContext.TraceIdentifier}"]); }); return(services); }