├── .dockerignore ├── .github └── workflows │ └── dotnetcore.yml ├── .gitignore ├── Metrics.sln ├── README.md ├── build.sh ├── kubernetes ├── prometheus-deployment.yml └── webapp-deployment.yml ├── run.sh ├── samples └── SampleWebApplication │ ├── Dockerfile │ ├── Program.cs │ ├── Properties │ └── launchSettings.json │ ├── SampleWebApplication.csproj │ ├── Startup.cs │ ├── appsettings.Development.json │ └── appsettings.json └── src └── Microsoft.Extensions.Metrics ├── CounterPayload ├── CounterPayload.cs ├── ICounterPayload.cs └── IncrementingCounterPayload.cs ├── Extensions ├── IEndpointRouteBuilderExtensions.cs └── IServiceCollectionExtensions.cs ├── IMetricsData.cs ├── Listener.cs ├── MetricsData.cs ├── MetricsService.cs ├── MetricsServiceOptions.cs ├── MetricsServiceOptionsSetup.cs └── Microsoft.Extensions.Metrics.csproj /.dockerignore: -------------------------------------------------------------------------------- 1 | **/.dockerignore 2 | **/.env 3 | **/.git 4 | **/.gitignore 5 | **/.vs 6 | **/.vscode 7 | **/*.*proj.user 8 | **/azds.yaml 9 | **/charts 10 | **/bin 11 | **/obj 12 | **/Dockerfile 13 | **/Dockerfile.develop 14 | **/docker-compose.yml 15 | **/docker-compose.*.yml 16 | **/*.dbmdl 17 | **/*.jfm 18 | **/secrets.dev.yaml 19 | **/values.dev.yaml 20 | **/.toolstarget -------------------------------------------------------------------------------- /.github/workflows/dotnetcore.yml: -------------------------------------------------------------------------------- 1 | name: .NET Core 2 | 3 | on: [push] 4 | 5 | jobs: 6 | build: 7 | 8 | runs-on: ubuntu-latest 9 | 10 | steps: 11 | - name: Generate build number 12 | uses: einaregilsson/build-number@v1 13 | with: 14 | token: ${{secrets.github_token}} 15 | - uses: actions/checkout@v1 16 | - name: Setup .NET Core 17 | uses: actions/setup-dotnet@v1 18 | with: 19 | dotnet-version: 3.0.100 20 | - name: Build with dotnet 21 | run: dotnet pack --configuration Release src/Microsoft.Extensions.Metrics /p:VersionSuffix=$BUILD_NUMBER 22 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | ## Ignore Visual Studio temporary files, build results, and 2 | ## files generated by popular Visual Studio add-ons. 3 | ## 4 | ## Get latest from https://github.com/github/gitignore/blob/master/VisualStudio.gitignore 5 | 6 | # User-specific files 7 | *.rsuser 8 | *.suo 9 | *.user 10 | *.userosscache 11 | *.sln.docstates 12 | 13 | # User-specific files (MonoDevelop/Xamarin Studio) 14 | *.userprefs 15 | 16 | # Mono auto generated files 17 | mono_crash.* 18 | 19 | # Build results 20 | [Dd]ebug/ 21 | [Dd]ebugPublic/ 22 | [Rr]elease/ 23 | [Rr]eleases/ 24 | x64/ 25 | x86/ 26 | [Aa][Rr][Mm]/ 27 | [Aa][Rr][Mm]64/ 28 | bld/ 29 | [Bb]in/ 30 | [Oo]bj/ 31 | [Ll]og/ 32 | 33 | # Visual Studio 2015/2017 cache/options directory 34 | .vs/ 35 | # Uncomment if you have tasks that create the project's static files in wwwroot 36 | #wwwroot/ 37 | 38 | # Visual Studio 2017 auto generated files 39 | Generated\ Files/ 40 | 41 | # MSTest test Results 42 | [Tt]est[Rr]esult*/ 43 | [Bb]uild[Ll]og.* 44 | 45 | # NUnit 46 | *.VisualState.xml 47 | TestResult.xml 48 | nunit-*.xml 49 | 50 | # Build Results of an ATL Project 51 | [Dd]ebugPS/ 52 | [Rr]eleasePS/ 53 | dlldata.c 54 | 55 | # Benchmark Results 56 | BenchmarkDotNet.Artifacts/ 57 | 58 | # .NET Core 59 | project.lock.json 60 | project.fragment.lock.json 61 | artifacts/ 62 | 63 | # StyleCop 64 | StyleCopReport.xml 65 | 66 | # Files built by Visual Studio 67 | *_i.c 68 | *_p.c 69 | *_h.h 70 | *.ilk 71 | *.meta 72 | *.obj 73 | *.iobj 74 | *.pch 75 | *.pdb 76 | *.ipdb 77 | *.pgc 78 | *.pgd 79 | *.rsp 80 | *.sbr 81 | *.tlb 82 | *.tli 83 | *.tlh 84 | *.tmp 85 | *.tmp_proj 86 | *_wpftmp.csproj 87 | *.log 88 | *.vspscc 89 | *.vssscc 90 | .builds 91 | *.pidb 92 | *.svclog 93 | *.scc 94 | 95 | # Chutzpah Test files 96 | _Chutzpah* 97 | 98 | # Visual C++ cache files 99 | ipch/ 100 | *.aps 101 | *.ncb 102 | *.opendb 103 | *.opensdf 104 | *.sdf 105 | *.cachefile 106 | *.VC.db 107 | *.VC.VC.opendb 108 | 109 | # Visual Studio profiler 110 | *.psess 111 | *.vsp 112 | *.vspx 113 | *.sap 114 | 115 | # Visual Studio Trace Files 116 | *.e2e 117 | 118 | # TFS 2012 Local Workspace 119 | $tf/ 120 | 121 | # Guidance Automation Toolkit 122 | *.gpState 123 | 124 | # ReSharper is a .NET coding add-in 125 | _ReSharper*/ 126 | *.[Rr]e[Ss]harper 127 | *.DotSettings.user 128 | 129 | # JustCode is a .NET coding add-in 130 | .JustCode 131 | 132 | # TeamCity is a build add-in 133 | _TeamCity* 134 | 135 | # DotCover is a Code Coverage Tool 136 | *.dotCover 137 | 138 | # AxoCover is a Code Coverage Tool 139 | .axoCover/* 140 | !.axoCover/settings.json 141 | 142 | # Visual Studio code coverage results 143 | *.coverage 144 | *.coveragexml 145 | 146 | # NCrunch 147 | _NCrunch_* 148 | .*crunch*.local.xml 149 | nCrunchTemp_* 150 | 151 | # MightyMoose 152 | *.mm.* 153 | AutoTest.Net/ 154 | 155 | # Web workbench (sass) 156 | .sass-cache/ 157 | 158 | # Installshield output folder 159 | [Ee]xpress/ 160 | 161 | # DocProject is a documentation generator add-in 162 | DocProject/buildhelp/ 163 | DocProject/Help/*.HxT 164 | DocProject/Help/*.HxC 165 | DocProject/Help/*.hhc 166 | DocProject/Help/*.hhk 167 | DocProject/Help/*.hhp 168 | DocProject/Help/Html2 169 | DocProject/Help/html 170 | 171 | # Click-Once directory 172 | publish/ 173 | 174 | # Publish Web Output 175 | *.[Pp]ublish.xml 176 | *.azurePubxml 177 | # Note: Comment the next line if you want to checkin your web deploy settings, 178 | # but database connection strings (with potential passwords) will be unencrypted 179 | *.pubxml 180 | *.publishproj 181 | 182 | # Microsoft Azure Web App publish settings. Comment the next line if you want to 183 | # checkin your Azure Web App publish settings, but sensitive information contained 184 | # in these scripts will be unencrypted 185 | PublishScripts/ 186 | 187 | # NuGet Packages 188 | *.nupkg 189 | # NuGet Symbol Packages 190 | *.snupkg 191 | # The packages folder can be ignored because of Package Restore 192 | **/[Pp]ackages/* 193 | # except build/, which is used as an MSBuild target. 194 | !**/[Pp]ackages/build/ 195 | # Uncomment if necessary however generally it will be regenerated when needed 196 | #!**/[Pp]ackages/repositories.config 197 | # NuGet v3's project.json files produces more ignorable files 198 | *.nuget.props 199 | *.nuget.targets 200 | 201 | # Microsoft Azure Build Output 202 | csx/ 203 | *.build.csdef 204 | 205 | # Microsoft Azure Emulator 206 | ecf/ 207 | rcf/ 208 | 209 | # Windows Store app package directories and files 210 | AppPackages/ 211 | BundleArtifacts/ 212 | Package.StoreAssociation.xml 213 | _pkginfo.txt 214 | *.appx 215 | *.appxbundle 216 | *.appxupload 217 | 218 | # Visual Studio cache files 219 | # files ending in .cache can be ignored 220 | *.[Cc]ache 221 | # but keep track of directories ending in .cache 222 | !?*.[Cc]ache/ 223 | 224 | # Others 225 | ClientBin/ 226 | ~$* 227 | *~ 228 | *.dbmdl 229 | *.dbproj.schemaview 230 | *.jfm 231 | *.pfx 232 | *.publishsettings 233 | orleans.codegen.cs 234 | 235 | # Including strong name files can present a security risk 236 | # (https://github.com/github/gitignore/pull/2483#issue-259490424) 237 | #*.snk 238 | 239 | # Since there are multiple workflows, uncomment next line to ignore bower_components 240 | # (https://github.com/github/gitignore/pull/1529#issuecomment-104372622) 241 | #bower_components/ 242 | 243 | # RIA/Silverlight projects 244 | Generated_Code/ 245 | 246 | # Backup & report files from converting an old project file 247 | # to a newer Visual Studio version. Backup files are not needed, 248 | # because we have git ;-) 249 | _UpgradeReport_Files/ 250 | Backup*/ 251 | UpgradeLog*.XML 252 | UpgradeLog*.htm 253 | ServiceFabricBackup/ 254 | *.rptproj.bak 255 | 256 | # SQL Server files 257 | *.mdf 258 | *.ldf 259 | *.ndf 260 | 261 | # Business Intelligence projects 262 | *.rdl.data 263 | *.bim.layout 264 | *.bim_*.settings 265 | *.rptproj.rsuser 266 | *- [Bb]ackup.rdl 267 | *- [Bb]ackup ([0-9]).rdl 268 | *- [Bb]ackup ([0-9][0-9]).rdl 269 | 270 | # Microsoft Fakes 271 | FakesAssemblies/ 272 | 273 | # GhostDoc plugin setting file 274 | *.GhostDoc.xml 275 | 276 | # Node.js Tools for Visual Studio 277 | .ntvs_analysis.dat 278 | node_modules/ 279 | 280 | # Visual Studio 6 build log 281 | *.plg 282 | 283 | # Visual Studio 6 workspace options file 284 | *.opt 285 | 286 | # Visual Studio 6 auto-generated workspace file (contains which files were open etc.) 287 | *.vbw 288 | 289 | # Visual Studio LightSwitch build output 290 | **/*.HTMLClient/GeneratedArtifacts 291 | **/*.DesktopClient/GeneratedArtifacts 292 | **/*.DesktopClient/ModelManifest.xml 293 | **/*.Server/GeneratedArtifacts 294 | **/*.Server/ModelManifest.xml 295 | _Pvt_Extensions 296 | 297 | # Paket dependency manager 298 | .paket/paket.exe 299 | paket-files/ 300 | 301 | # FAKE - F# Make 302 | .fake/ 303 | 304 | # CodeRush personal settings 305 | .cr/personal 306 | 307 | # Python Tools for Visual Studio (PTVS) 308 | __pycache__/ 309 | *.pyc 310 | 311 | # Cake - Uncomment if you are using it 312 | # tools/** 313 | # !tools/packages.config 314 | 315 | # Tabs Studio 316 | *.tss 317 | 318 | # Telerik's JustMock configuration file 319 | *.jmconfig 320 | 321 | # BizTalk build output 322 | *.btp.cs 323 | *.btm.cs 324 | *.odx.cs 325 | *.xsd.cs 326 | 327 | # OpenCover UI analysis results 328 | OpenCover/ 329 | 330 | # Azure Stream Analytics local run output 331 | ASALocalRun/ 332 | 333 | # MSBuild Binary and Structured Log 334 | *.binlog 335 | 336 | # NVidia Nsight GPU debugger configuration file 337 | *.nvuser 338 | 339 | # MFractors (Xamarin productivity tool) working folder 340 | .mfractor/ 341 | 342 | # Local History for Visual Studio 343 | .localhistory/ 344 | 345 | # BeatPulse healthcheck temp database 346 | healthchecksdb 347 | 348 | # Backup folder for Package Reference Convert tool in Visual Studio 2017 349 | MigrationBackup/ 350 | -------------------------------------------------------------------------------- /Metrics.sln: -------------------------------------------------------------------------------- 1 |  2 | Microsoft Visual Studio Solution File, Format Version 12.00 3 | # Visual Studio 15 4 | VisualStudioVersion = 15.0.26124.0 5 | MinimumVisualStudioVersion = 15.0.26124.0 6 | Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "src", "src", "{ABD33285-4E69-420E-AA5E-5F16D4FF274E}" 7 | EndProject 8 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Microsoft.Extensions.Metrics", "src\Microsoft.Extensions.Metrics\Microsoft.Extensions.Metrics.csproj", "{2B152693-A87E-4E48-893C-004EAC09E01B}" 9 | EndProject 10 | Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "samples", "samples", "{CCC23534-0D14-41CB-B61A-FE3FE3AC0431}" 11 | EndProject 12 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "SampleWebApplication", "samples\SampleWebApplication\SampleWebApplication.csproj", "{F2AF505C-08A0-4A93-A5F7-8670482E1103}" 13 | EndProject 14 | Global 15 | GlobalSection(SolutionConfigurationPlatforms) = preSolution 16 | Debug|Any CPU = Debug|Any CPU 17 | Debug|x64 = Debug|x64 18 | Debug|x86 = Debug|x86 19 | Release|Any CPU = Release|Any CPU 20 | Release|x64 = Release|x64 21 | Release|x86 = Release|x86 22 | EndGlobalSection 23 | GlobalSection(SolutionProperties) = preSolution 24 | HideSolutionNode = FALSE 25 | EndGlobalSection 26 | GlobalSection(ProjectConfigurationPlatforms) = postSolution 27 | {2B152693-A87E-4E48-893C-004EAC09E01B}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 28 | {2B152693-A87E-4E48-893C-004EAC09E01B}.Debug|Any CPU.Build.0 = Debug|Any CPU 29 | {2B152693-A87E-4E48-893C-004EAC09E01B}.Debug|x64.ActiveCfg = Debug|Any CPU 30 | {2B152693-A87E-4E48-893C-004EAC09E01B}.Debug|x64.Build.0 = Debug|Any CPU 31 | {2B152693-A87E-4E48-893C-004EAC09E01B}.Debug|x86.ActiveCfg = Debug|Any CPU 32 | {2B152693-A87E-4E48-893C-004EAC09E01B}.Debug|x86.Build.0 = Debug|Any CPU 33 | {2B152693-A87E-4E48-893C-004EAC09E01B}.Release|Any CPU.ActiveCfg = Release|Any CPU 34 | {2B152693-A87E-4E48-893C-004EAC09E01B}.Release|Any CPU.Build.0 = Release|Any CPU 35 | {2B152693-A87E-4E48-893C-004EAC09E01B}.Release|x64.ActiveCfg = Release|Any CPU 36 | {2B152693-A87E-4E48-893C-004EAC09E01B}.Release|x64.Build.0 = Release|Any CPU 37 | {2B152693-A87E-4E48-893C-004EAC09E01B}.Release|x86.ActiveCfg = Release|Any CPU 38 | {2B152693-A87E-4E48-893C-004EAC09E01B}.Release|x86.Build.0 = Release|Any CPU 39 | {F2AF505C-08A0-4A93-A5F7-8670482E1103}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 40 | {F2AF505C-08A0-4A93-A5F7-8670482E1103}.Debug|Any CPU.Build.0 = Debug|Any CPU 41 | {F2AF505C-08A0-4A93-A5F7-8670482E1103}.Debug|x64.ActiveCfg = Debug|Any CPU 42 | {F2AF505C-08A0-4A93-A5F7-8670482E1103}.Debug|x64.Build.0 = Debug|Any CPU 43 | {F2AF505C-08A0-4A93-A5F7-8670482E1103}.Debug|x86.ActiveCfg = Debug|Any CPU 44 | {F2AF505C-08A0-4A93-A5F7-8670482E1103}.Debug|x86.Build.0 = Debug|Any CPU 45 | {F2AF505C-08A0-4A93-A5F7-8670482E1103}.Release|Any CPU.ActiveCfg = Release|Any CPU 46 | {F2AF505C-08A0-4A93-A5F7-8670482E1103}.Release|Any CPU.Build.0 = Release|Any CPU 47 | {F2AF505C-08A0-4A93-A5F7-8670482E1103}.Release|x64.ActiveCfg = Release|Any CPU 48 | {F2AF505C-08A0-4A93-A5F7-8670482E1103}.Release|x64.Build.0 = Release|Any CPU 49 | {F2AF505C-08A0-4A93-A5F7-8670482E1103}.Release|x86.ActiveCfg = Release|Any CPU 50 | {F2AF505C-08A0-4A93-A5F7-8670482E1103}.Release|x86.Build.0 = Release|Any CPU 51 | EndGlobalSection 52 | GlobalSection(NestedProjects) = preSolution 53 | {2B152693-A87E-4E48-893C-004EAC09E01B} = {ABD33285-4E69-420E-AA5E-5F16D4FF274E} 54 | {F2AF505C-08A0-4A93-A5F7-8670482E1103} = {CCC23534-0D14-41CB-B61A-FE3FE3AC0431} 55 | EndGlobalSection 56 | EndGlobal 57 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Metrics 2 | 3 | Prometheus integration for ASP.NET Core 4 | 5 | Run `./build.sh` to build a container image locally that exposes a metrics endpoint 6 | 7 | Run `./run.sh` to create a k8s service to run prometheus and your web server 8 | 9 | The web application is accessible at http://localhost:5000 10 | 11 | The prometheus instance is accessible at http://localhost:8080 12 | 13 | Screen Shot 2019-07-12 at 4 28 28 PM 14 | -------------------------------------------------------------------------------- /build.sh: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | 3 | docker build -t aspnetmonitoring -f samples/SampleWebApplication/Dockerfile . -------------------------------------------------------------------------------- /kubernetes/prometheus-deployment.yml: -------------------------------------------------------------------------------- 1 | apiVersion: v1 2 | kind: ConfigMap 3 | metadata: 4 | name: prometheus-server-conf 5 | labels: 6 | name: prometheus-server-conf 7 | data: 8 | prometheus.yml: |- 9 | global: 10 | scrape_interval: 5s 11 | evaluation_interval: 5s 12 | 13 | scrape_configs: 14 | - job_name: 'kubernetes-service-endpoints' 15 | kubernetes_sd_configs: 16 | - role: endpoints 17 | relabel_configs: 18 | - source_labels: [__meta_kubernetes_service_annotation_prometheus_io_scrape] 19 | action: keep 20 | regex: true 21 | - source_labels: [__meta_kubernetes_service_annotation_prometheus_io_path] 22 | action: replace 23 | target_label: __metrics_path__ 24 | regex: (.+) 25 | - source_labels: [__address__, __meta_kubernetes_service_annotation_prometheus_io_port] 26 | action: replace 27 | target_label: __address__ 28 | regex: ([^:]+)(?::\d+)?;(\d+) 29 | replacement: $1:$2 30 | - action: labelmap 31 | regex: __meta_kubernetes_service_label_(.+) 32 | - source_labels: [__meta_kubernetes_namespace] 33 | action: replace 34 | target_label: kubernetes_namespace 35 | - source_labels: [__meta_kubernetes_service_name] 36 | action: replace 37 | target_label: kubernetes_name 38 | --- 39 | apiVersion: extensions/v1beta1 40 | kind: Deployment 41 | metadata: 42 | name: prometheus-deployment 43 | spec: 44 | replicas: 1 45 | template: 46 | metadata: 47 | labels: 48 | app: prometheus-server 49 | spec: 50 | containers: 51 | - name: prometheus 52 | image: prom/prometheus:v2.11.1 53 | args: 54 | - "--config.file=/etc/prometheus/prometheus.yml" 55 | - "--storage.tsdb.path=/data/" 56 | ports: 57 | - containerPort: 9090 58 | volumeMounts: 59 | - name: prometheus-config-volume 60 | mountPath: /etc/prometheus/ 61 | - name: prometheus-storage-volume 62 | mountPath: /data/ 63 | volumes: 64 | - name: prometheus-config-volume 65 | configMap: 66 | defaultMode: 420 67 | name: prometheus-server-conf 68 | 69 | - name: prometheus-storage-volume 70 | emptyDir: {} 71 | --- 72 | apiVersion: v1 73 | kind: Service 74 | metadata: 75 | name: prometheus-service 76 | annotations: 77 | prometheus.io/scrape: 'true' 78 | prometheus.io/port: '9090' 79 | 80 | spec: 81 | selector: 82 | app: prometheus-server 83 | type: LoadBalancer 84 | ports: 85 | - port: 8080 86 | targetPort: 9090 -------------------------------------------------------------------------------- /kubernetes/webapp-deployment.yml: -------------------------------------------------------------------------------- 1 | apiVersion: apps/v1 2 | kind: Deployment 3 | metadata: 4 | name: webapp-server 5 | spec: 6 | replicas: 3 7 | selector: 8 | matchLabels: 9 | app: webapp-server 10 | template: 11 | metadata: 12 | labels: 13 | app: webapp-server 14 | spec: 15 | containers: 16 | - name: webapp 17 | image: aspnetmonitoring 18 | imagePullPolicy: IfNotPresent 19 | resources: 20 | limits: 21 | cpu: 250m 22 | memory: 256Mi 23 | --- 24 | apiVersion: v1 25 | kind: Service 26 | metadata: 27 | name: webapp-server 28 | annotations: 29 | prometheus.io/scrape: 'true' 30 | prometheus.io/port: '80' 31 | spec: 32 | type: LoadBalancer 33 | ports: 34 | - port: 5000 35 | targetPort: 80 36 | selector: 37 | app: webapp-server -------------------------------------------------------------------------------- /run.sh: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | 3 | kubectl apply -f kubernetes/prometheus-deployment.yml 4 | kubectl apply -f kubernetes/webapp-deployment.yml 5 | -------------------------------------------------------------------------------- /samples/SampleWebApplication/Dockerfile: -------------------------------------------------------------------------------- 1 | FROM mcr.microsoft.com/dotnet/core/aspnet:3.0 AS base 2 | WORKDIR /app 3 | EXPOSE 80 4 | EXPOSE 443 5 | 6 | FROM mcr.microsoft.com/dotnet/core/sdk:3.0 AS build 7 | WORKDIR /src 8 | COPY ["samples/SampleWebApplication/SampleWebApplication.csproj", "samples/SampleWebApplication/"] 9 | COPY ["src/Microsoft.Extensions.Metrics/Microsoft.Extensions.Metrics.csproj", "src/Microsoft.Extensions.Metrics/"] 10 | RUN dotnet restore "samples/SampleWebApplication/SampleWebApplication.csproj" 11 | COPY . . 12 | WORKDIR "/src/samples/SampleWebApplication" 13 | RUN dotnet build "SampleWebApplication.csproj" -c Release -o /app 14 | 15 | FROM build AS publish 16 | RUN dotnet publish "SampleWebApplication.csproj" -c Release -o /app 17 | 18 | FROM base AS final 19 | WORKDIR /app 20 | COPY --from=publish /app . 21 | ENTRYPOINT ["dotnet", "SampleWebApplication.dll"] -------------------------------------------------------------------------------- /samples/SampleWebApplication/Program.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Threading.Tasks; 5 | using Microsoft.AspNetCore.Hosting; 6 | using Microsoft.Extensions.Configuration; 7 | using Microsoft.Extensions.Hosting; 8 | using Microsoft.Extensions.Logging; 9 | 10 | namespace SampleWebApplication 11 | { 12 | public class Program 13 | { 14 | public static void Main(string[] args) 15 | { 16 | CreateHostBuilder(args).Build().Run(); 17 | } 18 | 19 | public static IHostBuilder CreateHostBuilder(string[] args) => 20 | Host.CreateDefaultBuilder(args) 21 | .ConfigureWebHostDefaults(webBuilder => 22 | { 23 | webBuilder.UseStartup(); 24 | }); 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /samples/SampleWebApplication/Properties/launchSettings.json: -------------------------------------------------------------------------------- 1 | { 2 | "iisSettings": { 3 | "windowsAuthentication": false, 4 | "anonymousAuthentication": true, 5 | "iisExpress": { 6 | "applicationUrl": "http://localhost:28822", 7 | "sslPort": 44383 8 | } 9 | }, 10 | "profiles": { 11 | "IIS Express": { 12 | "commandName": "IISExpress", 13 | "launchBrowser": true, 14 | "environmentVariables": { 15 | "ASPNETCORE_ENVIRONMENT": "Development" 16 | } 17 | }, 18 | "SampleWebApplication": { 19 | "commandName": "Project", 20 | "launchBrowser": true, 21 | "environmentVariables": { 22 | "ASPNETCORE_ENVIRONMENT": "Development" 23 | }, 24 | "applicationUrl": "https://localhost:5001;http://localhost:5000" 25 | }, 26 | "Docker": { 27 | "commandName": "Docker", 28 | "launchBrowser": true, 29 | "launchUrl": "{Scheme}://{ServiceHost}:{ServicePort}", 30 | "environmentVariables": { 31 | "ASPNETCORE_URLS": "https://+:443;http://+:80", 32 | "ASPNETCORE_HTTPS_PORT": "44384" 33 | }, 34 | "httpPort": 28823, 35 | "useSSL": true, 36 | "sslPort": 44384 37 | } 38 | } 39 | } -------------------------------------------------------------------------------- /samples/SampleWebApplication/SampleWebApplication.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | netcoreapp3.0 13 | a3af014e-6b83-40cb-9b8f-278704d2ca21 14 | Linux 15 | ..\.. 16 | 17 | 18 | 19 | -------------------------------------------------------------------------------- /samples/SampleWebApplication/Startup.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.AspNetCore.Builder; 2 | using Microsoft.AspNetCore.Hosting; 3 | using Microsoft.AspNetCore.Http; 4 | using Microsoft.Extensions.DependencyInjection; 5 | using Microsoft.Extensions.Hosting; 6 | using System.Collections.Generic; 7 | 8 | namespace SampleWebApplication 9 | { 10 | public class Startup 11 | { 12 | // This method gets called by the runtime. Use this method to add services to the container. 13 | // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940 14 | public void ConfigureServices(IServiceCollection services) 15 | { 16 | services.AddMetrics(); 17 | } 18 | 19 | // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. 20 | public void Configure(IApplicationBuilder app, IWebHostEnvironment env) 21 | { 22 | if (env.IsDevelopment()) 23 | { 24 | app.UseDeveloperExceptionPage(); 25 | } 26 | 27 | app.UseRouting(); 28 | 29 | app.UseEndpoints(endpoints => 30 | { 31 | endpoints.MapGet("/", async context => 32 | { 33 | await context.Response.WriteAsync("Hello World!"); 34 | }); 35 | endpoints.MapMetricsEndpoint(); 36 | }); 37 | } 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /samples/SampleWebApplication/appsettings.Development.json: -------------------------------------------------------------------------------- 1 | { 2 | "Logging": { 3 | "LogLevel": { 4 | "Default": "Debug", 5 | "System": "Information", 6 | "Microsoft": "Information" 7 | } 8 | } 9 | } 10 | -------------------------------------------------------------------------------- /samples/SampleWebApplication/appsettings.json: -------------------------------------------------------------------------------- 1 | { 2 | "Logging": { 3 | "LogLevel": { 4 | "Default": "Information", 5 | "Microsoft": "Warning", 6 | "Microsoft.Hosting.Lifetime": "Information", 7 | //"Microsoft.Extensions.Metrics": "Trace" 8 | } 9 | }, 10 | "AllowedHosts": "*" 11 | } 12 | -------------------------------------------------------------------------------- /src/Microsoft.Extensions.Metrics/CounterPayload/CounterPayload.cs: -------------------------------------------------------------------------------- 1 | using System.Collections.Generic; 2 | 3 | namespace Microsoft.Extensions.Metrics 4 | { 5 | public class CounterPayload : ICounterPayload 6 | { 7 | public CounterPayload(IDictionary payloadFields) 8 | { 9 | Name = payloadFields["Name"].ToString(); 10 | Value = payloadFields["Mean"].ToString(); 11 | DisplayName = payloadFields["DisplayName"].ToString(); 12 | } 13 | 14 | public string Name { get; } 15 | public string Value { get; } 16 | public string DisplayName { get; } 17 | } 18 | } -------------------------------------------------------------------------------- /src/Microsoft.Extensions.Metrics/CounterPayload/ICounterPayload.cs: -------------------------------------------------------------------------------- 1 | namespace Microsoft.Extensions.Metrics 2 | { 3 | public interface ICounterPayload 4 | { 5 | public string Name { get;} 6 | public string Value { get;} 7 | public string DisplayName { get;} 8 | } 9 | } -------------------------------------------------------------------------------- /src/Microsoft.Extensions.Metrics/CounterPayload/IncrementingCounterPayload.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | 4 | namespace Microsoft.Extensions.Metrics 5 | { 6 | public class IncrementingCounterPayload : ICounterPayload 7 | { 8 | private readonly string _displayName; 9 | private readonly string _displayRateTimeScale; 10 | public IncrementingCounterPayload(IDictionary payloadFields) 11 | { 12 | Name = payloadFields["Name"].ToString(); 13 | Value = payloadFields["Increment"].ToString(); 14 | _displayName = payloadFields["DisplayName"].ToString(); 15 | _displayRateTimeScale = TimeSpan.Parse(payloadFields["DisplayRateTimeScale"].ToString()).ToString("%s' sec'"); 16 | } 17 | 18 | public string Name { get; } 19 | public string Value { get; } 20 | public string DisplayName { get => $"{_displayName} / {_displayRateTimeScale}"; } 21 | 22 | } 23 | } -------------------------------------------------------------------------------- /src/Microsoft.Extensions.Metrics/Extensions/IEndpointRouteBuilderExtensions.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.AspNetCore.Http; 2 | using Microsoft.AspNetCore.Routing; 3 | using Microsoft.Extensions.DependencyInjection; 4 | using Microsoft.Extensions.Metrics; 5 | using System; 6 | 7 | namespace Microsoft.AspNetCore.Builder 8 | { 9 | public static class IEndpointRouteBuilderExtensions 10 | { 11 | public static IEndpointRouteBuilder MapMetricsEndpoint(this IEndpointRouteBuilder builder) 12 | { 13 | if (builder == null) 14 | { 15 | throw new ArgumentNullException(nameof(builder)); 16 | } 17 | 18 | builder.MapGet("/metrics", async context => 19 | { 20 | var metricsService = context.RequestServices.GetRequiredService(); 21 | await context.Response.WriteAsync(metricsService.DumpToString()); 22 | }); 23 | return builder; 24 | } 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /src/Microsoft.Extensions.Metrics/Extensions/IServiceCollectionExtensions.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.Extensions.DependencyInjection; 2 | using Microsoft.Extensions.Metrics; 3 | using Microsoft.Extensions.Options; 4 | using System; 5 | 6 | namespace Microsoft.AspNetCore.Builder 7 | { 8 | public static class IServiceCollectionExtensions 9 | { 10 | /// 11 | /// Adds Metrics services to the specified . 12 | /// 13 | /// The for adding services. 14 | /// The so that additional calls can be chained. 15 | public static IServiceCollection AddMetrics(this IServiceCollection services) 16 | { 17 | services.AddRouting(); 18 | services.AddOptions(); 19 | services.AddHostedService(); 20 | services.AddSingleton(); 21 | services.AddSingleton, MetricsServiceOptionsSetup>(); 22 | return services; 23 | } 24 | 25 | /// 26 | /// Adds Metrics services to the specified . 27 | /// 28 | /// The for adding services. 29 | /// An to configure the provided . 30 | /// The so that additional calls can be chained. 31 | public static IServiceCollection AddMetrics(this IServiceCollection services, Action configureOptions) 32 | { 33 | if (services == null) 34 | { 35 | throw new ArgumentNullException(nameof(services)); 36 | } 37 | 38 | if (configureOptions == null) 39 | { 40 | throw new ArgumentNullException(nameof(configureOptions)); 41 | } 42 | 43 | return services.Configure(configureOptions).AddMetrics(); 44 | } 45 | } 46 | } 47 | -------------------------------------------------------------------------------- /src/Microsoft.Extensions.Metrics/IMetricsData.cs: -------------------------------------------------------------------------------- 1 | using System.Collections.Generic; 2 | using System.Text; 3 | 4 | namespace Microsoft.Extensions.Metrics 5 | { 6 | public interface IMetricsData 7 | { 8 | public IDictionary Metrics { get; } 9 | 10 | public string DumpToString() 11 | { 12 | var sb = new StringBuilder(); 13 | foreach (var metric in Metrics) 14 | { 15 | sb.AppendLine($"{metric.Key.Replace('-','_').Insert(0,"dotnet_")} {metric.Value}"); 16 | } 17 | return sb.ToString(); 18 | } 19 | } 20 | } -------------------------------------------------------------------------------- /src/Microsoft.Extensions.Metrics/Listener.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections; 3 | using System.Collections.Concurrent; 4 | using System.Collections.Generic; 5 | using System.Diagnostics.Tracing; 6 | using System.Globalization; 7 | using System.Linq; 8 | 9 | namespace Microsoft.Extensions.Metrics 10 | { 11 | internal class Listener : EventListener 12 | { 13 | private readonly int _refreshInterval = TimeSpan.FromSeconds(1).Seconds; 14 | private bool _initialized = false; 15 | private Dictionary _refreshIntervalDictionary; 16 | private Action> _eventWritten; 17 | private ICollection _providerNames; 18 | 19 | // Thread-safe variable to hold the list of all EventSourcesCreated. 20 | // This class may not be instantiated at the time of EventSource creation, so the list of EventSources should be stored to be enabled after initialization. 21 | private ConcurrentQueue _eventSources; 22 | 23 | public Listener(ICollection providerNames, Action> eventWritten) 24 | { 25 | _providerNames = providerNames; 26 | _eventWritten = eventWritten; 27 | _refreshIntervalDictionary = new Dictionary(); 28 | _refreshIntervalDictionary.Add("EventCounterIntervalSec", _refreshInterval.ToString(CultureInfo.InvariantCulture)); 29 | _initialized = true; 30 | foreach (var eventSource in _eventSources) 31 | { 32 | EnabledIfRequested(eventSource); 33 | } 34 | } 35 | 36 | protected override void OnEventSourceCreated(EventSource eventSource) 37 | { 38 | // Keeping track of all EventSources here, as this call may happen before initialization. 39 | lock (this) 40 | { 41 | if (_eventSources == null) 42 | { 43 | _eventSources = new ConcurrentQueue(); 44 | } 45 | 46 | _eventSources.Enqueue(eventSource); 47 | } 48 | 49 | // If initialization is already done, we can enable EventSource right away. 50 | // This will take care of all EventSources created after initialization is done. 51 | if (_initialized) 52 | { 53 | EnabledIfRequested(eventSource); 54 | } 55 | } 56 | 57 | private void EnabledIfRequested(EventSource eventSource) 58 | { 59 | if (_providerNames.Contains(eventSource.Name)) 60 | { 61 | EnableEvents(eventSource, EventLevel.Critical, EventKeywords.All, _refreshIntervalDictionary); 62 | } 63 | } 64 | 65 | protected override void OnEventWritten(EventWrittenEventArgs eventData) 66 | { 67 | if (_initialized) 68 | { 69 | var eventPayload = eventData.Payload[0] as IDictionary; 70 | if (eventPayload != null) 71 | { 72 | var eventSourceName = eventData.EventSource.Name; 73 | _eventWritten(eventSourceName, eventPayload); 74 | } 75 | } 76 | } 77 | } 78 | } 79 | -------------------------------------------------------------------------------- /src/Microsoft.Extensions.Metrics/MetricsData.cs: -------------------------------------------------------------------------------- 1 | using System.Collections.Concurrent; 2 | using System.Collections.Generic; 3 | 4 | namespace Microsoft.Extensions.Metrics 5 | { 6 | public class MetricsData : IMetricsData 7 | { 8 | public IDictionary Metrics { get; } = new ConcurrentDictionary(); 9 | } 10 | } -------------------------------------------------------------------------------- /src/Microsoft.Extensions.Metrics/MetricsService.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.Extensions.Hosting; 2 | using Microsoft.Extensions.Logging; 3 | using Microsoft.Extensions.Options; 4 | using System; 5 | using System.Threading; 6 | using System.Threading.Tasks; 7 | 8 | namespace Microsoft.Extensions.Metrics 9 | { 10 | 11 | public class MetricsService : IHostedService, IDisposable 12 | { 13 | private Listener _listener; 14 | private ILogger _logger; 15 | private MetricsServiceOptions _options; 16 | private static readonly Action _counterReceived = 17 | LoggerMessage.Define(LogLevel.Trace, 18 | new EventId(1, "CounterCallbackReceived"), 19 | "{eventSourceName}:{eventName}={Count}"); 20 | 21 | public MetricsService(IMetricsData metrics, ILoggerFactory loggerFactory, IOptions options) 22 | { 23 | if (options.Value == null) 24 | { 25 | throw new ArgumentNullException(nameof(options.Value)); 26 | } 27 | _options = options.Value; 28 | var map = metrics.Metrics; 29 | _logger = loggerFactory.CreateLogger(); 30 | _listener = new Listener(_options.ProviderNames, 31 | (eventSourceName, eventPayload) => 32 | { 33 | ICounterPayload payload; 34 | if (eventPayload.ContainsKey("CounterType")) 35 | { 36 | payload = eventPayload["CounterType"].Equals("Sum") ? (ICounterPayload)new IncrementingCounterPayload(eventPayload) : (ICounterPayload)new CounterPayload(eventPayload); 37 | } 38 | else 39 | { 40 | payload = eventPayload.Count == 6 ? (ICounterPayload)new IncrementingCounterPayload(eventPayload) : (ICounterPayload)new CounterPayload(eventPayload); 41 | } 42 | _counterReceived(_logger, eventSourceName, payload.Name, payload.Value, null); 43 | map[payload.Name] = payload.Value; 44 | }); 45 | } 46 | 47 | public void Dispose() 48 | { 49 | _listener.Dispose(); 50 | } 51 | 52 | public Task StartAsync(CancellationToken cancellationToken) => Task.CompletedTask; 53 | 54 | public Task StopAsync(CancellationToken cancellationToken) => Task.CompletedTask; 55 | } 56 | } -------------------------------------------------------------------------------- /src/Microsoft.Extensions.Metrics/MetricsServiceOptions.cs: -------------------------------------------------------------------------------- 1 | using System.Collections.Generic; 2 | 3 | namespace Microsoft.Extensions.Metrics 4 | { 5 | public class MetricsServiceOptions 6 | { 7 | public ICollection ProviderNames { get; set; } 8 | } 9 | } -------------------------------------------------------------------------------- /src/Microsoft.Extensions.Metrics/MetricsServiceOptionsSetup.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.Extensions.Metrics; 2 | using Microsoft.Extensions.Options; 3 | using Microsoft.VisualBasic; 4 | using System.Collections; 5 | using System.Collections.Generic; 6 | using System.Collections.ObjectModel; 7 | 8 | namespace Microsoft.AspNetCore.Builder 9 | { 10 | internal class MetricsServiceOptionsSetup : IConfigureOptions 11 | { 12 | private readonly static ICollection DefaultProviderNames = new List { "System.Runtime", "Microsoft.AspNetCore" }; 13 | public void Configure(MetricsServiceOptions options) 14 | { 15 | if (options.ProviderNames == null) 16 | { 17 | options.ProviderNames = new List(DefaultProviderNames); 18 | } 19 | } 20 | } 21 | } -------------------------------------------------------------------------------- /src/Microsoft.Extensions.Metrics/Microsoft.Extensions.Metrics.csproj: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | netcoreapp3.0 5 | 6 | $(RestoreSources); 7 | https://api.nuget.org/v3/index.json; 8 | https://dotnetfeed.blob.core.windows.net/aspnet-aspnetcore/index.json; 9 | https://dotnetfeed.blob.core.windows.net/aspnet-extensions/index.json; 10 | https://dotnetfeed.blob.core.windows.net/dotnet-core/index.json; 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | --------------------------------------------------------------------------------