Created
February 25, 2014 00:09
-
-
Save brunomlopes/9200010 to your computer and use it in GitHub Desktop.
Very simple Metrics.Net integration with ServiceStack
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Diagnostics; | |
using System.Web; | |
using metrics; | |
using metrics.Core; | |
using ServiceStack; | |
[Route("/admin/metrics/all")] | |
class GetAllMetrics { } | |
class MetricsService : IService | |
{ | |
public object Get(GetAllMetrics request) | |
{ | |
return metrics.Metrics.All; | |
} | |
} | |
public class MetricsFeature : IPlugin | |
{ | |
private MeterMetric _requestsMeter = Metrics.Meter(typeof (MetricsFeature), "ServicestackRequests", "requests", | |
TimeUnit.Seconds); | |
private TimerMetric _requestsTimer = Metrics.Timer(typeof (MetricsFeature), "ServicestackRequestsDuration", TimeUnit.Seconds, | |
TimeUnit.Seconds); | |
private MeterMetric _errorsMeter = Metrics.Meter(typeof (MetricsFeature), "ServiceStackErrors", "errors", | |
TimeUnit.Seconds); | |
private class RequestTimer : IDisposable | |
{ | |
private readonly Stopwatch _stopwatch; | |
private readonly TimerMetric _metric; | |
private RequestTimer(Stopwatch stopwatch, TimerMetric metric) | |
{ | |
_stopwatch = stopwatch; | |
_metric = metric; | |
_stopwatch.Start(); | |
} | |
public static RequestTimer Start(TimerMetric metric) | |
{ | |
return new RequestTimer(new Stopwatch(), metric); | |
} | |
public void Dispose() | |
{ | |
_stopwatch.Stop(); | |
_metric.Update(_stopwatch.ElapsedTicks * 1000000000L / Stopwatch.Frequency, TimeUnit.Nanoseconds); | |
} | |
} | |
public void Register(IAppHost appHost) | |
{ | |
appHost.RegisterService<MetricsService>(); | |
appHost.PreRequestFilters.Insert(0, (request, response) => | |
{ | |
_requestsMeter.Mark(); | |
((HttpRequestBase)request.OriginalRequest).RequestContext.HttpContext.Items.Add("_metrics_timer", RequestTimer.Start(_requestsTimer)); | |
}); | |
appHost.ServiceExceptionHandlers.Add((req, request, exception) => | |
{ | |
_errorsMeter.Mark(); | |
return null; | |
}); | |
appHost.UncaughtExceptionHandlers.Add((req, res, name, exception) => _errorsMeter.Mark()); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment