├── .editorconfig ├── .gitattributes ├── .github └── workflows │ └── publish.yml ├── .gitignore ├── Directory.Build.props ├── Directory.Build.targets ├── Finite.Metrics.sln ├── LICENSE ├── docs ├── README.md └── TODO.md ├── src ├── Abstractions │ ├── Finite.Metrics.Abstractions.csproj │ ├── IMetric.cs │ ├── IMetricFactory.cs │ ├── IMetricProvider.cs │ ├── MetricExtensions.cs │ ├── TagValues.Properties.cs │ └── TagValues.cs ├── Configuration │ ├── Finite.Metrics.Configuration.csproj │ ├── IMetricProviderConfiguration.cs │ ├── IMetricProviderConfigurationFactory.cs │ ├── MetricProviderConfiguration.cs │ ├── MetricProviderConfigurationFactory.cs │ ├── MetricProviderConfigureOptions.cs │ ├── MetricProviderOptions.cs │ ├── MetricProviderOptionsChangeTokenSource.cs │ ├── MetricsBuilderConfigurationExtensions.cs │ └── MetricsConfiguration.cs ├── Core │ ├── Finite.Metrics.csproj │ ├── IMetricsBuilder.cs │ ├── Measure.Duration.cs │ ├── Metric.cs │ ├── MetricFactory.cs │ ├── MetricsBuilder.cs │ └── MetricsServiceCollectionExtensions.cs ├── Directory.Build.props ├── Directory.Build.targets └── Providers │ └── OpenTsdb │ ├── DefaultSystemClock.cs │ ├── Finite.Metrics.OpenTsdb.csproj │ ├── ISystemClock.cs │ ├── MetricsBuilderTsdbExtensions.cs │ ├── OpenTsdbMetricsOptions.cs │ ├── TsdbMetric.cs │ ├── TsdbMetricProvider.cs │ ├── TsdbMetricsUploader.cs │ ├── TsdbPutRequest.cs │ └── TsdbPutResponse.cs └── tests ├── Configuration ├── Finite.Metrics.Configuration.UnitTests.csproj ├── MetricProviderConfiguration.Tests.cs ├── MetricProviderConfigurationFactory.Tests.cs ├── MetricProviderConfigureOptions.Tests.cs ├── MetricProviderOptions.Tests.cs ├── MetricProviderOptionsChangeTokenSource.Tests.cs ├── MetricsBuilderConfigurationExtensions.Tests.cs ├── ThrowingOptions.cs └── ThrowingProvider.cs ├── Core ├── DisabledAndThrowingMetric.cs ├── EnabledButThrowingMetric.cs ├── EnabledNonThrowingMetric.cs ├── Finite.Metrics.UnitTests.csproj ├── Measure.Duration.Tests.cs ├── Metric.Tests.cs ├── MetricFactory.Tests.cs ├── MetricsServiceCollectionExtensions.Tests.cs ├── NonThrowingMetricProvider.cs ├── ThrowingMetric.cs └── ThrowingMetricProvider.cs ├── Directory.Build.props ├── Directory.Build.targets └── Providers └── OpenTsdb ├── DummyHttpMessageHandler.cs ├── Finite.Metrics.OpenTsdb.UnitTests.csproj ├── MetricsBuilderTsdbExtensions.Tests.cs ├── OpenTsdbProvider.Tests.cs └── TestSystemClock.cs /.editorconfig: -------------------------------------------------------------------------------- 1 | ############################################################################### 2 | # EditorConfig is awesome: http://EditorConfig.org 3 | ############################################################################### 4 | 5 | ############################################################################### 6 | # Top-most EditorConfig file 7 | ############################################################################### 8 | root = true 9 | 10 | ############################################################################### 11 | # Set default behavior to: 12 | # a UTF-8 encoding, 13 | # Unix-style line endings, 14 | # a newline ending the file, 15 | # 4 space indentation, and 16 | # trimming of trailing whitespace 17 | ############################################################################### 18 | [*] 19 | charset = utf-8 20 | end_of_line = lf 21 | insert_final_newline = true 22 | indent_style = space 23 | indent_size = 4 24 | trim_trailing_whitespace = true 25 | 26 | ############################################################################### 27 | # Set file behavior to: 28 | # 2 space indentation 29 | ############################################################################### 30 | [*.{cmd,config,csproj,cxxproj,json,nuspec,props,ps1,resx,sh,targets,yml}] 31 | indent_size = 2 32 | 33 | ############################################################################### 34 | # Set file behavior to: 35 | # Windows-style line endings, and 36 | # tabular indentation 37 | ############################################################################### 38 | [*.sln] 39 | end_of_line = crlf 40 | indent_style = tab 41 | 42 | ############################################################################### 43 | # Set dotnet naming rules to: 44 | # suggest async members be pascal case suffixed with Async 45 | # suggest const declarations be pascal case 46 | # suggest interfaces be pascal case prefixed with I 47 | # suggest parameters be camel case 48 | # suggest private and internal static fields be pascal case 49 | # suggest private and internal fields be camel case and prefixed with underscore 50 | # suggest public and protected declarations be pascal case 51 | # suggest static readonly declarations be pascal case 52 | # suggest type parameters be prefixed with T 53 | ############################################################################### 54 | [*.cs] 55 | dotnet_naming_rule.async_members_should_be_pascal_case_suffixed_with_async.severity = suggestion 56 | dotnet_naming_rule.async_members_should_be_pascal_case_suffixed_with_async.style = pascal_case_suffixed_with_async 57 | dotnet_naming_rule.async_members_should_be_pascal_case_suffixed_with_async.symbols = async_members 58 | 59 | dotnet_naming_rule.const_declarations_should_be_pascal_case.severity = suggestion 60 | dotnet_naming_rule.const_declarations_should_be_pascal_case.style = pascal_case 61 | dotnet_naming_rule.const_declarations_should_be_pascal_case.symbols = const_declarations 62 | 63 | dotnet_naming_rule.interfaces_should_be_pascal_case_prefixed_with_i.severity = suggestion 64 | dotnet_naming_rule.interfaces_should_be_pascal_case_prefixed_with_i.style = pascal_case_prefixed_with_i 65 | dotnet_naming_rule.interfaces_should_be_pascal_case_prefixed_with_i.symbols = interfaces 66 | 67 | dotnet_naming_rule.parameters_should_be_camel_case.severity = suggestion 68 | dotnet_naming_rule.parameters_should_be_camel_case.style = camel_case 69 | dotnet_naming_rule.parameters_should_be_camel_case.symbols = parameters 70 | 71 | dotnet_naming_rule.private_and_internal_static_fields_should_be_pascal_case.severity = suggestion 72 | dotnet_naming_rule.private_and_internal_static_fields_should_be_pascal_case.style = pascal_case 73 | dotnet_naming_rule.private_and_internal_static_fields_should_be_pascal_case.symbols = private_and_internal_static_fields 74 | 75 | dotnet_naming_rule.private_and_internal_fields_should_be_camel_case_prefixed_with_underscore.severity = suggestion 76 | dotnet_naming_rule.private_and_internal_fields_should_be_camel_case_prefixed_with_underscore.style = camel_case_prefixed_with_underscore 77 | dotnet_naming_rule.private_and_internal_fields_should_be_camel_case_prefixed_with_underscore.symbols = private_and_internal_fields 78 | 79 | dotnet_naming_rule.public_and_protected_declarations_should_be_pascal_case.severity = suggestion 80 | dotnet_naming_rule.public_and_protected_declarations_should_be_pascal_case.style = pascal_case 81 | dotnet_naming_rule.public_and_protected_declarations_should_be_pascal_case.symbols = public_and_protected_declarations 82 | 83 | dotnet_naming_rule.static_readonly_declarations_should_be_pascal_case.severity = suggestion 84 | dotnet_naming_rule.static_readonly_declarations_should_be_pascal_case.style = pascal_case 85 | dotnet_naming_rule.static_readonly_declarations_should_be_pascal_case.symbols = static_readonly_declarations 86 | 87 | dotnet_naming_rule.type_parameters_should_be_pascal_case_prefixed_with_t.severity = suggestion 88 | dotnet_naming_rule.type_parameters_should_be_pascal_case_prefixed_with_t.style = pascal_case_prefixed_with_t 89 | dotnet_naming_rule.type_parameters_should_be_pascal_case_prefixed_with_t.symbols = type_parameters 90 | 91 | ############################################################################### 92 | # Set dotnet naming styles to define: 93 | # camel case 94 | # camel case prefixed with _ 95 | # camel case prefixed with s_ 96 | # pascal case 97 | # pascal case suffixed with Async 98 | # pascal case prefixed with I 99 | # pascal case prefixed with T 100 | ############################################################################### 101 | [*.cs] 102 | dotnet_naming_style.camel_case.capitalization = camel_case 103 | 104 | dotnet_naming_style.camel_case_prefixed_with_underscore.capitalization = camel_case 105 | dotnet_naming_style.camel_case_prefixed_with_underscore.required_prefix = _ 106 | 107 | dotnet_naming_style.pascal_case.capitalization = pascal_case 108 | 109 | dotnet_naming_style.pascal_case_suffixed_with_async.capitalization = pascal_case 110 | dotnet_naming_style.pascal_case_suffixed_with_async.required_suffix = Async 111 | 112 | dotnet_naming_style.pascal_case_prefixed_with_i.capitalization = pascal_case 113 | dotnet_naming_style.pascal_case_prefixed_with_i.required_prefix = I 114 | 115 | dotnet_naming_style.pascal_case_prefixed_with_t.capitalization = pascal_case 116 | dotnet_naming_style.pascal_case_prefixed_with_t.required_prefix = T 117 | 118 | ############################################################################### 119 | # Set dotnet naming symbols to: 120 | # async members 121 | # const declarations 122 | # interfaces 123 | # private and internal fields 124 | # private and internal static fields 125 | # public and protected declarations 126 | # static readonly declarations 127 | # type parameters 128 | ############################################################################### 129 | [*.cs] 130 | dotnet_naming_symbols.async_members.required_modifiers = async 131 | 132 | dotnet_naming_symbols.const_declarations.required_modifiers = const 133 | 134 | dotnet_naming_symbols.interfaces.applicable_kinds = interface 135 | 136 | dotnet_naming_symbols.parameters.applicable_kinds = parameter 137 | 138 | dotnet_naming_symbols.private_and_internal_fields.applicable_accessibilities = private, internal 139 | dotnet_naming_symbols.private_and_internal_fields.applicable_kinds = field 140 | 141 | dotnet_naming_symbols.private_and_internal_static_fields.applicable_accessibilities = private, internal 142 | dotnet_naming_symbols.private_and_internal_static_fields.applicable_kinds = field 143 | dotnet_naming_symbols.private_and_internal_static_fields.required_modifiers = static 144 | 145 | dotnet_naming_symbols.public_and_protected_declarations.applicable_accessibilities = public, protected 146 | dotnet_naming_symbols.public_and_protected_declarations.applicable_kinds = namespace, class, struct, enum, property, method, field, event, delegate, local_function 147 | 148 | dotnet_naming_symbols.static_readonly_declarations.required_modifiers = static, readonly 149 | 150 | dotnet_naming_symbols.type_parameters.applicable_kinds = type_parameter 151 | 152 | ############################################################################### 153 | # Set dotnet sort options to: 154 | # do not separate import directives into groups, and 155 | # sort system directives first 156 | ############################################################################### 157 | [*.cs] 158 | dotnet_separate_import_directive_groups = false 159 | dotnet_sort_system_directives_first = true 160 | 161 | ############################################################################### 162 | # Set dotnet style options to: 163 | # suggest null-coalescing expressions, 164 | # suggest collection-initializers, 165 | # suggest explicit tuple names, 166 | # suggest null-propogation 167 | # suggest object-initializers, 168 | # suggest parentheses in arithmetic binary operators for clarity, 169 | # suggest parentheses in other binary operators for clarity, 170 | # don't suggest parentheses in other operators if unnecessary, 171 | # suggest parentheses in relational binary operators for clarity, 172 | # suggest predefined-types for locals, parameters, and members, 173 | # suggest predefined-types of type names for member access, 174 | # don't suggest auto properties, 175 | # suggest compound assignment, 176 | # suggest conditional expression over assignment, 177 | # suggest conditional expression over return, 178 | # suggest inferred anonymous types, 179 | # suggest inferred tuple names, 180 | # suggest 'is null' checks over '== null', 181 | # don't suggest 'this.' and 'Me.' for events, 182 | # don't suggest 'this.' and 'Me.' for fields, 183 | # don't suggest 'this.' and 'Me.' for methods, 184 | # don't suggest 'this.' and 'Me.' for properties, 185 | # suggest readonly fields, and 186 | # suggest specifying accessibility modifiers 187 | ############################################################################### 188 | [*.cs] 189 | dotnet_style_coalesce_expression = true:suggestion 190 | dotnet_style_collection_initializer = true:suggestion 191 | dotnet_style_explicit_tuple_names = true:suggestion 192 | dotnet_style_null_propagation = true:suggestion 193 | dotnet_style_object_initializer = true:suggestion 194 | 195 | dotnet_style_parentheses_in_arithmetic_binary_operators = always_for_clarity:suggestion 196 | dotnet_style_parentheses_in_other_binary_operators = always_for_clarity:suggestion 197 | dotnet_style_parentheses_in_other_operators = never_if_unnecessary:suggestion 198 | dotnet_style_parentheses_in_relational_binary_operators = always_for_clarity:suggestion 199 | 200 | dotnet_style_predefined_type_for_locals_parameters_members = true:suggestion 201 | dotnet_style_predefined_type_for_member_access = true:suggestion 202 | 203 | dotnet_style_prefer_auto_properties = false:suggestion 204 | dotnet_style_prefer_compound_assignment = true:suggestion 205 | dotnet_style_prefer_conditional_expression_over_assignment = true:suggestion 206 | dotnet_style_prefer_conditional_expression_over_return = true:suggestion 207 | dotnet_style_prefer_inferred_anonymous_type_member_names = true:suggestion 208 | dotnet_style_prefer_inferred_tuple_names = true:suggestion 209 | dotnet_style_prefer_is_null_check_over_reference_equality_method = true:suggestion 210 | 211 | dotnet_style_qualification_for_event = false:suggestion 212 | dotnet_style_qualification_for_field = false:suggestion 213 | dotnet_style_qualification_for_method = false:suggestion 214 | dotnet_style_qualification_for_property = false:suggestion 215 | 216 | dotnet_style_readonly_field = true:suggestion 217 | dotnet_style_require_accessibility_modifiers = always:suggestion 218 | 219 | ############################################################################### 220 | # Set dotnet style options to: 221 | # suggest removing all unused parameters 222 | ############################################################################### 223 | [*.cs] 224 | dotnet_code_quality_unused_parameters = all:suggestion 225 | 226 | ############################################################################### 227 | # Set csharp indent options to: 228 | # indent block contents, 229 | # not indent braces, 230 | # indent case contents, 231 | # not indent case contents when block, 232 | # indent labels one less than the current, and 233 | # indent switch labels 234 | ############################################################################### 235 | [*.cs] 236 | csharp_indent_block_contents = true 237 | csharp_indent_braces = false 238 | csharp_indent_case_contents = true 239 | csharp_indent_case_contents_when_block = false 240 | csharp_indent_labels = one_less_than_current 241 | csharp_indent_switch_labels = true 242 | 243 | ############################################################################### 244 | # Set csharp new-line options to: 245 | # insert a new-line before "catch", 246 | # insert a new-line before "else", 247 | # insert a new-line before "finally", 248 | # insert a new-line before members in anonymous-types, 249 | # insert a new-line before members in object-initializers, 250 | # insert a new-line before all open braces except anonymous methods, anonymous types, lambdas, and object collections and 251 | # insert a new-line within query expression clauses 252 | ############################################################################### 253 | [*.cs] 254 | csharp_new_line_before_catch = true 255 | csharp_new_line_before_else = true 256 | csharp_new_line_before_finally = true 257 | 258 | csharp_new_line_before_members_in_anonymous_types = true 259 | csharp_new_line_before_members_in_object_initializers = true 260 | 261 | csharp_new_line_before_open_brace = accessors, control_blocks, events, indexers, local_functions, methods, object_collection_array_initializers, properties, types 262 | 263 | csharp_new_line_within_query_expression_clauses = true 264 | 265 | ############################################################################### 266 | # Set csharp preserve options to: 267 | # preserve single-line blocks, and 268 | # not preserve single-line statements 269 | ############################################################################### 270 | [*.cs] 271 | csharp_preserve_single_line_blocks = true 272 | csharp_preserve_single_line_statements = false 273 | 274 | ############################################################################### 275 | # Set csharp space options to: 276 | # remove any space after a cast, 277 | # add a space after the colon in an inheritance clause, 278 | # add a space after a comma, 279 | # remove any space after a dot, 280 | # add a space after keywords in control flow statements, 281 | # add a space after a semicolon in a "for" statement, 282 | # add a space before and after binary operators, 283 | # remove space around declaration statements, 284 | # add a space before the colon in an inheritance clause, 285 | # remove any space before a comma, 286 | # remove any space before a dot, 287 | # remove any space before an open square-bracket, 288 | # remove any space before a semicolon in a "for" statement, 289 | # remove any space between empty square-brackets, 290 | # remove any space between a method call's empty parameter list parenthesis, 291 | # remove any space between a method call's name and its opening parenthesis, 292 | # remove any space between a method call's parameter list parenthesis, 293 | # remove any space between a method declaration's empty parameter list parenthesis, 294 | # remove any space between a method declaration's name and its openening parenthesis, 295 | # remove any space between a method declaration's parameter list parenthesis, 296 | # remove any space between parentheses, and 297 | # remove any space between square brackets 298 | ############################################################################### 299 | [*.cs] 300 | csharp_space_after_cast = false 301 | csharp_space_after_colon_in_inheritance_clause = true 302 | csharp_space_after_comma = true 303 | csharp_space_after_dot = false 304 | csharp_space_after_keywords_in_control_flow_statements = true 305 | csharp_space_after_semicolon_in_for_statement = true 306 | 307 | csharp_space_around_binary_operators = before_and_after 308 | csharp_space_around_declaration_statements = do_not_ignore 309 | 310 | csharp_space_before_colon_in_inheritance_clause = true 311 | csharp_space_before_comma = false 312 | csharp_space_before_dot = false 313 | csharp_space_before_open_square_brackets = false 314 | csharp_space_before_semicolon_in_for_statement = false 315 | 316 | csharp_space_between_empty_square_brackets = false 317 | csharp_space_between_method_call_empty_parameter_list_parentheses = false 318 | csharp_space_between_method_call_name_and_opening_parenthesis = false 319 | csharp_space_between_method_call_parameter_list_parentheses = false 320 | csharp_space_between_method_declaration_empty_parameter_list_parentheses = false 321 | csharp_space_between_method_declaration_name_and_open_parenthesis = false 322 | csharp_space_between_method_declaration_parameter_list_parentheses = false 323 | csharp_space_between_parentheses = false 324 | csharp_space_between_square_brackets = false 325 | 326 | ############################################################################### 327 | # Set csharp style options to: 328 | # don't suggest braces, 329 | # suggest simple default expressions, 330 | # suggest a preferred modifier order, 331 | # suggest conditional delegate calls, 332 | # suggest deconstructed variable declarations, 333 | # don't suggest expression-bodied accessors, 334 | # don't suggest expression-bodied indexers, 335 | # don't suggest expression-bodied constructors, 336 | # suggest expression-bodied lambdas, 337 | # don't suggest expression-bodied methods, 338 | # don't suggest expression-bodied operators, 339 | # don't suggest expression-bodied properties, 340 | # suggest inlined variable declarations, 341 | # suggest local over anonymous functions, 342 | # suggest pattern-matching over "as" with "null" check, 343 | # suggest pattern-matching over "is" with "cast" check, 344 | # suggest throw expressions, 345 | # suggest a discard variable for unused value expression statements, 346 | # suggest a discard variable for unused assignments, 347 | # suggest var for built-in types, 348 | # suggest var when the type is not apparent, and 349 | # suggest var when the type is apparent 350 | ############################################################################### 351 | [*.cs] 352 | csharp_prefer_braces = false:suggestion 353 | csharp_prefer_simple_default_expression = true:suggestion 354 | csharp_preferred_modifier_order = public,private,protected,internal,static,extern,new,virtual,abstract,sealed,override,readonly,unsafe,volatile,async:suggestion 355 | 356 | csharp_style_conditional_delegate_call = true:suggestion 357 | csharp_style_deconstructed_variable_declaration = true:suggestion 358 | 359 | csharp_style_expression_bodied_accessors = when_on_single_line:suggestion 360 | csharp_style_expression_bodied_constructors = false:suggestion 361 | csharp_style_expression_bodied_indexers = when_on_single_line:suggestion 362 | csharp_style_expression_bodied_lambdas = true:suggestion 363 | csharp_style_expression_bodied_methods = when_on_single_line:suggestion 364 | csharp_style_expression_bodied_operators = when_on_single_line:suggestion 365 | csharp_style_expression_bodied_properties = when_on_single_line:suggestion 366 | 367 | csharp_style_inlined_variable_declaration = true:suggestion 368 | 369 | csharp_style_pattern_local_over_anonymous_function = true:suggestion 370 | csharp_style_pattern_matching_over_as_with_null_check = true:suggestion 371 | csharp_style_pattern_matching_over_is_with_cast_check = true:suggestion 372 | 373 | csharp_style_throw_expression = true:suggestion 374 | 375 | csharp_style_unused_value_expression_statement_preference = discard_variable:suggestion 376 | csharp_style_unused_value_assignment_preference = discard_variable:suggestion 377 | 378 | csharp_style_var_for_built_in_types = true:none 379 | csharp_style_var_elsewhere = true:suggestion 380 | csharp_style_var_when_type_is_apparent = true:suggestion 381 | -------------------------------------------------------------------------------- /.gitattributes: -------------------------------------------------------------------------------- 1 | ############################################################################### 2 | # Default to Unix-style text files 3 | ############################################################################### 4 | * text eol=lf 5 | 6 | ############################################################################### 7 | # Treat code and markdown as Unix-style text files 8 | ############################################################################### 9 | *.cs text eol=lf 10 | *.csproj text eol=lf 11 | *.md text eol=lf 12 | *.props text eol=lf 13 | *.targets text eol=lf 14 | 15 | ############################################################################### 16 | # Treat Solution files as Windows text files 17 | ############################################################################### 18 | *.sln text eol=crlf 19 | -------------------------------------------------------------------------------- /.github/workflows/publish.yml: -------------------------------------------------------------------------------- 1 | name: Publish Finite.Metrics to MyGet 2 | 3 | on: 4 | push: 5 | branches: 6 | - main 7 | paths-ignore: 8 | - 'docs/**' 9 | pull_request: 10 | 11 | env: 12 | MYGET_FEED: https://www.myget.org/F/finitereality/api/v2/package 13 | CI: true 14 | 15 | jobs: 16 | build: 17 | runs-on: [ubuntu-latest] 18 | 19 | steps: 20 | - uses: actions/checkout@v2 21 | - name: Setup .NET Core 22 | uses: actions/setup-dotnet@v1 23 | with: 24 | dotnet-version: 5.0.100-preview.4.20258.7 25 | 26 | - name: Install dependencies 27 | run: dotnet restore 28 | 29 | - name: Build Finite.Metrics 30 | run: dotnet build --no-restore --configuration Release 31 | 32 | - name: Run Unit Tests 33 | run: dotnet test --no-build --configuration Release /p:CollectCoverage=true 34 | 35 | - name: Upload code coverage 36 | run: bash <(curl -s https://codecov.io/bash) -s "${{ github.workspace }}/artifacts/coverage/" -f "*.xml" 37 | shell: bash 38 | 39 | - name: Pack Finite.Metrics 40 | run: dotnet pack --no-build --configuration Release 41 | 42 | - name: Upload Artifacts 43 | uses: actions/upload-artifact@v1.0.0 44 | with: 45 | name: nupkgs 46 | path: ${{ github.workspace }}/artifacts/pkg/Release/ 47 | 48 | - name: Upload NuGet packages 49 | run: for pkg in artifacts/pkg/Release/*.nupkg; do dotnet nuget push "$pkg" -k "${{ secrets.MyGet }}" -s "${{ env.MYGET_FEED }}"; done 50 | shell: bash 51 | -------------------------------------------------------------------------------- /.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 | 49 | # Build Results of an ATL Project 50 | [Dd]ebugPS/ 51 | [Rr]eleasePS/ 52 | dlldata.c 53 | 54 | # Benchmark Results 55 | BenchmarkDotNet.Artifacts/ 56 | 57 | # .NET Core 58 | project.lock.json 59 | project.fragment.lock.json 60 | artifacts/ 61 | 62 | # StyleCop 63 | StyleCopReport.xml 64 | 65 | # Files built by Visual Studio 66 | *_i.c 67 | *_p.c 68 | *_h.h 69 | *.ilk 70 | *.meta 71 | *.obj 72 | *.iobj 73 | *.pch 74 | *.pdb 75 | *.ipdb 76 | *.pgc 77 | *.pgd 78 | *.rsp 79 | *.sbr 80 | *.tlb 81 | *.tli 82 | *.tlh 83 | *.tmp 84 | *.tmp_proj 85 | *_wpftmp.csproj 86 | *.log 87 | *.vspscc 88 | *.vssscc 89 | .builds 90 | *.pidb 91 | *.svclog 92 | *.scc 93 | 94 | # Chutzpah Test files 95 | _Chutzpah* 96 | 97 | # Visual C++ cache files 98 | ipch/ 99 | *.aps 100 | *.ncb 101 | *.opendb 102 | *.opensdf 103 | *.sdf 104 | *.cachefile 105 | *.VC.db 106 | *.VC.VC.opendb 107 | 108 | # Visual Studio profiler 109 | *.psess 110 | *.vsp 111 | *.vspx 112 | *.sap 113 | 114 | # Visual Studio Trace Files 115 | *.e2e 116 | 117 | # TFS 2012 Local Workspace 118 | $tf/ 119 | 120 | # Guidance Automation Toolkit 121 | *.gpState 122 | 123 | # ReSharper is a .NET coding add-in 124 | _ReSharper*/ 125 | *.[Rr]e[Ss]harper 126 | *.DotSettings.user 127 | 128 | # JustCode is a .NET coding add-in 129 | .JustCode 130 | 131 | # TeamCity is a build add-in 132 | _TeamCity* 133 | 134 | # DotCover is a Code Coverage Tool 135 | *.dotCover 136 | 137 | # AxoCover is a Code Coverage Tool 138 | .axoCover/* 139 | !.axoCover/settings.json 140 | 141 | # Visual Studio code coverage results 142 | *.coverage 143 | *.coveragexml 144 | 145 | # NCrunch 146 | _NCrunch_* 147 | .*crunch*.local.xml 148 | nCrunchTemp_* 149 | 150 | # MightyMoose 151 | *.mm.* 152 | AutoTest.Net/ 153 | 154 | # Web workbench (sass) 155 | .sass-cache/ 156 | 157 | # Installshield output folder 158 | [Ee]xpress/ 159 | 160 | # DocProject is a documentation generator add-in 161 | DocProject/buildhelp/ 162 | DocProject/Help/*.HxT 163 | DocProject/Help/*.HxC 164 | DocProject/Help/*.hhc 165 | DocProject/Help/*.hhk 166 | DocProject/Help/*.hhp 167 | DocProject/Help/Html2 168 | DocProject/Help/html 169 | 170 | # Click-Once directory 171 | publish/ 172 | 173 | # Publish Web Output 174 | *.[Pp]ublish.xml 175 | *.azurePubxml 176 | # Note: Comment the next line if you want to checkin your web deploy settings, 177 | # but database connection strings (with potential passwords) will be unencrypted 178 | *.pubxml 179 | *.publishproj 180 | 181 | # Microsoft Azure Web App publish settings. Comment the next line if you want to 182 | # checkin your Azure Web App publish settings, but sensitive information contained 183 | # in these scripts will be unencrypted 184 | PublishScripts/ 185 | 186 | # NuGet Packages 187 | *.nupkg 188 | # The packages folder can be ignored because of Package Restore 189 | **/[Pp]ackages/* 190 | # except build/, which is used as an MSBuild target. 191 | !**/[Pp]ackages/build/ 192 | # Uncomment if necessary however generally it will be regenerated when needed 193 | #!**/[Pp]ackages/repositories.config 194 | # NuGet v3's project.json files produces more ignorable files 195 | *.nuget.props 196 | *.nuget.targets 197 | 198 | # Microsoft Azure Build Output 199 | csx/ 200 | *.build.csdef 201 | 202 | # Microsoft Azure Emulator 203 | ecf/ 204 | rcf/ 205 | 206 | # Windows Store app package directories and files 207 | AppPackages/ 208 | BundleArtifacts/ 209 | Package.StoreAssociation.xml 210 | _pkginfo.txt 211 | *.appx 212 | *.appxbundle 213 | *.appxupload 214 | 215 | # Visual Studio cache files 216 | # files ending in .cache can be ignored 217 | *.[Cc]ache 218 | # but keep track of directories ending in .cache 219 | !?*.[Cc]ache/ 220 | 221 | # Others 222 | ClientBin/ 223 | ~$* 224 | *~ 225 | *.dbmdl 226 | *.dbproj.schemaview 227 | *.jfm 228 | *.pfx 229 | *.publishsettings 230 | orleans.codegen.cs 231 | 232 | # Including strong name files can present a security risk 233 | # (https://github.com/github/gitignore/pull/2483#issue-259490424) 234 | #*.snk 235 | 236 | # Since there are multiple workflows, uncomment next line to ignore bower_components 237 | # (https://github.com/github/gitignore/pull/1529#issuecomment-104372622) 238 | #bower_components/ 239 | 240 | # RIA/Silverlight projects 241 | Generated_Code/ 242 | 243 | # Backup & report files from converting an old project file 244 | # to a newer Visual Studio version. Backup files are not needed, 245 | # because we have git ;-) 246 | _UpgradeReport_Files/ 247 | Backup*/ 248 | UpgradeLog*.XML 249 | UpgradeLog*.htm 250 | ServiceFabricBackup/ 251 | *.rptproj.bak 252 | 253 | # SQL Server files 254 | *.mdf 255 | *.ldf 256 | *.ndf 257 | 258 | # Business Intelligence projects 259 | *.rdl.data 260 | *.bim.layout 261 | *.bim_*.settings 262 | *.rptproj.rsuser 263 | *- Backup*.rdl 264 | 265 | # Microsoft Fakes 266 | FakesAssemblies/ 267 | 268 | # GhostDoc plugin setting file 269 | *.GhostDoc.xml 270 | 271 | # Node.js Tools for Visual Studio 272 | .ntvs_analysis.dat 273 | node_modules/ 274 | 275 | # Visual Studio 6 build log 276 | *.plg 277 | 278 | # Visual Studio 6 workspace options file 279 | *.opt 280 | 281 | # Visual Studio 6 auto-generated workspace file (contains which files were open etc.) 282 | *.vbw 283 | 284 | # Visual Studio LightSwitch build output 285 | **/*.HTMLClient/GeneratedArtifacts 286 | **/*.DesktopClient/GeneratedArtifacts 287 | **/*.DesktopClient/ModelManifest.xml 288 | **/*.Server/GeneratedArtifacts 289 | **/*.Server/ModelManifest.xml 290 | _Pvt_Extensions 291 | 292 | # Paket dependency manager 293 | .paket/paket.exe 294 | paket-files/ 295 | 296 | # FAKE - F# Make 297 | .fake/ 298 | 299 | # CodeRush personal settings 300 | .cr/personal 301 | 302 | # Python Tools for Visual Studio (PTVS) 303 | __pycache__/ 304 | *.pyc 305 | 306 | # Cake - Uncomment if you are using it 307 | # tools/** 308 | # !tools/packages.config 309 | 310 | # Tabs Studio 311 | *.tss 312 | 313 | # Telerik's JustMock configuration file 314 | *.jmconfig 315 | 316 | # BizTalk build output 317 | *.btp.cs 318 | *.btm.cs 319 | *.odx.cs 320 | *.xsd.cs 321 | 322 | # OpenCover UI analysis results 323 | OpenCover/ 324 | 325 | # Azure Stream Analytics local run output 326 | ASALocalRun/ 327 | 328 | # MSBuild Binary and Structured Log 329 | *.binlog 330 | 331 | # NVidia Nsight GPU debugger configuration file 332 | *.nvuser 333 | 334 | # MFractors (Xamarin productivity tool) working folder 335 | .mfractor/ 336 | 337 | # Local History for Visual Studio 338 | .localhistory/ 339 | 340 | # BeatPulse healthcheck temp database 341 | healthchecksdb 342 | 343 | # Backup folder for Package Reference Convert tool in Visual Studio 2017 344 | MigrationBackup/ 345 | 346 | ## 347 | ## Visual studio for Mac 348 | ## 349 | 350 | 351 | # globs 352 | Makefile.in 353 | *.userprefs 354 | *.usertasks 355 | config.make 356 | config.status 357 | aclocal.m4 358 | install-sh 359 | autom4te.cache/ 360 | *.tar.gz 361 | tarballs/ 362 | test-results/ 363 | 364 | # Mac bundle stuff 365 | *.dmg 366 | *.app 367 | 368 | # content below from: https://github.com/github/gitignore/blob/master/Global/macOS.gitignore 369 | # General 370 | .DS_Store 371 | .AppleDouble 372 | .LSOverride 373 | 374 | # Icon must end with two \r 375 | Icon 376 | 377 | 378 | # Thumbnails 379 | ._* 380 | 381 | # Files that might appear in the root of a volume 382 | .DocumentRevisions-V100 383 | .fseventsd 384 | .Spotlight-V100 385 | .TemporaryItems 386 | .Trashes 387 | .VolumeIcon.icns 388 | .com.apple.timemachine.donotpresent 389 | 390 | # Directories potentially created on remote AFP share 391 | .AppleDB 392 | .AppleDesktop 393 | Network Trash Folder 394 | Temporary Items 395 | .apdisk 396 | 397 | # content below from: https://github.com/github/gitignore/blob/master/Global/Windows.gitignore 398 | # Windows thumbnail cache files 399 | Thumbs.db 400 | ehthumbs.db 401 | ehthumbs_vista.db 402 | 403 | # Dump file 404 | *.stackdump 405 | 406 | # Folder config file 407 | [Dd]esktop.ini 408 | 409 | # Recycle Bin used on file shares 410 | $RECYCLE.BIN/ 411 | 412 | # Windows Installer files 413 | *.cab 414 | *.msi 415 | *.msix 416 | *.msm 417 | *.msp 418 | 419 | # Windows shortcuts 420 | *.lnk 421 | 422 | # JetBrains Rider 423 | .idea/ 424 | *.sln.iml 425 | 426 | ## 427 | ## Visual Studio Code 428 | ## 429 | .vscode/ 430 | -------------------------------------------------------------------------------- /Directory.Build.props: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 14 | 15 | 16 | 17 | $([System.String]::Copy('$(GITHUB_REF)').Replace('refs/pull/', '').Replace('/merge', '')) 18 | 19 | 20 | 21 | 22 | $(MSBuildThisFileDirectory)artifacts/ 23 | $(FiniteMetricsProjectCategory)/$(MSBuildProjectName) 24 | https://github.com/FiniteReality/Finite.Metrics/ 25 | 26 | 27 | 28 | 29 | true 30 | $(BaseArtifactsPath)obj/$(BaseArtifactsPathSuffix)/ 31 | embedded 32 | false 33 | enable 34 | true 35 | true 36 | true 37 | 38 | 39 | 40 | true 41 | 42 | 43 | 44 | 45 | Monica S. 46 | $(BaseArtifactsPath)bin/$(BaseArtifactsPathSuffix)/ 47 | Finite.Metrics 48 | $(BaseArtifactsPath)pkg/$(Configuration) 49 | $(BaseArtifactsPath)pkg/$(Configuration) 50 | Finite.Metrics 51 | 0.2.0 52 | alpha 53 | pr$(PullRequestNumber) 54 | 55 | 56 | 57 | 58 | Copyright © Monica S. 59 | A metrics framework for .NET styled after Microsoft.Extensions.Logging 60 | strict 61 | true 62 | true 63 | preview 64 | 4.3 65 | en-US 66 | true 67 | MIT 68 | $(RepositoryUrl) 69 | git 70 | 71 | https://api.nuget.org/v3/index.json; 72 | 73 | true 74 | 75 | 76 | 77 | 78 | true 79 | 80 | 81 | 82 | 83 | 84 | 85 | 86 | 87 | -------------------------------------------------------------------------------- /Directory.Build.targets: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 14 | 15 | 16 | 17 | $(DefineConstants);$(OS) 18 | $(NoWarn);NU5105 19 | $(Version).$(GITHUB_RUN_ID) 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | -------------------------------------------------------------------------------- /Finite.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", "{7C493A69-008A-4F4B-9AC1-23A64682C4AB}" 7 | EndProject 8 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Finite.Metrics.Abstractions", "src\Abstractions\Finite.Metrics.Abstractions.csproj", "{9E815B92-5565-46FA-A666-18BC0D5333DA}" 9 | EndProject 10 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Finite.Metrics", "src\Core\Finite.Metrics.csproj", "{BDEAF88D-40A6-47EF-B4CB-AE3C8F4B3111}" 11 | EndProject 12 | Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Providers", "Providers", "{13420B5B-28D6-40FF-B378-82E6FB742AB4}" 13 | EndProject 14 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Finite.Metrics.OpenTsdb", "src\Providers\OpenTsdb\Finite.Metrics.OpenTsdb.csproj", "{84D1C7FC-C682-48A5-B4DC-08C8FB3A7FC6}" 15 | EndProject 16 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Finite.Metrics.Configuration", "src\Configuration\Finite.Metrics.Configuration.csproj", "{2080C45E-CDB2-4525-8AE7-8E51D10744D8}" 17 | EndProject 18 | Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "tests", "tests", "{62C62A44-4FCE-4B47-96CE-C9282E374813}" 19 | EndProject 20 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Finite.Metrics.UnitTests", "tests\Core\Finite.Metrics.UnitTests.csproj", "{92589C32-7712-447A-84A9-D493A0637A7A}" 21 | EndProject 22 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Finite.Metrics.Configuration.UnitTests", "tests\Configuration\Finite.Metrics.Configuration.UnitTests.csproj", "{4AD95898-6A60-4B74-976A-80DD4BFCAFC5}" 23 | EndProject 24 | Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Providers", "Providers", "{310165FD-B3CA-49FD-929D-9E8BABAF116B}" 25 | EndProject 26 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Finite.Metrics.OpenTsdb.UnitTests", "tests\Providers\OpenTsdb\Finite.Metrics.OpenTsdb.UnitTests.csproj", "{8C2BA2A6-9D4A-432D-B8B1-B07E0E01FB2C}" 27 | EndProject 28 | Global 29 | GlobalSection(SolutionConfigurationPlatforms) = preSolution 30 | Debug|Any CPU = Debug|Any CPU 31 | Debug|x64 = Debug|x64 32 | Debug|x86 = Debug|x86 33 | Release|Any CPU = Release|Any CPU 34 | Release|x64 = Release|x64 35 | Release|x86 = Release|x86 36 | EndGlobalSection 37 | GlobalSection(SolutionProperties) = preSolution 38 | HideSolutionNode = FALSE 39 | EndGlobalSection 40 | GlobalSection(ProjectConfigurationPlatforms) = postSolution 41 | {9E815B92-5565-46FA-A666-18BC0D5333DA}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 42 | {9E815B92-5565-46FA-A666-18BC0D5333DA}.Debug|Any CPU.Build.0 = Debug|Any CPU 43 | {9E815B92-5565-46FA-A666-18BC0D5333DA}.Debug|x64.ActiveCfg = Debug|Any CPU 44 | {9E815B92-5565-46FA-A666-18BC0D5333DA}.Debug|x64.Build.0 = Debug|Any CPU 45 | {9E815B92-5565-46FA-A666-18BC0D5333DA}.Debug|x86.ActiveCfg = Debug|Any CPU 46 | {9E815B92-5565-46FA-A666-18BC0D5333DA}.Debug|x86.Build.0 = Debug|Any CPU 47 | {9E815B92-5565-46FA-A666-18BC0D5333DA}.Release|Any CPU.ActiveCfg = Release|Any CPU 48 | {9E815B92-5565-46FA-A666-18BC0D5333DA}.Release|Any CPU.Build.0 = Release|Any CPU 49 | {9E815B92-5565-46FA-A666-18BC0D5333DA}.Release|x64.ActiveCfg = Release|Any CPU 50 | {9E815B92-5565-46FA-A666-18BC0D5333DA}.Release|x64.Build.0 = Release|Any CPU 51 | {9E815B92-5565-46FA-A666-18BC0D5333DA}.Release|x86.ActiveCfg = Release|Any CPU 52 | {9E815B92-5565-46FA-A666-18BC0D5333DA}.Release|x86.Build.0 = Release|Any CPU 53 | {BDEAF88D-40A6-47EF-B4CB-AE3C8F4B3111}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 54 | {BDEAF88D-40A6-47EF-B4CB-AE3C8F4B3111}.Debug|Any CPU.Build.0 = Debug|Any CPU 55 | {BDEAF88D-40A6-47EF-B4CB-AE3C8F4B3111}.Debug|x64.ActiveCfg = Debug|Any CPU 56 | {BDEAF88D-40A6-47EF-B4CB-AE3C8F4B3111}.Debug|x64.Build.0 = Debug|Any CPU 57 | {BDEAF88D-40A6-47EF-B4CB-AE3C8F4B3111}.Debug|x86.ActiveCfg = Debug|Any CPU 58 | {BDEAF88D-40A6-47EF-B4CB-AE3C8F4B3111}.Debug|x86.Build.0 = Debug|Any CPU 59 | {BDEAF88D-40A6-47EF-B4CB-AE3C8F4B3111}.Release|Any CPU.ActiveCfg = Release|Any CPU 60 | {BDEAF88D-40A6-47EF-B4CB-AE3C8F4B3111}.Release|Any CPU.Build.0 = Release|Any CPU 61 | {BDEAF88D-40A6-47EF-B4CB-AE3C8F4B3111}.Release|x64.ActiveCfg = Release|Any CPU 62 | {BDEAF88D-40A6-47EF-B4CB-AE3C8F4B3111}.Release|x64.Build.0 = Release|Any CPU 63 | {BDEAF88D-40A6-47EF-B4CB-AE3C8F4B3111}.Release|x86.ActiveCfg = Release|Any CPU 64 | {BDEAF88D-40A6-47EF-B4CB-AE3C8F4B3111}.Release|x86.Build.0 = Release|Any CPU 65 | {84D1C7FC-C682-48A5-B4DC-08C8FB3A7FC6}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 66 | {84D1C7FC-C682-48A5-B4DC-08C8FB3A7FC6}.Debug|Any CPU.Build.0 = Debug|Any CPU 67 | {84D1C7FC-C682-48A5-B4DC-08C8FB3A7FC6}.Debug|x64.ActiveCfg = Debug|Any CPU 68 | {84D1C7FC-C682-48A5-B4DC-08C8FB3A7FC6}.Debug|x64.Build.0 = Debug|Any CPU 69 | {84D1C7FC-C682-48A5-B4DC-08C8FB3A7FC6}.Debug|x86.ActiveCfg = Debug|Any CPU 70 | {84D1C7FC-C682-48A5-B4DC-08C8FB3A7FC6}.Debug|x86.Build.0 = Debug|Any CPU 71 | {84D1C7FC-C682-48A5-B4DC-08C8FB3A7FC6}.Release|Any CPU.ActiveCfg = Release|Any CPU 72 | {84D1C7FC-C682-48A5-B4DC-08C8FB3A7FC6}.Release|Any CPU.Build.0 = Release|Any CPU 73 | {84D1C7FC-C682-48A5-B4DC-08C8FB3A7FC6}.Release|x64.ActiveCfg = Release|Any CPU 74 | {84D1C7FC-C682-48A5-B4DC-08C8FB3A7FC6}.Release|x64.Build.0 = Release|Any CPU 75 | {84D1C7FC-C682-48A5-B4DC-08C8FB3A7FC6}.Release|x86.ActiveCfg = Release|Any CPU 76 | {84D1C7FC-C682-48A5-B4DC-08C8FB3A7FC6}.Release|x86.Build.0 = Release|Any CPU 77 | {2080C45E-CDB2-4525-8AE7-8E51D10744D8}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 78 | {2080C45E-CDB2-4525-8AE7-8E51D10744D8}.Debug|Any CPU.Build.0 = Debug|Any CPU 79 | {2080C45E-CDB2-4525-8AE7-8E51D10744D8}.Debug|x64.ActiveCfg = Debug|Any CPU 80 | {2080C45E-CDB2-4525-8AE7-8E51D10744D8}.Debug|x64.Build.0 = Debug|Any CPU 81 | {2080C45E-CDB2-4525-8AE7-8E51D10744D8}.Debug|x86.ActiveCfg = Debug|Any CPU 82 | {2080C45E-CDB2-4525-8AE7-8E51D10744D8}.Debug|x86.Build.0 = Debug|Any CPU 83 | {2080C45E-CDB2-4525-8AE7-8E51D10744D8}.Release|Any CPU.ActiveCfg = Release|Any CPU 84 | {2080C45E-CDB2-4525-8AE7-8E51D10744D8}.Release|Any CPU.Build.0 = Release|Any CPU 85 | {2080C45E-CDB2-4525-8AE7-8E51D10744D8}.Release|x64.ActiveCfg = Release|Any CPU 86 | {2080C45E-CDB2-4525-8AE7-8E51D10744D8}.Release|x64.Build.0 = Release|Any CPU 87 | {2080C45E-CDB2-4525-8AE7-8E51D10744D8}.Release|x86.ActiveCfg = Release|Any CPU 88 | {2080C45E-CDB2-4525-8AE7-8E51D10744D8}.Release|x86.Build.0 = Release|Any CPU 89 | {92589C32-7712-447A-84A9-D493A0637A7A}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 90 | {92589C32-7712-447A-84A9-D493A0637A7A}.Debug|Any CPU.Build.0 = Debug|Any CPU 91 | {92589C32-7712-447A-84A9-D493A0637A7A}.Debug|x64.ActiveCfg = Debug|Any CPU 92 | {92589C32-7712-447A-84A9-D493A0637A7A}.Debug|x64.Build.0 = Debug|Any CPU 93 | {92589C32-7712-447A-84A9-D493A0637A7A}.Debug|x86.ActiveCfg = Debug|Any CPU 94 | {92589C32-7712-447A-84A9-D493A0637A7A}.Debug|x86.Build.0 = Debug|Any CPU 95 | {92589C32-7712-447A-84A9-D493A0637A7A}.Release|Any CPU.ActiveCfg = Release|Any CPU 96 | {92589C32-7712-447A-84A9-D493A0637A7A}.Release|Any CPU.Build.0 = Release|Any CPU 97 | {92589C32-7712-447A-84A9-D493A0637A7A}.Release|x64.ActiveCfg = Release|Any CPU 98 | {92589C32-7712-447A-84A9-D493A0637A7A}.Release|x64.Build.0 = Release|Any CPU 99 | {92589C32-7712-447A-84A9-D493A0637A7A}.Release|x86.ActiveCfg = Release|Any CPU 100 | {92589C32-7712-447A-84A9-D493A0637A7A}.Release|x86.Build.0 = Release|Any CPU 101 | {4AD95898-6A60-4B74-976A-80DD4BFCAFC5}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 102 | {4AD95898-6A60-4B74-976A-80DD4BFCAFC5}.Debug|Any CPU.Build.0 = Debug|Any CPU 103 | {4AD95898-6A60-4B74-976A-80DD4BFCAFC5}.Debug|x64.ActiveCfg = Debug|Any CPU 104 | {4AD95898-6A60-4B74-976A-80DD4BFCAFC5}.Debug|x64.Build.0 = Debug|Any CPU 105 | {4AD95898-6A60-4B74-976A-80DD4BFCAFC5}.Debug|x86.ActiveCfg = Debug|Any CPU 106 | {4AD95898-6A60-4B74-976A-80DD4BFCAFC5}.Debug|x86.Build.0 = Debug|Any CPU 107 | {4AD95898-6A60-4B74-976A-80DD4BFCAFC5}.Release|Any CPU.ActiveCfg = Release|Any CPU 108 | {4AD95898-6A60-4B74-976A-80DD4BFCAFC5}.Release|Any CPU.Build.0 = Release|Any CPU 109 | {4AD95898-6A60-4B74-976A-80DD4BFCAFC5}.Release|x64.ActiveCfg = Release|Any CPU 110 | {4AD95898-6A60-4B74-976A-80DD4BFCAFC5}.Release|x64.Build.0 = Release|Any CPU 111 | {4AD95898-6A60-4B74-976A-80DD4BFCAFC5}.Release|x86.ActiveCfg = Release|Any CPU 112 | {4AD95898-6A60-4B74-976A-80DD4BFCAFC5}.Release|x86.Build.0 = Release|Any CPU 113 | {8C2BA2A6-9D4A-432D-B8B1-B07E0E01FB2C}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 114 | {8C2BA2A6-9D4A-432D-B8B1-B07E0E01FB2C}.Debug|Any CPU.Build.0 = Debug|Any CPU 115 | {8C2BA2A6-9D4A-432D-B8B1-B07E0E01FB2C}.Debug|x64.ActiveCfg = Debug|Any CPU 116 | {8C2BA2A6-9D4A-432D-B8B1-B07E0E01FB2C}.Debug|x64.Build.0 = Debug|Any CPU 117 | {8C2BA2A6-9D4A-432D-B8B1-B07E0E01FB2C}.Debug|x86.ActiveCfg = Debug|Any CPU 118 | {8C2BA2A6-9D4A-432D-B8B1-B07E0E01FB2C}.Debug|x86.Build.0 = Debug|Any CPU 119 | {8C2BA2A6-9D4A-432D-B8B1-B07E0E01FB2C}.Release|Any CPU.ActiveCfg = Release|Any CPU 120 | {8C2BA2A6-9D4A-432D-B8B1-B07E0E01FB2C}.Release|Any CPU.Build.0 = Release|Any CPU 121 | {8C2BA2A6-9D4A-432D-B8B1-B07E0E01FB2C}.Release|x64.ActiveCfg = Release|Any CPU 122 | {8C2BA2A6-9D4A-432D-B8B1-B07E0E01FB2C}.Release|x64.Build.0 = Release|Any CPU 123 | {8C2BA2A6-9D4A-432D-B8B1-B07E0E01FB2C}.Release|x86.ActiveCfg = Release|Any CPU 124 | {8C2BA2A6-9D4A-432D-B8B1-B07E0E01FB2C}.Release|x86.Build.0 = Release|Any CPU 125 | EndGlobalSection 126 | GlobalSection(NestedProjects) = preSolution 127 | {9E815B92-5565-46FA-A666-18BC0D5333DA} = {7C493A69-008A-4F4B-9AC1-23A64682C4AB} 128 | {BDEAF88D-40A6-47EF-B4CB-AE3C8F4B3111} = {7C493A69-008A-4F4B-9AC1-23A64682C4AB} 129 | {13420B5B-28D6-40FF-B378-82E6FB742AB4} = {7C493A69-008A-4F4B-9AC1-23A64682C4AB} 130 | {84D1C7FC-C682-48A5-B4DC-08C8FB3A7FC6} = {13420B5B-28D6-40FF-B378-82E6FB742AB4} 131 | {2080C45E-CDB2-4525-8AE7-8E51D10744D8} = {7C493A69-008A-4F4B-9AC1-23A64682C4AB} 132 | {92589C32-7712-447A-84A9-D493A0637A7A} = {62C62A44-4FCE-4B47-96CE-C9282E374813} 133 | {4AD95898-6A60-4B74-976A-80DD4BFCAFC5} = {62C62A44-4FCE-4B47-96CE-C9282E374813} 134 | {310165FD-B3CA-49FD-929D-9E8BABAF116B} = {62C62A44-4FCE-4B47-96CE-C9282E374813} 135 | {8C2BA2A6-9D4A-432D-B8B1-B07E0E01FB2C} = {310165FD-B3CA-49FD-929D-9E8BABAF116B} 136 | EndGlobalSection 137 | EndGlobal 138 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2019+ Monica S. 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /docs/README.md: -------------------------------------------------------------------------------- 1 | # Finite.Metrics # 2 | 3 | ![Build Status](https://github.com/FiniteReality/Finite.Metrics/workflows/Publish%20Finite.Metrics%20to%20MyGet/badge.svg?branch=main) 4 | [![Code Coverage](https://codecov.io/gh/FiniteReality/Finite.Metrics/branch/master/graph/badge.svg)](https://codecov.io/gh/FiniteReality/Finite.Metrics) 5 | 6 | 7 | A simple metrics library for .NET, written in the style of 8 | Microsoft.Extensions.Logging. 9 | 10 | Development packages can be found on my [MyGet] page. 11 | 12 | ## Why? ## 13 | 14 | I believe recording metrics should be simple and easy. No need for complicated 15 | configuration of individual options like units, reservoirs, histograms, et 16 | cetera. Those should all be left to the system which processes and displays the 17 | metrics. 18 | 19 | Originally, I was looking at [AppMetrics] as I didn't want to write a custom 20 | metrics solution for a project I was working on. However, its approach to 21 | metrics left me disillusioned, and my trusty $searchEngine-Fu wasn't revealing 22 | other options, so I decided that I unfortunately had to implement my own. 23 | 24 | At first, I was looking to implement the metrics solution as part of my normal 25 | logging, so that the "standard interfaces" would also track metrics, and 26 | additionally giving me the ability to easily add metrics to systems which did 27 | not normally have them with little effort. (Systems like IdentityServer4, 28 | Kestrel, and Entity Framework, where adding metrics is more of a tedious matter 29 | of finding the correct interfaces and plugging in the correct implementations.) 30 | 31 | However, this quickly turned into a mess, as I would have to manually map which 32 | log messages were metrics, and what properties to track, so on so forth. As 33 | such, I decided to start a new abstraction centered around a simple 34 | `Log(T value, TTags tags = null)` interface, which could be used to 35 | log any time-series value; even structured data, if your provider supported it. 36 | 37 | ## Examples ## 38 | 39 | ### Configuration ### 40 | ```cs 41 | namespace MyProject 42 | { 43 | public class Startup 44 | { 45 | public IConfiguration Configuration { get; } 46 | public IWebHostEnvironment Environment { get; } 47 | 48 | public Startup(IConfiguration configuration, 49 | IWebHostEnvironment environment) 50 | { 51 | Configuration = configuration; 52 | Environment = environment; 53 | } 54 | 55 | public void ConfigureServices(IServiceCollection services) 56 | { 57 | services.AddMetrics(builder => 58 | { 59 | if (environment.IsDevelopment()) 60 | builder.AddOtherProvider(); 61 | else 62 | builder.AddOpenTsdb(Configuration.GetConnectionString("OpenTSDB")); 63 | }); 64 | } 65 | } 66 | } 67 | ``` 68 | 69 | ### Consumption ### 70 | 71 | ```cs 72 | namespace MyProject 73 | { 74 | public class MyService 75 | { 76 | private readonly IMetric _userAdded; 77 | private readonly IMetric _userDeleted; 78 | 79 | public MyService(IMetricFactory metricFactory) 80 | { 81 | _userAdded = metricFactory.CreateMetric("service.user.add"); 82 | _userDeleted = metricFactory.CreateMetric("service.user.del"); 83 | } 84 | 85 | public async Task CreateUserAsync(string id, string name, string language) 86 | { 87 | using var timer = Measure.Duration(_userAdded, new{ 88 | language 89 | }); 90 | 91 | Database.Add(new SomeUser 92 | { 93 | Id = id, 94 | Name = name 95 | Language = language 96 | }); 97 | } 98 | 99 | public async Task DeleteUserAsync(SomeUser user) 100 | { 101 | using var timer = Measure.Duration(_userDeleted); 102 | Database.Delete(user); 103 | } 104 | } 105 | } 106 | ``` 107 | 108 | ## TODO / Contributing ## 109 | 110 | Please see [TODO] for more info. 111 | 112 | ## License ## 113 | 114 | MIT License. Copyright (C) 2019+ Monica S. See [LICENSE] for more info. 115 | 116 | [MyGet]: https://www.myget.org/feed/Packages/finitereality 117 | [AppMetrics]: https://www.app-metrics.io/ 118 | [TODO]: ./TODO.md 119 | [LICENSE]: ../LICENSE 120 | -------------------------------------------------------------------------------- /docs/TODO.md: -------------------------------------------------------------------------------- 1 | # TODO # 2 | - Unit tests 3 | - Other metrics providers (Prometheus, Graphite, ElasticSearch etc) 4 | - General code clean up and verification 5 | - Create the `Metric` helper class used in the examples in the README 6 | -------------------------------------------------------------------------------- /src/Abstractions/Finite.Metrics.Abstractions.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | net5.0 5 | 6 | Logging abstractions for Finite.Metrics 7 | 8 | 9 | 10 | -------------------------------------------------------------------------------- /src/Abstractions/IMetric.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | namespace Finite.Metrics 4 | { 5 | /// 6 | /// Represents a type used to record metrics. 7 | /// 8 | public interface IMetric 9 | { 10 | /// 11 | /// Checks if the given metric is enabled. 12 | /// 13 | /// 14 | /// true if enabled. 15 | /// 16 | bool IsEnabled(); 17 | 18 | /// 19 | /// Writes a metrics entry. 20 | /// 21 | /// 22 | /// The value that will be written. 23 | /// 24 | /// 25 | /// The additional tags to supply with this metric entry. 26 | /// 27 | /// 28 | /// The type of value to write. 29 | /// 30 | void Log(T value, TagValues? tags = null); 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /src/Abstractions/IMetricFactory.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | namespace Finite.Metrics 4 | { 5 | /// 6 | /// Represents a type used to configure the metrics system and create 7 | /// instances of form the registered 8 | /// s. 9 | /// 10 | public interface IMetricFactory : IDisposable 11 | { 12 | /// 13 | /// Creates a new instance. 14 | /// 15 | /// 16 | /// The name of metrics produced by the metric. 17 | /// 18 | /// 19 | /// The . 20 | /// 21 | IMetric CreateMetric(string metricName); 22 | 23 | /// 24 | /// Adds an to the metrics system. 25 | /// 26 | /// 27 | /// The . 28 | /// 29 | void AddProvider(IMetricProvider provider); 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /src/Abstractions/IMetricProvider.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | namespace Finite.Metrics 4 | { 5 | /// 6 | /// Represents a type that can create instances of . 7 | /// 8 | public interface IMetricProvider : IDisposable 9 | { 10 | /// 11 | /// Creates a new instance. 12 | /// 13 | /// 14 | /// The name for metrics produced by the metric. 15 | /// 16 | /// 17 | /// The instance of that was created. 18 | /// 19 | IMetric CreateMetric(string metricName); 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /src/Abstractions/MetricExtensions.cs: -------------------------------------------------------------------------------- 1 | namespace Finite.Metrics 2 | { 3 | /// 4 | /// Extension methods for for common scenarios. 5 | /// 6 | public static class MetricExtensions 7 | { 8 | /// 9 | /// Writes a metric entry. 10 | /// 11 | /// 12 | /// The to write to. 13 | /// 14 | /// 15 | /// The value that will be written. 16 | /// 17 | /// 18 | /// The tags that will be supplied with this metric entry. 19 | /// 20 | /// 21 | /// The type of value to write. 22 | /// 23 | /// 24 | /// The type of tags to supply with the metric. 25 | /// 26 | public static void Log(this IMetric metric, T value, 27 | TTags tags) 28 | where TTags : class 29 | => metric.Log(value, TagValues.CreateFrom(tags)); 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /src/Abstractions/TagValues.Properties.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Reflection; 4 | 5 | namespace Finite.Metrics 6 | { 7 | public partial class TagValues 8 | { 9 | private static class PropertiesHelper 10 | where T : class 11 | { 12 | private static readonly List<(string, Func)> Props 13 | = new List<(string, Func)>(); 14 | private static readonly MethodInfo GetValueFactoryMethod 15 | = typeof(PropertiesHelper).GetMethod( 16 | nameof(GetValueFactory), 17 | BindingFlags.NonPublic | BindingFlags.Static)!; 18 | 19 | static PropertiesHelper() 20 | { 21 | var props = typeof(T).GetProperties(); 22 | 23 | foreach (var prop in props) 24 | { 25 | if (prop.GetMethod is null) 26 | continue; 27 | 28 | var getMethod = GetValueFactoryMethod 29 | .MakeGenericMethod(new[] { prop.PropertyType }); 30 | var getter = (Func)getMethod 31 | .Invoke(null, new[] { prop.GetMethod })!; 32 | 33 | Props.Add((prop.Name, getter)); 34 | } 35 | } 36 | 37 | public static IEnumerable> GetProps( 38 | T value) 39 | { 40 | foreach (var prop in Props) 41 | { 42 | yield return KeyValuePair.Create( 43 | prop.Item1, prop.Item2(value)); 44 | } 45 | } 46 | 47 | private static Func GetValueFactory( 48 | MethodInfo getMethod) 49 | { 50 | var method = (Func)getMethod 51 | .CreateDelegate(typeof(Func)); 52 | 53 | return v => method(v); 54 | } 55 | } 56 | } 57 | } 58 | -------------------------------------------------------------------------------- /src/Abstractions/TagValues.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections; 3 | using System.Collections.Generic; 4 | 5 | namespace Finite.Metrics 6 | { 7 | /// 8 | /// Represents a collection of tag keys and values 9 | /// 10 | public partial class TagValues 11 | : IReadOnlyList> 12 | { 13 | private readonly List> _tags; 14 | 15 | private TagValues(List> tags) 16 | { 17 | _tags = tags; 18 | } 19 | 20 | /// 21 | /// Creates a new instance of from the given 22 | /// object. 23 | /// 24 | /// 25 | /// The value to convert to a collection of tag keys and values. 26 | /// 27 | /// 28 | /// The type of value to convert. 29 | /// 30 | /// 31 | /// A containing the data specified by 32 | /// . 33 | /// 34 | public static TagValues CreateFrom(T value) 35 | where T : class 36 | => new TagValues( 37 | new List>( 38 | PropertiesHelper.GetProps(value))); 39 | 40 | /// 41 | public KeyValuePair this[int index] 42 | => _tags[index]; 43 | 44 | /// 45 | public int Count 46 | => _tags.Count; 47 | 48 | /// 49 | public IEnumerator> GetEnumerator() 50 | => _tags.GetEnumerator(); 51 | 52 | /// 53 | IEnumerator IEnumerable.GetEnumerator() 54 | => ((IEnumerable)_tags).GetEnumerator(); 55 | } 56 | } 57 | -------------------------------------------------------------------------------- /src/Configuration/Finite.Metrics.Configuration.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | net5.0 5 | 6 | Configuration support for Finite.Metrics 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | -------------------------------------------------------------------------------- /src/Configuration/IMetricProviderConfiguration.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.Extensions.Configuration; 2 | 3 | namespace Finite.Metrics.Configuration 4 | { 5 | /// 6 | /// Allows access to the configuration section associated with a metrics 7 | /// provider. 8 | /// 9 | /// 10 | /// The type of metrics provider to get configuration for. 11 | /// 12 | public interface IMetricProviderConfiguration 13 | { 14 | /// 15 | /// Gets the configuration section for the requested metrics provider. 16 | /// 17 | IConfiguration Configuration { get; } 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /src/Configuration/IMetricProviderConfigurationFactory.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using Microsoft.Extensions.Configuration; 3 | 4 | namespace Finite.Metrics.Configuration 5 | { 6 | /// 7 | /// Allows access to the configuration section associated with a metrics 8 | /// provider. 9 | /// 10 | public interface IMetricProviderConfigurationFactory 11 | { 12 | /// 13 | /// Gets the configuration section associated with the passed metrics 14 | /// provider. 15 | /// 16 | /// 17 | /// The metrics provider type. 18 | /// 19 | /// 20 | /// The for the given 21 | /// . 22 | /// 23 | IConfiguration GetConfiguration( 24 | Type providerType); 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /src/Configuration/MetricProviderConfiguration.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.Extensions.Configuration; 2 | 3 | namespace Finite.Metrics.Configuration 4 | { 5 | internal class MetricProviderConfiguration 6 | : IMetricProviderConfiguration 7 | { 8 | public IConfiguration Configuration { get; } 9 | 10 | public MetricProviderConfiguration( 11 | IMetricProviderConfigurationFactory providerConfigurationFactory) 12 | { 13 | Configuration = providerConfigurationFactory 14 | .GetConfiguration(typeof(T)); 15 | } 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /src/Configuration/MetricProviderConfigurationFactory.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using Microsoft.Extensions.Configuration; 4 | 5 | namespace Finite.Metrics.Configuration 6 | { 7 | internal class MetricProviderConfigurationFactory 8 | : IMetricProviderConfigurationFactory 9 | { 10 | private readonly IEnumerable _configurations; 11 | 12 | public MetricProviderConfigurationFactory( 13 | IEnumerable configurations) 14 | { 15 | _configurations = configurations; 16 | } 17 | 18 | public IConfiguration GetConfiguration(Type providerType) 19 | { 20 | if (providerType is null) 21 | throw new ArgumentNullException(nameof(providerType)); 22 | 23 | var fullName = providerType.FullName; 24 | // TODO: provider alias support 25 | var configurationBuilder = new ConfigurationBuilder(); 26 | 27 | foreach (var configuration in _configurations) 28 | { 29 | var sectionFromFullName = configuration.Configuration 30 | .GetSection(fullName); 31 | 32 | _ = configurationBuilder.AddConfiguration(sectionFromFullName); 33 | } 34 | 35 | return configurationBuilder.Build(); 36 | } 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /src/Configuration/MetricProviderConfigureOptions.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.Extensions.Configuration; 2 | using Microsoft.Extensions.Options; 3 | 4 | namespace Finite.Metrics.Configuration 5 | { 6 | /// 7 | public class MetricProviderConfigureOptions 8 | : ConfigureFromConfigurationOptions 9 | where TOptions : class 10 | { 11 | /// 12 | public MetricProviderConfigureOptions( 13 | IMetricProviderConfiguration providerConfiguration) 14 | : base(providerConfiguration.Configuration) 15 | { 16 | } 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /src/Configuration/MetricProviderOptions.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.Extensions.DependencyInjection; 2 | using Microsoft.Extensions.DependencyInjection.Extensions; 3 | using Microsoft.Extensions.Options; 4 | 5 | namespace Finite.Metrics.Configuration 6 | { 7 | /// 8 | /// Provides a set of helpers to initialize options objects from metrics 9 | /// provider configuration. 10 | /// 11 | public static class MetricProviderOptions 12 | { 13 | /// 14 | /// Indicates that settings for should 15 | /// be loaded into . 16 | /// 17 | /// 18 | /// The to register options in. 19 | /// 20 | /// 21 | /// The options class 22 | /// 23 | /// 24 | /// The provider class 25 | /// 26 | public static void RegisterProviderOptions( 27 | IServiceCollection services) 28 | where TOptions : class 29 | { 30 | services.TryAddEnumerable(ServiceDescriptor.Singleton< 31 | IConfigureOptions, 32 | MetricProviderConfigureOptions>()); 33 | services.TryAddEnumerable(ServiceDescriptor.Singleton< 34 | IOptionsChangeTokenSource, 35 | MetricProviderOptionsChangeTokenSource>() 36 | ); 37 | } 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /src/Configuration/MetricProviderOptionsChangeTokenSource.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.Extensions.Configuration; 2 | using Microsoft.Extensions.Options; 3 | 4 | namespace Finite.Metrics.Configuration 5 | { 6 | /// 7 | public class MetricProviderOptionsChangeTokenSource 8 | : ConfigurationChangeTokenSource 9 | { 10 | /// 11 | public MetricProviderOptionsChangeTokenSource( 12 | IMetricProviderConfiguration providerConfiguration) 13 | : base(providerConfiguration.Configuration) 14 | { 15 | } 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /src/Configuration/MetricsBuilderConfigurationExtensions.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using Finite.Metrics.Configuration; 3 | using Microsoft.Extensions.Configuration; 4 | using Microsoft.Extensions.DependencyInjection; 5 | using Microsoft.Extensions.DependencyInjection.Extensions; 6 | 7 | namespace Finite.Metrics 8 | { 9 | /// 10 | /// Extension methods for setting up metrics services in an 11 | /// . 12 | /// 13 | public static class MetricsBuilderConfigurationExtensions 14 | { 15 | /// 16 | /// Adds services required to consume 17 | /// or 18 | /// 19 | /// 20 | /// 21 | /// The to register services on. 22 | /// 23 | /// 24 | /// The builder. 25 | /// 26 | public static IMetricsBuilder AddConfiguration( 27 | this IMetricsBuilder builder) 28 | { 29 | builder.Services 30 | .TryAddSingleton(); 32 | 33 | builder.Services.TryAddSingleton( 34 | typeof(IMetricProviderConfiguration<>), 35 | typeof(MetricProviderConfiguration<>)); 36 | 37 | return builder; 38 | } 39 | 40 | /// 41 | /// Configures an from an instance of 42 | /// . 43 | /// 44 | /// 45 | /// The to use. 46 | /// 47 | /// 48 | /// The to add. 49 | /// 50 | /// 51 | /// The builder. 52 | /// 53 | public static IMetricsBuilder AddConfiguration( 54 | this IMetricsBuilder builder, 55 | IConfiguration configuration) 56 | { 57 | _ = builder.AddConfiguration(); 58 | 59 | _ = builder.Services.AddSingleton( 60 | new MetricsConfiguration(configuration)); 61 | 62 | return builder; 63 | } 64 | } 65 | } 66 | -------------------------------------------------------------------------------- /src/Configuration/MetricsConfiguration.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.Extensions.Configuration; 2 | 3 | namespace Finite.Metrics.Configuration 4 | { 5 | internal class MetricsConfiguration 6 | { 7 | public IConfiguration Configuration { get; } 8 | 9 | public MetricsConfiguration(IConfiguration configuration) 10 | { 11 | Configuration = configuration; 12 | } 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /src/Core/Finite.Metrics.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | net5.0 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | -------------------------------------------------------------------------------- /src/Core/IMetricsBuilder.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using Microsoft.Extensions.DependencyInjection; 3 | 4 | namespace Finite.Metrics 5 | { 6 | /// 7 | /// An interface for configuring metrics providers. 8 | /// 9 | public interface IMetricsBuilder 10 | { 11 | /// 12 | /// Gets the where metrics services 13 | /// are configured. 14 | /// 15 | IServiceCollection Services { get; } 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /src/Core/Measure.Duration.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Diagnostics; 3 | 4 | namespace Finite.Metrics 5 | { 6 | /// 7 | /// Contains helper methods for , to make measuring 8 | /// certain metrics easier. 9 | /// 10 | public static partial class Measure 11 | { 12 | /// 13 | /// Measures a duration, starting at the method call, finishing when 14 | /// is called. 15 | /// 16 | /// 17 | /// The metric to store the result in. 18 | /// 19 | /// 20 | /// 21 | public static DurationMeasure Duration(IMetric metric) 22 | => new DurationMeasure(metric); 23 | 24 | /// 25 | /// Measures a duration, starting at the method call, finishing when 26 | /// is called. 27 | /// 28 | /// 29 | /// The metric to store the result in. 30 | /// 31 | /// 32 | /// The optional tags to tag this duration with. 33 | /// 34 | /// 35 | /// The type of the tags to tag this duration with. 36 | /// 37 | /// 38 | /// 39 | public static DurationMeasure Duration(IMetric metric, 40 | TTags tags) 41 | where TTags : class 42 | => new DurationMeasure(metric, tags); 43 | 44 | /// 45 | /// A duration measure for measuring durations using 46 | /// . 47 | /// 48 | public struct DurationMeasure : IDisposable 49 | { 50 | private readonly IMetric _metric; 51 | private readonly Stopwatch _timer; 52 | 53 | internal DurationMeasure(IMetric metric) 54 | { 55 | if (metric is null) 56 | throw new ArgumentNullException(nameof(metric)); 57 | 58 | _metric = metric; 59 | _timer = Stopwatch.StartNew(); 60 | } 61 | 62 | /// 63 | public void Dispose() 64 | { 65 | var time = _timer.Elapsed; 66 | _timer.Stop(); 67 | 68 | _metric.Log(time); 69 | } 70 | } 71 | 72 | /// 73 | /// A duration measure for measuring durations using 74 | /// . 75 | /// 76 | /// 77 | /// The type of the tags used to tag the duration with. 78 | /// 79 | public struct DurationMeasure : IDisposable 80 | where TTags : class 81 | { 82 | private readonly IMetric _metric; 83 | private readonly TTags _tags; 84 | private readonly Stopwatch _timer; 85 | 86 | internal DurationMeasure(IMetric metric, TTags tags) 87 | { 88 | if (metric is null) 89 | throw new ArgumentNullException(nameof(metric)); 90 | 91 | _metric = metric; 92 | _tags = tags; 93 | _timer = Stopwatch.StartNew(); 94 | } 95 | 96 | /// 97 | public void Dispose() 98 | { 99 | var time = _timer.Elapsed; 100 | _timer.Stop(); 101 | 102 | _metric.Log(time, _tags); 103 | } 104 | } 105 | } 106 | } 107 | -------------------------------------------------------------------------------- /src/Core/Metric.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | 4 | namespace Finite.Metrics 5 | { 6 | internal class Metric : IMetric 7 | { 8 | public IMetric[] Metrics { get; set; } = null!; 9 | 10 | public void Log(T value, TagValues? tags = null) 11 | { 12 | var metrics = Metrics; 13 | 14 | if (metrics == null || metrics.Length == 0) 15 | return; 16 | 17 | List? exceptions = null; 18 | for (var x = 0; x < metrics.Length; x++) 19 | { 20 | var metric = metrics[x]; 21 | 22 | if (!metric.IsEnabled()) 23 | continue; 24 | 25 | try 26 | { 27 | metric.Log(value, tags); 28 | } 29 | catch (Exception ex) 30 | { 31 | if (exceptions == null) 32 | exceptions = new List(); 33 | 34 | exceptions.Add(ex); 35 | } 36 | } 37 | 38 | if (exceptions != null) 39 | { 40 | throw new AggregateException( 41 | "An error occured while writing to metric(s):", 42 | exceptions); 43 | } 44 | } 45 | 46 | public bool IsEnabled() 47 | { 48 | var metrics = Metrics; 49 | 50 | if (metrics == null || metrics.Length == 0) 51 | return false; 52 | 53 | List? exceptions = null; 54 | for (var x = 0; x < metrics.Length; x++) 55 | { 56 | var metric = metrics[x]; 57 | 58 | try 59 | { 60 | if (metric.IsEnabled()) 61 | return true; 62 | } 63 | catch (Exception ex) 64 | { 65 | if (exceptions == null) 66 | exceptions = new List(); 67 | 68 | exceptions.Add(ex); 69 | } 70 | } 71 | 72 | return exceptions != null 73 | ? throw new AggregateException( 74 | "An error occured while writing to metric(s):", 75 | exceptions) 76 | : false; 77 | } 78 | } 79 | } 80 | -------------------------------------------------------------------------------- /src/Core/MetricFactory.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using Microsoft.Extensions.DependencyInjection; 5 | 6 | namespace Finite.Metrics 7 | { 8 | /// 9 | /// Produces instances of classes based on the given 10 | /// providers. 11 | /// 12 | public class MetricFactory : IMetricFactory 13 | { 14 | // internal for unit testing purposes 15 | internal readonly List _providers; 16 | 17 | /// 18 | /// Creates a new instance. 19 | /// 20 | /// 21 | /// The providers to use in producing instances. 22 | /// 23 | public MetricFactory(IEnumerable providers) 24 | { 25 | _providers = providers.ToList(); 26 | } 27 | 28 | /// 29 | /// Creates a new instance of configured 30 | /// using the provided delegate. 31 | /// 32 | /// 33 | /// A delegate to configure the . 34 | /// 35 | /// 36 | /// The that was created. 37 | /// 38 | public static IMetricFactory Create(Action configure) 39 | { 40 | var collection = new ServiceCollection(); 41 | _ = collection.AddMetrics(configure); 42 | var provider = collection.BuildServiceProvider(); 43 | 44 | var factory = provider.GetService(); 45 | 46 | return new DisposingMetricsFactory(factory, provider); 47 | } 48 | 49 | /// 50 | public void AddProvider(IMetricProvider provider) 51 | { 52 | if (provider is null) 53 | throw new ArgumentNullException(nameof(provider)); 54 | _providers.Add(provider); 55 | } 56 | 57 | /// 58 | public IMetric CreateMetric(string metricName) 59 | { 60 | var metrics = new IMetric[_providers.Count]; 61 | for (var i = 0; i < _providers.Count; i++) 62 | metrics[i] = _providers[i].CreateMetric(metricName); 63 | 64 | return new Metric() 65 | { 66 | Metrics = metrics 67 | }; 68 | } 69 | 70 | /// 71 | public void Dispose() 72 | { 73 | foreach (var provider in _providers) 74 | { 75 | try 76 | { 77 | provider.Dispose(); 78 | } 79 | catch 80 | { 81 | // swallow exceptions on dispose 82 | } 83 | } 84 | } 85 | 86 | private class DisposingMetricsFactory : IMetricFactory 87 | { 88 | private readonly IMetricFactory _factory; 89 | 90 | private readonly ServiceProvider _services; 91 | 92 | public DisposingMetricsFactory(IMetricFactory factory, 93 | ServiceProvider services) 94 | { 95 | _factory = factory; 96 | _services = services; 97 | } 98 | 99 | public void AddProvider(IMetricProvider provider) 100 | => _factory.AddProvider(provider); 101 | 102 | public IMetric CreateMetric(string metricName) 103 | => _factory.CreateMetric(metricName); 104 | 105 | public void Dispose() 106 | => _services.Dispose(); 107 | } 108 | } 109 | } 110 | -------------------------------------------------------------------------------- /src/Core/MetricsBuilder.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.Extensions.DependencyInjection; 2 | 3 | namespace Finite.Metrics 4 | { 5 | internal class MetricsBuilder : IMetricsBuilder 6 | { 7 | public MetricsBuilder(IServiceCollection services) 8 | { 9 | Services = services; 10 | } 11 | 12 | public IServiceCollection Services { get; } 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /src/Core/MetricsServiceCollectionExtensions.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using Finite.Metrics; 3 | using Microsoft.Extensions.DependencyInjection.Extensions; 4 | 5 | namespace Microsoft.Extensions.DependencyInjection 6 | { 7 | /// 8 | /// Extension methods for setting up metrics services in an 9 | /// . 10 | /// 11 | public static class MetricsServiceCollectionExtensions 12 | { 13 | /// 14 | /// Adds metrics services to the specified 15 | /// . 16 | /// 17 | /// 18 | /// The to add services to. 19 | /// 20 | /// 21 | /// The so that additional calls can 22 | /// be chained. 23 | /// 24 | public static IServiceCollection AddMetrics( 25 | this IServiceCollection services) 26 | => AddMetrics(services, builder => { }); 27 | 28 | 29 | /// 30 | /// Adds metrics services to the specified 31 | /// . 32 | /// 33 | /// 34 | /// The to add services to. 35 | /// 36 | /// 37 | /// The configuration delegate. 38 | /// 39 | /// 40 | /// The so that additional calls can 41 | /// be chained. 42 | /// 43 | public static IServiceCollection AddMetrics( 44 | this IServiceCollection services, 45 | Action configure) 46 | { 47 | if (services is null) 48 | throw new ArgumentNullException(nameof(services)); 49 | 50 | services.TryAdd(ServiceDescriptor 51 | .Singleton()); 52 | services.TryAdd(ServiceDescriptor.Singleton()); 53 | 54 | configure(new MetricsBuilder(services)); 55 | return services; 56 | } 57 | } 58 | } 59 | -------------------------------------------------------------------------------- /src/Directory.Build.props: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 14 | 15 | 16 | true 17 | $(MSBuildAllProjects);$(MSBuildThisFileDirectory)..\Directory.Build.props 18 | src 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | -------------------------------------------------------------------------------- /src/Directory.Build.targets: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 14 | 15 | 16 | $(MSBuildAllProjects);$(MSBuildThisFileDirectory)..\Directory.Build.targets 17 | 18 | 19 | 20 | 21 | 22 | $(IntermediateOutputPath)$(MSBuildProjectName).InternalsVisibleTo$(DefaultLanguageSourceExtension) 23 | 24 | 25 | 26 | 27 | false 28 | 29 | 30 | 31 | 35 | 36 | 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | 49 | 50 | 51 | 52 | 53 | 54 | -------------------------------------------------------------------------------- /src/Providers/OpenTsdb/DefaultSystemClock.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | namespace Finite.Metrics.OpenTsdb 4 | { 5 | internal class DefaultSystemClock : ISystemClock 6 | { 7 | public DateTimeOffset UtcNow => DateTimeOffset.UtcNow; 8 | } 9 | } 10 | -------------------------------------------------------------------------------- /src/Providers/OpenTsdb/Finite.Metrics.OpenTsdb.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | net5.0 5 | 6 | OpenTSDB metrics provider implementation for Finite.Metrics 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | -------------------------------------------------------------------------------- /src/Providers/OpenTsdb/ISystemClock.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | namespace Finite.Metrics.OpenTsdb 4 | { 5 | internal interface ISystemClock 6 | { 7 | DateTimeOffset UtcNow { get; } 8 | } 9 | } 10 | -------------------------------------------------------------------------------- /src/Providers/OpenTsdb/MetricsBuilderTsdbExtensions.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using Finite.Metrics.Configuration; 3 | using Finite.Metrics.OpenTsdb; 4 | using Microsoft.Extensions.DependencyInjection; 5 | using Microsoft.Extensions.DependencyInjection.Extensions; 6 | 7 | namespace Finite.Metrics 8 | { 9 | /// 10 | /// OpenTSDB extensions for . 11 | /// 12 | public static class MetricsBuilderOpenTsdbExtensions 13 | { 14 | /// 15 | /// Adds an OpenTSDB provider to the factory. 16 | /// 17 | /// 18 | /// The to use. 19 | /// 20 | /// 21 | /// The connection string to use when connecting to OpenTSDB. 22 | /// 23 | /// 24 | /// The , to allow for chaining. 25 | /// 26 | public static IMetricsBuilder AddOpenTsdb(this IMetricsBuilder builder, 27 | string connectionString) 28 | { 29 | if (connectionString is null) 30 | throw new ArgumentNullException(nameof(connectionString)); 31 | 32 | var baseAddress = new Uri(connectionString, UriKind.Absolute); 33 | 34 | _ = builder.AddConfiguration(); 35 | 36 | builder.Services.TryAddSingleton 37 | (); 38 | 39 | builder.Services.TryAddSingleton(); 40 | builder.Services.TryAddEnumerable(ServiceDescriptor 41 | .Singleton()); 42 | 43 | MetricProviderOptions.RegisterProviderOptions 44 | (builder.Services); 45 | 46 | _ = builder.Services.AddHostedService( 47 | services => services 48 | .GetRequiredService()); 49 | 50 | _ = builder.Services.AddHttpClient( 51 | OpenTsdbMetricsOptions.HttpClientName, 52 | (client) => client.BaseAddress = baseAddress); 53 | 54 | return builder; 55 | } 56 | 57 | /// 58 | /// Adds an OpenTSDB provider to the factory. 59 | /// 60 | /// 61 | /// The to use. 62 | /// 63 | /// 64 | /// The connection string to use when connecting to OpenTSDB. 65 | /// 66 | /// 67 | /// A delegate to congfigure the OpenTSDB provider. 68 | /// 69 | /// 70 | /// The , to allow for chaining. 71 | /// 72 | public static IMetricsBuilder AddOpenTsdb(this IMetricsBuilder builder, 73 | string connectionString, 74 | Action configure) 75 | { 76 | _ = builder.AddOpenTsdb(connectionString); 77 | _ = builder.Services.Configure(configure); 78 | 79 | return builder; 80 | } 81 | } 82 | } 83 | -------------------------------------------------------------------------------- /src/Providers/OpenTsdb/OpenTsdbMetricsOptions.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | 4 | namespace Finite.Metrics.OpenTsdb 5 | { 6 | /// 7 | /// Options used by the OpenTSDB metrics provider. 8 | /// 9 | public class OpenTsdbMetricsOptions 10 | { 11 | /// 12 | /// Gets the name of the HTTP client used by OpenTSDB. 13 | /// 14 | public static string HttpClientName 15 | => "OpenTSDB"; 16 | 17 | /// 18 | /// Gets or sets the interval to wait for between uploading metrics to 19 | /// OpenTSDB. 20 | /// 21 | public TimeSpan Interval { get; set; } = TimeSpan.FromSeconds(5); 22 | 23 | /// 24 | /// Gets or sets the endpoint used to upload metrics to OpenTSDB. 25 | /// 26 | public string UploadMetricsEndpoint { get; set; } = "/api/put"; 27 | 28 | /// 29 | /// Gets or sets the default tags to apply to metrics uploaded to 30 | /// OpenTSDB. 31 | /// 32 | public IDictionary DefaultTags { get; set; } 33 | = new Dictionary(); 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /src/Providers/OpenTsdb/TsdbMetric.cs: -------------------------------------------------------------------------------- 1 | using System.Collections.Generic; 2 | using System.Linq; 3 | 4 | namespace Finite.Metrics.OpenTsdb 5 | { 6 | internal class TsdbMetric : IMetric 7 | { 8 | private readonly string _name; 9 | private readonly TsdbMetricsUploader _uploader; 10 | 11 | public TsdbMetric(string name, TsdbMetricsUploader uploader) 12 | { 13 | _name = name; 14 | _uploader = uploader; 15 | } 16 | 17 | public bool IsEnabled() 18 | => true; 19 | 20 | public void Log(T value, TagValues? tags = null) 21 | => _uploader.AddLogEntry(new TsdbPutRequest 22 | { 23 | Metric = _name, 24 | Value = value!, 25 | Tags = tags?.ToDictionary(x => x.Key, x => x.Value) 26 | ?? new Dictionary() 27 | }); 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /src/Providers/OpenTsdb/TsdbMetricProvider.cs: -------------------------------------------------------------------------------- 1 | namespace Finite.Metrics.OpenTsdb 2 | { 3 | internal class TsdbMetricProvider : IMetricProvider 4 | { 5 | private readonly TsdbMetricsUploader _uploader; 6 | 7 | public TsdbMetricProvider(TsdbMetricsUploader uploader) 8 | { 9 | _uploader = uploader; 10 | } 11 | 12 | public IMetric CreateMetric(string name) 13 | => new TsdbMetric(name, _uploader); 14 | 15 | public void Dispose() 16 | { 17 | // no-op 18 | } 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /src/Providers/OpenTsdb/TsdbMetricsUploader.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Concurrent; 3 | using System.Collections.Generic; 4 | using System.Diagnostics.CodeAnalysis; 5 | using System.Linq; 6 | using System.Net; 7 | using System.Net.Http; 8 | using System.Net.Http.Json; 9 | using System.Threading; 10 | using System.Threading.Tasks; 11 | using Microsoft.Extensions.Hosting; 12 | using Microsoft.Extensions.Logging; 13 | using Microsoft.Extensions.Options; 14 | 15 | namespace Finite.Metrics.OpenTsdb 16 | { 17 | internal class TsdbMetricsUploader : BackgroundService, IAsyncDisposable 18 | { 19 | private readonly IHttpClientFactory _clientFactory; 20 | private readonly ILogger _logger; 21 | private readonly IOptionsMonitor _options; 22 | private readonly ISystemClock _systemClock; 23 | 24 | private readonly bool _hostFreeMode; 25 | 26 | private ConcurrentBag _lastLogs; 27 | private ConcurrentBag _logs; 28 | 29 | public TsdbMetricsUploader(IHttpClientFactory clientFactory, 30 | ILogger logger, 31 | IOptionsMonitor options, 32 | ISystemClock systemClock, 33 | IHost? host = null) 34 | : base() 35 | { 36 | _clientFactory = clientFactory; 37 | _logger = logger; 38 | _options = options; 39 | _systemClock = systemClock; 40 | 41 | _logs = new ConcurrentBag(); 42 | _lastLogs = new ConcurrentBag(); 43 | 44 | _hostFreeMode = host is null; 45 | 46 | if (_hostFreeMode) 47 | { 48 | _ = StartAsync(CancellationToken.None); 49 | } 50 | } 51 | 52 | public async ValueTask DisposeAsync() 53 | { 54 | if (!_hostFreeMode) 55 | return; 56 | 57 | try 58 | { 59 | await StopAsync(CancellationToken.None); 60 | } 61 | catch (OperationCanceledException) 62 | { /* no-op */ } 63 | } 64 | 65 | public void AddLogEntry(TsdbPutRequest request) 66 | { 67 | request.Timestamp = _systemClock.UtcNow.ToUnixTimeMilliseconds(); 68 | 69 | var defaultTags = _options.CurrentValue.DefaultTags; 70 | 71 | foreach (var pair in defaultTags) 72 | { 73 | _ = request.Tags.TryAdd(pair.Key, pair.Value); 74 | } 75 | 76 | if (!request.Tags.Any()) 77 | throw new InvalidOperationException( 78 | "Cannot upload a metric with no tags"); 79 | 80 | _logs.Add(request); 81 | } 82 | 83 | protected override async Task ExecuteAsync( 84 | CancellationToken stoppingToken) 85 | { 86 | while (true) 87 | { 88 | var options = _options.CurrentValue; 89 | await Task.Delay(options.Interval, stoppingToken); 90 | 91 | if (_logs.IsEmpty) 92 | continue; 93 | 94 | using var client = _clientFactory.CreateClient( 95 | OpenTsdbMetricsOptions.HttpClientName); 96 | 97 | var logs = Interlocked.Exchange(ref _logs, _lastLogs); 98 | 99 | var response = await client.PostAsJsonAsync( 100 | options.UploadMetricsEndpoint, 101 | value: logs.ToArray(), 102 | cancellationToken: stoppingToken); 103 | 104 | if (response.StatusCode != HttpStatusCode.NoContent) 105 | { 106 | var errors = await response.Content! 107 | .ReadFromJsonAsync( 108 | cancellationToken: stoppingToken); 109 | 110 | _logger.LogWarning( 111 | "Some metrics failed to upload: {success} " + 112 | "successful, {failed} failed.", 113 | errors.Successful, 114 | errors.Failed); 115 | } 116 | 117 | logs.Clear(); 118 | _lastLogs = logs; 119 | } 120 | } 121 | } 122 | } 123 | -------------------------------------------------------------------------------- /src/Providers/OpenTsdb/TsdbPutRequest.cs: -------------------------------------------------------------------------------- 1 | using System.Collections.Generic; 2 | using System.Text.Json.Serialization; 3 | 4 | namespace Finite.Metrics.OpenTsdb 5 | { 6 | internal struct TsdbPutRequest 7 | { 8 | [JsonPropertyName("metric")] 9 | public string Metric { get; set; } 10 | 11 | [JsonPropertyName("timestamp")] 12 | public long Timestamp { get; set; } 13 | 14 | [JsonPropertyName("value")] 15 | public object Value { get; set; } 16 | 17 | [JsonPropertyName("tags")] 18 | public IDictionary Tags { get; set; } 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /src/Providers/OpenTsdb/TsdbPutResponse.cs: -------------------------------------------------------------------------------- 1 | using System.Text.Json.Serialization; 2 | 3 | namespace Finite.Metrics.OpenTsdb 4 | { 5 | internal struct TsdbPutResponse 6 | { 7 | [JsonPropertyName("success")] 8 | public int Successful { get; set; } 9 | 10 | [JsonPropertyName("failed")] 11 | public int Failed { get; set; } 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /tests/Configuration/Finite.Metrics.Configuration.UnitTests.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | net5.0 5 | 6 | false 7 | 8 | [Finite.Metrics.Configuration]* 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | -------------------------------------------------------------------------------- /tests/Configuration/MetricProviderConfiguration.Tests.cs: -------------------------------------------------------------------------------- 1 | using System.Collections.Generic; 2 | using Microsoft.Extensions.Configuration; 3 | using NUnit.Framework; 4 | 5 | namespace Finite.Metrics.Configuration.UnitTests 6 | { 7 | /// 8 | /// Unit tests for 9 | /// 10 | public class MetricProviderConfigurationTests 11 | { 12 | /// 13 | /// Ensures that 14 | /// 15 | /// returns a populated instance of when 16 | /// it has a backing configuration. 17 | /// 18 | [Test] 19 | public void MetricProviderConfigurationHasSameConfiguration() 20 | { 21 | const string ExpectedConfigurationKey = "MyProperty"; 22 | const string ExpectedConfigurationValue = "OK"; 23 | 24 | var inputConfiguration = new ConfigurationBuilder() 25 | .AddInMemoryCollection(new[] 26 | { 27 | KeyValuePair.Create( 28 | $"{typeof(ThrowingOptions).FullName}:{ExpectedConfigurationKey}", 29 | ExpectedConfigurationValue) 30 | }) 31 | .Build(); 32 | 33 | var factory = new MetricProviderConfigurationFactory( 34 | new[] 35 | { 36 | new MetricsConfiguration(inputConfiguration) 37 | }); 38 | 39 | var outputConfiguration = factory.GetConfiguration( 40 | typeof(ThrowingOptions)); 41 | var value = outputConfiguration[ExpectedConfigurationKey]; 42 | 43 | var outputConfiguration2 = 44 | new MetricProviderConfiguration(factory) 45 | .Configuration; 46 | 47 | Assert.NotNull(outputConfiguration2); 48 | 49 | var value2 = outputConfiguration2[ExpectedConfigurationKey]; 50 | 51 | Assert.AreEqual(value, value2); 52 | } 53 | } 54 | } 55 | -------------------------------------------------------------------------------- /tests/Configuration/MetricProviderConfigurationFactory.Tests.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using Microsoft.Extensions.Configuration; 5 | using NUnit.Framework; 6 | 7 | namespace Finite.Metrics.Configuration.UnitTests 8 | { 9 | /// 10 | /// Unit tests for 11 | /// 12 | public class MetricProviderConfigurationFactoryTests 13 | { 14 | /// 15 | /// Ensures that 16 | /// throws an instance of when 17 | /// null is passed as a parameter, and that the exception's 18 | /// property was the expected 19 | /// parameter name. 20 | /// 21 | [Test] 22 | public void GetConfigurationThrowsArgumentNullException() 23 | { 24 | var factory = new MetricProviderConfigurationFactory( 25 | Array.Empty()); 26 | 27 | var method = factory.GetType().GetMethod("GetConfiguration")!; 28 | var parameter = method.GetParameters().First(); 29 | 30 | var ex = Assert.Throws( 31 | () => factory.GetConfiguration(null!)); 32 | 33 | Assert.AreEqual(parameter.Name, ex.ParamName); 34 | } 35 | 36 | /// 37 | /// Ensures that 38 | /// returns an instance of . 39 | /// 40 | [Test] 41 | public void GetConfigurationReturnsNonNull() 42 | { 43 | var factory = new MetricProviderConfigurationFactory( 44 | Array.Empty()); 45 | 46 | var config = factory.GetConfiguration(typeof(ThrowingOptions)); 47 | 48 | Assert.NotNull(config); 49 | } 50 | 51 | /// 52 | /// Ensures that 53 | /// returns an empty instance of when it 54 | /// has no backing configuration providers. 55 | /// 56 | [Test] 57 | public void GetConfigurationWithNoConfigurationReturnsEmpty() 58 | { 59 | var factory = new MetricProviderConfigurationFactory( 60 | Array.Empty()); 61 | 62 | var config = factory.GetConfiguration(typeof(ThrowingOptions)); 63 | 64 | Assert.IsEmpty(config.AsEnumerable()); 65 | } 66 | 67 | /// 68 | /// Ensures that 69 | /// returns a populated instance of when 70 | /// it has a backing configuration. 71 | /// 72 | [Test] 73 | public void GetConfigurationWithConfigurationReturnsNonEmpty() 74 | { 75 | const string ExpectedConfigurationKey = "MyProperty"; 76 | const string ExpectedConfigurationValue = "OK"; 77 | 78 | var inputConfiguration = new ConfigurationBuilder() 79 | .AddInMemoryCollection(new[] 80 | { 81 | KeyValuePair.Create( 82 | $"{typeof(ThrowingOptions).FullName}:{ExpectedConfigurationKey}", 83 | ExpectedConfigurationValue) 84 | }) 85 | .Build(); 86 | 87 | var factory = new MetricProviderConfigurationFactory( 88 | new[] 89 | { 90 | new MetricsConfiguration(inputConfiguration) 91 | }); 92 | 93 | var outputConfiguration = factory.GetConfiguration( 94 | typeof(ThrowingOptions)); 95 | var value = outputConfiguration[ExpectedConfigurationKey]; 96 | 97 | Assert.AreEqual(ExpectedConfigurationValue, value); 98 | } 99 | } 100 | } 101 | -------------------------------------------------------------------------------- /tests/Configuration/MetricProviderConfigureOptions.Tests.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using NUnit.Framework; 3 | 4 | namespace Finite.Metrics.Configuration.UnitTests 5 | { 6 | /// 7 | /// Unit tests for 8 | /// 9 | /// 10 | public class MetricProviderConfigureOptionsTests 11 | { 12 | /// 13 | /// Ensures that 14 | /// 15 | /// can be constructed. 16 | /// 17 | [Test] 18 | public void MetricProviderConfigureOptionsCanBeConstructed() 19 | { 20 | Assert.DoesNotThrow(() => 21 | { 22 | var factory = new MetricProviderConfigurationFactory( 23 | Array.Empty()); 24 | var configuration = new MetricProviderConfiguration< 25 | ThrowingProvider>(factory); 26 | var options = new MetricProviderConfigureOptions< 27 | ThrowingOptions, ThrowingProvider>(configuration); 28 | }); 29 | } 30 | 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /tests/Configuration/MetricProviderOptions.Tests.cs: -------------------------------------------------------------------------------- 1 | using System.Linq; 2 | using Microsoft.Extensions.DependencyInjection; 3 | using Microsoft.Extensions.Options; 4 | using NUnit.Framework; 5 | 6 | namespace Finite.Metrics.Configuration.UnitTests 7 | { 8 | /// 9 | /// Unit tests for 10 | /// 11 | public class MetricProviderOptionsTests 12 | { 13 | /// 14 | /// Ensures that 15 | /// adds the required services to the service collection. 16 | /// 17 | [Test] 18 | public static void RegisterProviderOptionsAddsRequiredServices() 19 | { 20 | var services = new ServiceCollection(); 21 | 22 | MetricProviderOptions 23 | .RegisterProviderOptions( 24 | services); 25 | 26 | var hasConfigureOptions = services.Any( 27 | x => x.ServiceType == typeof( 28 | IConfigureOptions)); 29 | var hasChangeTokenSource = services.Any( 30 | x => x.ServiceType == typeof( 31 | IOptionsChangeTokenSource)); 32 | 33 | Assert.True(hasConfigureOptions); 34 | Assert.True(hasChangeTokenSource); 35 | } 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /tests/Configuration/MetricProviderOptionsChangeTokenSource.Tests.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using NUnit.Framework; 3 | 4 | namespace Finite.Metrics.Configuration.UnitTests 5 | { 6 | /// 7 | /// Unit tests for 8 | /// 9 | /// 10 | public class MetricProviderOptionsChangeTokenSourceTests 11 | { 12 | /// 13 | /// Ensures that 14 | /// 15 | /// can be constructed. 16 | /// 17 | [Test] 18 | public void MetricProviderOptionsChangeTokenSourceCanBeConstructed() 19 | { 20 | Assert.DoesNotThrow(() => 21 | { 22 | var factory = new MetricProviderConfigurationFactory( 23 | Array.Empty()); 24 | var configuration = new MetricProviderConfiguration< 25 | ThrowingProvider>(factory); 26 | var cts = new MetricProviderOptionsChangeTokenSource< 27 | ThrowingOptions, ThrowingProvider>(configuration); 28 | }); 29 | } 30 | 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /tests/Configuration/MetricsBuilderConfigurationExtensions.Tests.cs: -------------------------------------------------------------------------------- 1 | using System.Linq; 2 | using Finite.Metrics; 3 | using Finite.Metrics.Configuration; 4 | using Microsoft.Extensions.Configuration; 5 | using Microsoft.Extensions.DependencyInjection; 6 | using NUnit.Framework; 7 | 8 | namespace Finite.Metrics.Configuration.UnitTests 9 | { 10 | /// 11 | /// Unit tests for 12 | /// 13 | public class MetricsBuilderConfigurationExtensionsTests 14 | { 15 | /// 16 | /// Ensures that 17 | /// adds the required configuration services to 18 | /// . 19 | /// 20 | [Test] 21 | public void AddConfigurationAddsConfigurationServices() 22 | { 23 | var services = new ServiceCollection(); 24 | var builder = new MetricsBuilder(services); 25 | 26 | _ = builder.AddConfiguration(); 27 | 28 | var hasProviderConfigFactory = services.Any( 29 | x => x.ServiceType == 30 | typeof(IMetricProviderConfigurationFactory)); 31 | var hasProviderConfiguration = services.Any( 32 | x => x.ServiceType == typeof(IMetricProviderConfiguration<>)); 33 | 34 | Assert.True(hasProviderConfigFactory); 35 | Assert.True(hasProviderConfiguration); 36 | } 37 | 38 | /// 39 | /// Ensures that 40 | /// adds a instance, whose 41 | /// property equals 42 | /// the configuration we passed to AddConfiguration. 43 | /// 44 | [Test] 45 | public void AddConfigurationWithConfigAddsConfigurationServices() 46 | { 47 | var services = new ServiceCollection(); 48 | var builder = new MetricsBuilder(services); 49 | var configuration = new ConfigurationBuilder().Build(); 50 | 51 | _ = builder.AddConfiguration(configuration); 52 | 53 | var metricsConfigurationDescriptor = services.SingleOrDefault( 54 | x => x.ServiceType == typeof(MetricsConfiguration)); 55 | 56 | Assert.NotNull(metricsConfigurationDescriptor); 57 | 58 | var metricsConfiguration = (MetricsConfiguration) 59 | metricsConfigurationDescriptor!.ImplementationInstance; 60 | 61 | Assert.AreEqual(configuration, metricsConfiguration.Configuration); 62 | } 63 | } 64 | } 65 | -------------------------------------------------------------------------------- /tests/Configuration/ThrowingOptions.cs: -------------------------------------------------------------------------------- 1 | namespace Finite.Metrics.Configuration.UnitTests 2 | { 3 | internal class ThrowingOptions 4 | { 5 | 6 | } 7 | } 8 | -------------------------------------------------------------------------------- /tests/Configuration/ThrowingProvider.cs: -------------------------------------------------------------------------------- 1 | namespace Finite.Metrics.Configuration.UnitTests 2 | { 3 | internal class ThrowingProvider 4 | { 5 | 6 | } 7 | } 8 | -------------------------------------------------------------------------------- /tests/Core/DisabledAndThrowingMetric.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | namespace Finite.Metrics.UnitTests 4 | { 5 | /// 6 | /// A metric which is disabled, and whose Log method throws. 7 | /// 8 | internal class DisabledAndThrowingMetric : IMetric 9 | { 10 | public DisabledAndThrowingMetric() 11 | { } 12 | 13 | public bool IsEnabled() 14 | => false; 15 | 16 | public void Log(T value, TagValues? tags = null) 17 | => throw new NotImplementedException(); 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /tests/Core/EnabledButThrowingMetric.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | namespace Finite.Metrics.UnitTests 4 | { 5 | /// 6 | /// A metric which is enabled, but whose Log method throws. 7 | /// 8 | internal class EnabledButThrowingMetric : IMetric 9 | { 10 | public EnabledButThrowingMetric() 11 | { } 12 | 13 | public bool IsEnabled() 14 | => true; 15 | 16 | public void Log(T value, TagValues? tags = null) 17 | => throw new NotImplementedException(); 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /tests/Core/EnabledNonThrowingMetric.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | namespace Finite.Metrics.UnitTests 4 | { 5 | /// 6 | /// A metric which is enabled, and whose Log methods do not throw. 7 | /// 8 | internal class EnabledNonThrowingMetric : IMetric 9 | { 10 | public EnabledNonThrowingMetric() 11 | { } 12 | 13 | public bool IsEnabled() 14 | => true; 15 | 16 | public void Log(T value, TagValues? tags = null) 17 | { } 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /tests/Core/Finite.Metrics.UnitTests.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | net5.0 5 | 6 | false 7 | 8 | [Finite.Metrics]* 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | -------------------------------------------------------------------------------- /tests/Core/Measure.Duration.Tests.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Linq; 3 | using NUnit.Framework; 4 | 5 | namespace Finite.Metrics.UnitTests 6 | { 7 | /// 8 | /// Unit tests for 9 | /// /// 10 | public partial class MeasureTests 11 | { 12 | /// 13 | /// Ensures that throws an 14 | /// instance of when null 15 | /// is passed as a parameter, and that the exception's 16 | /// propery was the expected 17 | /// parameter name. 18 | /// 19 | [Test] 20 | public void MeasureDurationNoTagsThrowsForNullParameter() 21 | { 22 | var method = typeof(Measure).GetMethod("Duration", 23 | new[]{ typeof(IMetric) })!; 24 | var parameter = method.GetParameters().First(); 25 | 26 | var ex = Assert.Throws( 27 | () => Measure.Duration(null!)); 28 | 29 | Assert.AreEqual(parameter.Name, ex.ParamName); 30 | } 31 | 32 | /// 33 | /// Ensures that returns an 34 | /// instance of 35 | /// 36 | [Test] 37 | public void MeasureDurationNoTagsReturnsDurationMeasure() 38 | { 39 | _ = Measure.Duration(new EnabledNonThrowingMetric()); 40 | 41 | // If the method returned successfully, then it can only be an 42 | // instance of DurationMeasure, since DurationMeasure is a struct. 43 | Assert.Pass(); 44 | } 45 | 46 | /// 47 | /// Ensures that returns an 48 | /// object which can be disposed. 49 | /// 50 | [Test] 51 | public void MeasureDurationNoTagsCanBeDisposed() 52 | { 53 | using var x = Measure.Duration(new EnabledNonThrowingMetric()); 54 | 55 | // This code will fail to compile if the returned value cannot be 56 | // dispoed (i.e. not IDisposable or does not have a Dispose method) 57 | Assert.Pass(); 58 | } 59 | 60 | /// 61 | /// Ensures that 62 | /// throws an instance of when 63 | /// null is passed as a parameter, and that the exception's 64 | /// propery was the expected 65 | /// parameter name. 66 | /// 67 | [Test] 68 | public void MeasureDurationWithTagsThrowsForNullParameter() 69 | { 70 | var method = typeof(Measure).GetMethod("Duration", 71 | new[]{ typeof(IMetric) })!; 72 | var parameter = method.GetParameters().First(); 73 | 74 | var ex = Assert.Throws( 75 | () => Measure.Duration(null!, new object())); 76 | 77 | Assert.AreEqual(parameter.Name, ex.ParamName); 78 | } 79 | 80 | /// 81 | /// Ensures that 82 | /// returns an instance of 83 | /// 84 | [Test] 85 | public void MeasureDurationWithTagsReturnsDurationMeasure() 86 | { 87 | _ = Measure.Duration(new EnabledNonThrowingMetric(), new object()); 88 | 89 | // If the method returned successfully, then it can only be an 90 | // instance of DurationMeasure, since DurationMeasure is a struct. 91 | Assert.Pass(); 92 | } 93 | 94 | /// 95 | /// Ensures that 96 | /// returns an object which can be disposed. 97 | /// 98 | [Test] 99 | public void MeasureDurationWithTagsCanBeDisposed() 100 | { 101 | using var x = Measure.Duration(new EnabledNonThrowingMetric(), 102 | new object()); 103 | 104 | // This code will fail to compile if the returned value cannot be 105 | // dispoed (i.e. not IDisposable or does not have a Dispose method) 106 | Assert.Pass(); 107 | } 108 | } 109 | } 110 | -------------------------------------------------------------------------------- /tests/Core/Metric.Tests.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using NUnit.Framework; 3 | 4 | namespace Finite.Metrics.UnitTests 5 | { 6 | /// 7 | /// Unit tests for . 8 | /// 9 | public class MetricTests 10 | { 11 | /// 12 | /// Ensures that returns false when no 13 | /// provider metrics are present. 14 | /// 15 | [Test] 16 | public void IsEnabledReturnsFalseForNoMetrics() 17 | { 18 | var metric = new Metric(); 19 | 20 | Assert.False(metric.IsEnabled()); // metric.Metrics = null 21 | 22 | metric.Metrics = Array.Empty(); 23 | 24 | Assert.False(metric.IsEnabled()); // metric.Metrics.Length == 0 25 | } 26 | 27 | /// 28 | /// Ensures that returns true when a 29 | /// provider metric is present and enabled. 30 | /// 31 | [Test] 32 | public void IsEnabledReturnsTrueForEnabledMetric() 33 | { 34 | var metric = new Metric 35 | { 36 | Metrics = new[] { new EnabledButThrowingMetric() } 37 | }; 38 | 39 | Assert.True(metric.IsEnabled()); 40 | } 41 | 42 | /// 43 | /// Ensures that returns false when all 44 | /// provider metrics are disabled. 45 | /// 46 | [Test] 47 | public void IsEnabledReturnsFalseForDisabledMetrics() 48 | { 49 | var metric = new Metric 50 | { 51 | Metrics = new[] { new DisabledAndThrowingMetric() } 52 | }; 53 | 54 | Assert.False(metric.IsEnabled()); 55 | } 56 | 57 | 58 | /// 59 | /// Ensures that throws an instance of 60 | /// if any of the metrics throw, and 61 | /// that the thrown exception contains all of the correct exceptions. 62 | /// 63 | [Test] 64 | public void IsEnabledThrowsAggregateException() 65 | { 66 | var metric = new Metric 67 | { 68 | Metrics = new[] { new ThrowingMetric() } 69 | }; 70 | 71 | var exception = Assert.Throws( 72 | () => metric.IsEnabled()); 73 | 74 | Assert.AreEqual(1, exception.InnerExceptions.Count); 75 | Assert.IsInstanceOf( 76 | exception.InnerExceptions[0]); 77 | } 78 | 79 | /// 80 | /// Ensures that and 81 | /// do 82 | /// nothing when no provider metrics are present. 83 | /// 84 | [Test] 85 | public void LogWithNoMetricsIsIgnored() 86 | { 87 | var metric = new Metric(); 88 | 89 | // metric.Metrics == null 90 | Assert.DoesNotThrow(() => metric.Log(1)); 91 | Assert.DoesNotThrow(() => metric.Log(1, metric)); 92 | 93 | // metric.Metrics.Length == 0 94 | metric.Metrics = Array.Empty(); 95 | 96 | Assert.DoesNotThrow(() => metric.Log(1)); 97 | Assert.DoesNotThrow(() => metric.Log(1, metric)); 98 | } 99 | 100 | /// 101 | /// Ensures that and 102 | /// do 103 | /// nothing when returns false. 104 | /// 105 | [Test] 106 | public void LogWhenDisabledIsIgnored() 107 | { 108 | var metric = new Metric 109 | { 110 | Metrics = new[] { new DisabledAndThrowingMetric() } 111 | }; 112 | 113 | Assert.DoesNotThrow(() => metric.Log(1)); 114 | Assert.DoesNotThrow(() => metric.Log(1, metric)); 115 | } 116 | 117 | /// 118 | /// Ensures that and 119 | /// 120 | /// throws an instance of if any of 121 | /// the metrics throw, and that the thrown exception contains all of 122 | /// the correct exceptions. 123 | /// 124 | [Test] 125 | public void LogWhenEnabledThrowsAggregateException() 126 | { 127 | var metric = new Metric 128 | { 129 | Metrics = new[] { new EnabledButThrowingMetric() } 130 | }; 131 | 132 | var exception = Assert.Throws( 133 | () => metric.Log(1)); 134 | 135 | Assert.AreEqual(1, exception.InnerExceptions.Count); 136 | Assert.IsInstanceOf( 137 | exception.InnerExceptions[0]); 138 | 139 | exception = Assert.Throws( 140 | () => metric.Log(1, metric)); 141 | 142 | Assert.AreEqual(1, exception.InnerExceptions.Count); 143 | Assert.IsInstanceOf( 144 | exception.InnerExceptions[0]); 145 | } 146 | 147 | /// 148 | /// Ensures that and 149 | /// 150 | /// does not throw when all provider metrics return successfully. 151 | /// 152 | [Test] 153 | public void LogDoesNotThrow() 154 | { 155 | var metric = new Metric() 156 | { 157 | Metrics = new[] { new EnabledNonThrowingMetric() } 158 | }; 159 | 160 | Assert.DoesNotThrow(() => metric.Log(1)); 161 | Assert.DoesNotThrow(() => metric.Log(1, metric)); 162 | } 163 | } 164 | } 165 | -------------------------------------------------------------------------------- /tests/Core/MetricFactory.Tests.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Linq; 3 | using Microsoft.Extensions.DependencyInjection; 4 | using NUnit.Framework; 5 | 6 | namespace Finite.Metrics.UnitTests 7 | { 8 | /// 9 | /// Unit tests for 10 | /// 11 | public class MetricFactoryTests 12 | { 13 | /// 14 | /// Ensures that 15 | /// 16 | /// calls the delegate parameter passed. 17 | /// 18 | [Test] 19 | public void CreateCallsDelegate() 20 | { 21 | _ = MetricFactory.Create(_ => Assert.Pass()); 22 | 23 | Assert.Fail(); 24 | } 25 | 26 | /// 27 | /// Ensures that 28 | /// 29 | /// returns an instance of . 30 | /// 31 | [Test] 32 | public void CreateReturnsNonNull() 33 | => Assert.NotNull(MetricFactory.Create(_ => { })); 34 | 35 | /// 36 | /// Ensures that 37 | /// 38 | /// returns an instance of , whose methods 39 | /// do not throw. 40 | /// 41 | [Test] 42 | public void CreateReturnsSafeFactory() 43 | { 44 | var factory = MetricFactory.Create(_ => { }); 45 | 46 | Assert.DoesNotThrow( 47 | () => factory.AddProvider(new NonThrowingMetricProvider())); 48 | Assert.DoesNotThrow( 49 | () => factory.CreateMetric("test")); 50 | Assert.DoesNotThrow( 51 | () => factory.Dispose()); 52 | } 53 | 54 | /// 55 | /// Ensures that 56 | /// populates the internal list of providers with the given enumerable. 57 | /// 58 | [Test] 59 | public void ConstructorPopulatesInternalProviderList() 60 | { 61 | var factory = new MetricFactory(new[]{ 62 | new ThrowingMetricProvider() 63 | }); 64 | 65 | Assert.IsNotEmpty(factory._providers); 66 | } 67 | 68 | /// 69 | /// Ensures that 70 | /// throws an 71 | /// throws an instance of when 72 | /// null is passed as a parameter, and that the exception's 73 | /// property was the expected 74 | /// parameter name. 75 | /// 76 | [Test] 77 | public void AddProviderThrowsArgumentNullException() 78 | { 79 | var factory = new MetricFactory(Array.Empty()); 80 | 81 | var method = factory.GetType().GetMethod("AddProvider")!; 82 | var parameter = method.GetParameters().First(); 83 | 84 | var ex = Assert.Throws( 85 | () => factory.AddProvider(null!)); 86 | 87 | Assert.AreEqual(parameter.Name, ex.ParamName); 88 | } 89 | 90 | /// 91 | /// Ensures that 92 | /// adds a 93 | /// provider to the internal list of providers. 94 | /// 95 | [Test] 96 | public void AddProviderPopulatesInternalProviderList() 97 | { 98 | var factory = new MetricFactory(Array.Empty()); 99 | 100 | factory.AddProvider(new ThrowingMetricProvider()); 101 | 102 | Assert.IsNotEmpty(factory._providers); 103 | } 104 | 105 | /// 106 | /// Ensures that swallows 107 | /// exceptions from providers which erroneously throw on Dispose. 108 | /// 109 | [Test] 110 | public void DisposeSwallowsExceptions() 111 | { 112 | var factory = new MetricFactory(new IMetricProvider[]{ 113 | new NonThrowingMetricProvider(), 114 | new ThrowingMetricProvider() 115 | }); 116 | 117 | Assert.DoesNotThrow(() => factory.Dispose()); 118 | } 119 | 120 | /// 121 | /// Ensures that can safely be 122 | /// called multiple times. 123 | /// 124 | [Test] 125 | public void DisposeCanBeCalledMultipleTimes() 126 | { 127 | var factory = new MetricFactory(Array.Empty()); 128 | 129 | factory.Dispose(); 130 | 131 | Assert.DoesNotThrow(() => factory.Dispose()); 132 | } 133 | 134 | /// 135 | /// Ensures that 136 | /// returns an instance of . 137 | /// 138 | [Test] 139 | public void CreateMetricReturnsNonNull() 140 | { 141 | var factory = new MetricFactory(Array.Empty()); 142 | 143 | Assert.NotNull(factory.CreateMetric("A name")); 144 | } 145 | 146 | /// 147 | /// Ensures that 148 | /// returns an instance of whose 149 | /// property is non-empty. 150 | /// 151 | [Test] 152 | public void CreateMetricReturnsNonEmptyMetric() 153 | { 154 | var factory = new MetricFactory(new[] 155 | { 156 | new NonThrowingMetricProvider() 157 | }); 158 | 159 | var metric = factory.CreateMetric("A name") as Metric; 160 | 161 | Assert.NotNull(metric); 162 | Assert.IsNotEmpty(metric!.Metrics); 163 | } 164 | } 165 | } 166 | -------------------------------------------------------------------------------- /tests/Core/MetricsServiceCollectionExtensions.Tests.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Linq; 3 | using Microsoft.Extensions.DependencyInjection; 4 | using NUnit.Framework; 5 | 6 | namespace Finite.Metrics.UnitTests 7 | { 8 | /// 9 | /// Unit tests for 10 | /// 11 | public class MetricsServiceCollectionExtensionsTests 12 | { 13 | /// 14 | /// Ensures that 15 | /// throws an instance of when 16 | /// null is passed as a parameter, and that the exception's 17 | /// property was the expected 18 | /// parameter name. 19 | /// 20 | [Test] 21 | public void AddMetricsThrowsForNullServiceCollection() 22 | { 23 | var method = typeof(MetricsServiceCollectionExtensions) 24 | .GetMethod("AddMetrics", new[] 25 | { 26 | typeof(IServiceCollection), 27 | typeof(Action) 28 | })!; 29 | var parameter = method.GetParameters().First(); 30 | 31 | var ex = Assert.Throws( 32 | () => MetricsServiceCollectionExtensions.AddMetrics(null!)); 33 | 34 | Assert.AreEqual(parameter.Name, ex.ParamName); 35 | } 36 | 37 | /// 38 | /// Ensures the correct metrics services have been added to the service 39 | /// collection when using the 40 | /// method. 41 | /// 42 | [Test] 43 | public void MetricsServicesAreAddedToCollection() 44 | { 45 | var collection = new ServiceCollection(); 46 | 47 | _ = collection.AddMetrics(); 48 | 49 | var hasIMetricFactory = collection.Any( 50 | x => x.ServiceType == typeof(IMetricFactory)); 51 | var hasIMetric = collection.Any( 52 | x => x.ServiceType == typeof(IMetric)); 53 | 54 | Assert.True(hasIMetricFactory); 55 | Assert.True(hasIMetric); 56 | } 57 | 58 | /// 59 | /// Ensures that the 60 | /// method can be called multiple times without throwing exceptions. 61 | /// 62 | [Test] 63 | public void MetricsServicesCanBeAddedMultipleTimes() 64 | { 65 | var collection = new ServiceCollection(); 66 | 67 | _ = collection.AddMetrics(); 68 | 69 | Assert.DoesNotThrow(() => collection.AddMetrics()); 70 | } 71 | 72 | /// 73 | /// Ensures that the 74 | /// method calls the passed delegate. 75 | /// 76 | [Test] 77 | public void AddMetricsWithDelegateCallsDelegate() 78 | { 79 | var collection = new ServiceCollection(); 80 | 81 | _ = collection.AddMetrics(_ => Assert.Pass()); 82 | 83 | Assert.Fail(); 84 | } 85 | 86 | /// 87 | /// Ensures that the 88 | /// method calls the passed delegate with an instance of 89 | /// . 90 | /// 91 | [Test] 92 | public void AddMetricsWithDelegatePassedIMetricsBuilder() 93 | { 94 | var collection = new ServiceCollection(); 95 | 96 | _ = collection.AddMetrics(builder => Assert.NotNull(builder)); 97 | } 98 | 99 | /// 100 | /// Ensures that the 101 | /// method calls the passed delegate with an instance of 102 | /// , whose 103 | /// property equals the 104 | /// container we called AddMetrics on. 105 | /// 106 | [Test] 107 | public void AddMetricsWithDelegateHasSameContainer() 108 | { 109 | var collection = new ServiceCollection(); 110 | 111 | _ = collection.AddMetrics( 112 | builder => Assert.AreEqual(collection, builder.Services)); 113 | } 114 | } 115 | } 116 | -------------------------------------------------------------------------------- /tests/Core/NonThrowingMetricProvider.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | namespace Finite.Metrics.UnitTests 4 | { 5 | internal class NonThrowingMetricProvider : IMetricProvider 6 | { 7 | public IMetric CreateMetric(string metricName) 8 | => new EnabledNonThrowingMetric(); 9 | 10 | public void Dispose() 11 | { } 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /tests/Core/ThrowingMetric.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | namespace Finite.Metrics.UnitTests 4 | { 5 | /// 6 | /// A metric whose methods all throw. 7 | /// 8 | internal class ThrowingMetric : IMetric 9 | { 10 | public ThrowingMetric() 11 | { } 12 | 13 | public bool IsEnabled() 14 | => throw new NotImplementedException(); 15 | 16 | public void Log(T value, TagValues? tags = null) 17 | => throw new NotImplementedException(); 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /tests/Core/ThrowingMetricProvider.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | namespace Finite.Metrics.UnitTests 4 | { 5 | internal class ThrowingMetricProvider : IMetricProvider 6 | { 7 | public IMetric CreateMetric(string metricName) 8 | => throw new NotImplementedException(); 9 | 10 | public void Dispose() 11 | => throw new NotImplementedException(); 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /tests/Directory.Build.props: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 14 | 15 | 16 | true 17 | $(MSBuildAllProjects);$(MSBuildThisFileDirectory)..\Directory.Build.props 18 | tests 19 | 20 | 21 | 22 | 23 | 24 | 25 | $(BaseArtifactsPath)coverage/$(MSBuildProjectName).xml 26 | opencover 27 | true 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | -------------------------------------------------------------------------------- /tests/Directory.Build.targets: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 14 | 15 | 16 | $(MSBuildAllProjects);$(MSBuildThisFileDirectory)..\Directory.Build.targets 17 | 18 | 19 | 20 | 21 | 22 | $(IntermediateOutputPath)$(MSBuildProjectName).InternalsVisibleTo$(DefaultLanguageSourceExtension) 23 | 24 | 25 | 26 | 27 | false 28 | 29 | 30 | 31 | 35 | 36 | 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | 49 | 50 | 51 | 52 | 53 | 54 | -------------------------------------------------------------------------------- /tests/Providers/OpenTsdb/DummyHttpMessageHandler.cs: -------------------------------------------------------------------------------- 1 | using System.Net.Http; 2 | using System.Threading; 3 | using System.Threading.Tasks; 4 | 5 | namespace Finite.Metrics.OpenTsdb.UnitTests 6 | { 7 | internal class DummyHttpMessageHandler : HttpMessageHandler 8 | { 9 | private TaskCompletionSource? _mostRecentResponse; 10 | 11 | public HttpRequestMessage? MostRecentMessage { get; private set; } 12 | 13 | public DummyHttpMessageHandler() 14 | { } 15 | 16 | protected override Task SendAsync( 17 | HttpRequestMessage request, 18 | CancellationToken cancellationToken) 19 | { 20 | MostRecentMessage = request; 21 | 22 | _mostRecentResponse = 23 | new TaskCompletionSource(); 24 | 25 | return _mostRecentResponse.Task; 26 | } 27 | 28 | public void RespondToMostRecentMessage(HttpResponseMessage message) 29 | { 30 | if (_mostRecentResponse is null) 31 | return; 32 | 33 | _ = _mostRecentResponse.TrySetResult(message); 34 | } 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /tests/Providers/OpenTsdb/Finite.Metrics.OpenTsdb.UnitTests.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | net5.0 5 | 6 | false 7 | 8 | [Finite.Metrics.OpenTsdb]* 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | -------------------------------------------------------------------------------- /tests/Providers/OpenTsdb/MetricsBuilderTsdbExtensions.Tests.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Linq; 3 | using System.Net.Http; 4 | using Finite.Metrics.Configuration; 5 | using Microsoft.Extensions.DependencyInjection; 6 | using Microsoft.Extensions.Hosting; 7 | using NUnit.Framework; 8 | 9 | namespace Finite.Metrics.OpenTsdb.UnitTests 10 | { 11 | /// 12 | /// Unit tests for 13 | /// 14 | public class MetricsBuilderTsdbExtensionsTests 15 | { 16 | /// 17 | /// Ensures that 18 | /// throws an instance of when an 19 | /// invalid connection string has been passed, and also ensures that it 20 | /// throws an instance of when 21 | /// null is passed. 22 | /// 23 | [Test] 24 | public void AddOpenTsdbInvalidConnectionStringThrows() 25 | { 26 | var services = new ServiceCollection(); 27 | var builder = new MetricsBuilder(services); 28 | 29 | _ = Assert.Throws( 30 | () => _ = builder.AddOpenTsdb("invalid uri text")); 31 | 32 | _ = Assert.Throws( 33 | () => _ = builder.AddOpenTsdb(null!)); 34 | } 35 | 36 | /// 37 | /// Ensures that 38 | /// adds the required OpenTSDB services to 39 | /// . 40 | /// 41 | [Test] 42 | public void AddOpenTsdbAddsTsdbServices() 43 | { 44 | var services = new ServiceCollection(); 45 | var builder = new MetricsBuilder(services); 46 | 47 | _ = builder.AddOpenTsdb("http://localhost/"); 48 | 49 | var hasConfiguration = services.Any( 50 | x => x.ServiceType 51 | == typeof(IMetricProviderConfigurationFactory)); 52 | var hasMetricsUploader = services.Any( 53 | x => x.ImplementationType == typeof(TsdbMetricsUploader)); 54 | var hasMetricProvider = services.Any( 55 | x => x.ImplementationType == typeof(TsdbMetricProvider)); 56 | var hasHostedService = services.Any( 57 | x => x.ServiceType == typeof(IHostedService)); 58 | var hasHttpClientFactory = services.Any( 59 | x => x.ServiceType == typeof(IHttpClientFactory)); 60 | 61 | Assert.True(hasConfiguration); 62 | Assert.True(hasMetricsUploader); 63 | Assert.True(hasMetricProvider); 64 | Assert.True(hasHostedService); 65 | Assert.True(hasHttpClientFactory); 66 | } 67 | 68 | /// 69 | /// Ensures that 70 | /// throws an instance of when an 71 | /// invalid connection string has been passed, and also ensures that it 72 | /// throws an instance of when 73 | /// null is passed. 74 | /// 75 | [Test] 76 | public void AddOpenTsdbConfigurationInvalidConnectionStringThrows() 77 | { 78 | var services = new ServiceCollection(); 79 | var builder = new MetricsBuilder(services); 80 | 81 | _ = Assert.Throws( 82 | () => _ = builder.AddOpenTsdb("invalid uri text", 83 | options => { })); 84 | 85 | _ = Assert.Throws( 86 | () => _ = builder.AddOpenTsdb(null!)); 87 | } 88 | 89 | /// 90 | /// Ensures that 91 | /// adds the required OpenTSDB services to 92 | /// . 93 | /// 94 | [Test] 95 | public void AddOpenTsdbConfigurationAddsTsdbServices() 96 | { 97 | var services = new ServiceCollection(); 98 | var builder = new MetricsBuilder(services); 99 | 100 | _ = builder.AddOpenTsdb("http://localhost/", 101 | options => { }); 102 | 103 | var hasConfiguration = services.Any( 104 | x => x.ServiceType 105 | == typeof(IMetricProviderConfigurationFactory)); 106 | var hasMetricsUploader = services.Any( 107 | x => x.ImplementationType == typeof(TsdbMetricsUploader)); 108 | var hasMetricProvider = services.Any( 109 | x => x.ImplementationType == typeof(TsdbMetricProvider)); 110 | var hasHostedService = services.Any( 111 | x => x.ServiceType == typeof(IHostedService)); 112 | var hasHttpClientFactory = services.Any( 113 | x => x.ServiceType == typeof(IHttpClientFactory)); 114 | 115 | Assert.True(hasConfiguration); 116 | Assert.True(hasMetricsUploader); 117 | Assert.True(hasMetricProvider); 118 | Assert.True(hasHostedService); 119 | Assert.True(hasHttpClientFactory); 120 | } 121 | } 122 | } 123 | -------------------------------------------------------------------------------- /tests/Providers/OpenTsdb/OpenTsdbProvider.Tests.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Net; 3 | using System.Net.Http; 4 | using System.Net.Http.Json; 5 | using System.Threading.Tasks; 6 | using Microsoft.Extensions.DependencyInjection; 7 | using NUnit.Framework; 8 | 9 | namespace Finite.Metrics.OpenTsdb.UnitTests 10 | { 11 | /// 12 | /// End-to-end tests for the OpenTSDB metrics provider. 13 | /// 14 | public class OpenTsdbProviderTests 15 | { 16 | private DummyHttpMessageHandler _httpHandler = null!; 17 | private IMetricFactory _factory = null!; 18 | 19 | /// 20 | /// Setup for end-to-end test 21 | /// 22 | [SetUp] 23 | public void Setup() 24 | { 25 | _httpHandler = new DummyHttpMessageHandler(); 26 | 27 | _factory = MetricFactory.Create(builder => 28 | { 29 | _ = builder.Services.AddSingleton 30 | (); 31 | 32 | _ = builder.Services.AddHttpClient( 33 | OpenTsdbMetricsOptions.HttpClientName) 34 | .ConfigurePrimaryHttpMessageHandler( 35 | () => _httpHandler); 36 | 37 | _ = builder.AddOpenTsdb("http://localhost/", 38 | options => 39 | { 40 | options.Interval = TimeSpan.FromSeconds(0.5); 41 | 42 | options.DefaultTags["Latency"] = "0.5"; 43 | }); 44 | }); 45 | } 46 | 47 | /// 48 | /// Teardown from end-to-end test 49 | /// 50 | [TearDown] 51 | public void TearDown() 52 | { 53 | _factory.Dispose(); 54 | _httpHandler.Dispose(); 55 | } 56 | 57 | /// 58 | /// Ensures that logging a metric with tags correctly grabs the tags. 59 | /// 60 | [Test] 61 | public async Task LogWithTagsAsync() 62 | { 63 | var metric = _factory.CreateMetric("endtoend"); 64 | metric.Log(1, new { HostName = "woah" }); 65 | 66 | await Task.Delay(TimeSpan.FromSeconds(1.5)); 67 | 68 | Assert.NotNull(_httpHandler.MostRecentMessage); 69 | 70 | var request = _httpHandler.MostRecentMessage!; 71 | 72 | Assert.AreEqual(HttpMethod.Post, request.Method); 73 | Assert.IsInstanceOf(request.Content); 74 | 75 | var content = (JsonContent)request.Content!; 76 | var text = await content.ReadAsStringAsync(); 77 | 78 | // TODO: this should be fuzzy; HostName and Latency may be swapped 79 | Assert.AreEqual( 80 | @"[{""metric"":""endtoend"",""timestamp"":0,""value"":1,""tags"":{""HostName"":""woah"",""Latency"":""0.5""}}]", 81 | text); 82 | } 83 | 84 | /// 85 | /// Ensures that logging a metric without metrics correctly applies the 86 | /// default tags. 87 | /// 88 | [Test] 89 | public async Task LogWithoutTagsAsync() 90 | { 91 | var metric = _factory.CreateMetric("endtoend"); 92 | metric.Log(1); 93 | 94 | await Task.Delay(TimeSpan.FromSeconds(1.5)); 95 | 96 | Assert.NotNull(_httpHandler.MostRecentMessage); 97 | 98 | var request = _httpHandler.MostRecentMessage!; 99 | 100 | Assert.AreEqual(HttpMethod.Post, request.Method); 101 | Assert.IsInstanceOf(request.Content); 102 | 103 | var content = (JsonContent)request.Content!; 104 | var text = await content.ReadAsStringAsync(); 105 | 106 | Assert.AreEqual( 107 | @"[{""metric"":""endtoend"",""timestamp"":0,""value"":1,""tags"":{""Latency"":""0.5""}}]", 108 | text); 109 | } 110 | } 111 | } 112 | -------------------------------------------------------------------------------- /tests/Providers/OpenTsdb/TestSystemClock.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | namespace Finite.Metrics.OpenTsdb.UnitTests 4 | { 5 | internal class TestSystemClock : ISystemClock 6 | { 7 | public DateTimeOffset UtcNow => DateTimeOffset.UnixEpoch; 8 | } 9 | } 10 | --------------------------------------------------------------------------------