Repository: opentracing-contrib/csharp-netcore Branch: master Commit: f64af79ae582 Files: 165 Total size: 272.2 KB Directory structure: gitextract_0r5cqphu/ ├── .appveyor.yml ├── .editorconfig ├── .gitattributes ├── .gitignore ├── .travis.yml ├── .vscode/ │ ├── extensions.json │ ├── settings.json │ └── tasks.json ├── Directory.Build.props ├── LICENSE ├── NuGet.config ├── OpenTracing.Contrib.sln ├── README.md ├── RELEASE.md ├── SignKey.snk ├── benchmarks/ │ └── OpenTracing.Contrib.NetCore.Benchmarks/ │ ├── AspNetCore/ │ │ └── RequestDiagnosticsBenchmark.cs │ ├── CoreFx/ │ │ └── HttpHandlerDiagnosticsBenchmark.cs │ ├── InstrumentationMode.cs │ ├── OpenTracing.Contrib.NetCore.Benchmarks.csproj │ ├── OpenTracingBuilderExtensions.cs │ └── Program.cs ├── build.ps1 ├── global.json ├── launch-sample.ps1 ├── samples/ │ ├── net6.0/ │ │ ├── CustomersApi/ │ │ │ ├── Controllers/ │ │ │ │ └── CustomersController.cs │ │ │ ├── CustomersApi.csproj │ │ │ ├── DataStore/ │ │ │ │ └── CustomerDbContext.cs │ │ │ ├── Program.cs │ │ │ ├── Properties/ │ │ │ │ └── launchSettings.json │ │ │ ├── Startup.cs │ │ │ └── appsettings.json │ │ ├── FrontendWeb/ │ │ │ ├── Controllers/ │ │ │ │ └── HomeController.cs │ │ │ ├── FrontendWeb.csproj │ │ │ ├── Program.cs │ │ │ ├── Properties/ │ │ │ │ └── launchSettings.json │ │ │ ├── Startup.cs │ │ │ ├── Views/ │ │ │ │ ├── Home/ │ │ │ │ │ ├── Index.cshtml │ │ │ │ │ └── PlaceOrder.cshtml │ │ │ │ └── _ViewImports.cshtml │ │ │ └── appsettings.json │ │ ├── OrdersApi/ │ │ │ ├── Controllers/ │ │ │ │ └── OrdersController.cs │ │ │ ├── DataStore/ │ │ │ │ ├── Order.cs │ │ │ │ └── OrdersDbContext.cs │ │ │ ├── OrdersApi.csproj │ │ │ ├── Program.cs │ │ │ ├── Properties/ │ │ │ │ └── launchSettings.json │ │ │ ├── Startup.cs │ │ │ └── appsettings.json │ │ ├── Shared/ │ │ │ ├── Constants.cs │ │ │ ├── Customer.cs │ │ │ ├── JaegerServiceCollectionExtensions.cs │ │ │ ├── PlaceOrderCommand.cs │ │ │ └── Shared.csproj │ │ └── TrafficGenerator/ │ │ ├── Program.cs │ │ ├── TrafficGenerator.csproj │ │ ├── Worker.cs │ │ └── appsettings.json │ ├── net7.0/ │ │ ├── CustomersApi/ │ │ │ ├── CustomersApi.csproj │ │ │ ├── DataStore/ │ │ │ │ └── CustomerDbContext.cs │ │ │ ├── Program.cs │ │ │ ├── Properties/ │ │ │ │ └── launchSettings.json │ │ │ └── appsettings.json │ │ ├── FrontendWeb/ │ │ │ ├── Controllers/ │ │ │ │ └── HomeController.cs │ │ │ ├── FrontendWeb.csproj │ │ │ ├── Program.cs │ │ │ ├── Properties/ │ │ │ │ └── launchSettings.json │ │ │ ├── Views/ │ │ │ │ ├── Home/ │ │ │ │ │ ├── Index.cshtml │ │ │ │ │ └── PlaceOrder.cshtml │ │ │ │ └── _ViewImports.cshtml │ │ │ └── appsettings.json │ │ ├── OrdersApi/ │ │ │ ├── Controllers/ │ │ │ │ └── OrdersController.cs │ │ │ ├── DataStore/ │ │ │ │ ├── Order.cs │ │ │ │ └── OrdersDbContext.cs │ │ │ ├── OrdersApi.csproj │ │ │ ├── Program.cs │ │ │ ├── Properties/ │ │ │ │ └── launchSettings.json │ │ │ └── appsettings.json │ │ ├── Shared/ │ │ │ ├── Constants.cs │ │ │ ├── Customer.cs │ │ │ ├── JaegerServiceCollectionExtensions.cs │ │ │ ├── PlaceOrderCommand.cs │ │ │ └── Shared.csproj │ │ └── TrafficGenerator/ │ │ ├── Program.cs │ │ ├── TrafficGenerator.csproj │ │ ├── Worker.cs │ │ └── appsettings.json │ └── netcoreapp3.1/ │ ├── CustomersApi/ │ │ ├── Controllers/ │ │ │ └── CustomersController.cs │ │ ├── CustomersApi.csproj │ │ ├── DataStore/ │ │ │ └── CustomerDbContext.cs │ │ ├── Program.cs │ │ ├── Properties/ │ │ │ └── launchSettings.json │ │ ├── Startup.cs │ │ └── appsettings.json │ ├── FrontendWeb/ │ │ ├── Controllers/ │ │ │ └── HomeController.cs │ │ ├── FrontendWeb.csproj │ │ ├── Program.cs │ │ ├── Properties/ │ │ │ └── launchSettings.json │ │ ├── Startup.cs │ │ ├── Views/ │ │ │ ├── Home/ │ │ │ │ ├── Index.cshtml │ │ │ │ └── PlaceOrder.cshtml │ │ │ └── _ViewImports.cshtml │ │ └── appsettings.json │ ├── OrdersApi/ │ │ ├── Controllers/ │ │ │ └── OrdersController.cs │ │ ├── DataStore/ │ │ │ ├── Order.cs │ │ │ └── OrdersDbContext.cs │ │ ├── OrdersApi.csproj │ │ ├── Program.cs │ │ ├── Properties/ │ │ │ └── launchSettings.json │ │ ├── Startup.cs │ │ └── appsettings.json │ ├── Shared/ │ │ ├── Constants.cs │ │ ├── Customer.cs │ │ ├── JaegerServiceCollectionExtensions.cs │ │ ├── PlaceOrderCommand.cs │ │ └── Shared.csproj │ └── TrafficGenerator/ │ ├── Program.cs │ ├── TrafficGenerator.csproj │ ├── Worker.cs │ └── appsettings.json ├── src/ │ ├── Directory.Build.props │ └── OpenTracing.Contrib.NetCore/ │ ├── AspNetCore/ │ │ ├── AspNetCoreDiagnosticOptions.cs │ │ ├── AspNetCoreDiagnostics.cs │ │ ├── HostingOptions.cs │ │ └── RequestHeadersExtractAdapter.cs │ ├── Configuration/ │ │ ├── DiagnosticOptions.cs │ │ ├── IOpenTracingBuilder.cs │ │ ├── OpenTracingBuilder.cs │ │ ├── OpenTracingBuilderExtensions.cs │ │ └── ServiceCollectionExtensions.cs │ ├── EntityFrameworkCore/ │ │ ├── EntityFrameworkCoreDiagnosticOptions.cs │ │ └── EntityFrameworkCoreDiagnostics.cs │ ├── GenericListeners/ │ │ ├── GenericDiagnosticOptions.cs │ │ └── GenericDiagnostics.cs │ ├── HttpHandler/ │ │ ├── HttpHandlerDiagnosticOptions.cs │ │ ├── HttpHandlerDiagnostics.cs │ │ └── HttpHeadersInjectAdapter.cs │ ├── InstrumentationService.cs │ ├── Internal/ │ │ ├── DiagnosticEventObserver.cs │ │ ├── DiagnosticManager.cs │ │ ├── DiagnosticManagerOptions.cs │ │ ├── DiagnosticObserver.cs │ │ ├── GenericEventProcessor.cs │ │ ├── GlobalTracerAccessor.cs │ │ ├── IGlobalTracerAccessor.cs │ │ ├── PropertyFetcher.cs │ │ ├── SpanExtensions.cs │ │ └── TracerExtensions.cs │ ├── Logging/ │ │ ├── OpenTracingLogger.cs │ │ └── OpenTracingLoggerProvider.cs │ ├── MicrosoftSqlClient/ │ │ ├── MicrosoftSqlClientDiagnosticOptions.cs │ │ └── MicrosoftSqlClientDiagnostics.cs │ ├── OpenTracing.Contrib.NetCore.csproj │ ├── Properties/ │ │ └── AssemblyInfo.cs │ └── SystemSqlClient/ │ ├── SqlClientDiagnosticOptions.cs │ └── SqlClientDiagnostics.cs ├── test/ │ └── OpenTracing.Contrib.NetCore.Tests/ │ ├── AspNetCore/ │ │ └── HostingTest.cs │ ├── CoreFx/ │ │ └── HttpHandlerDiagnosticTest.cs │ ├── Internal/ │ │ ├── DiagnosticManagerTest.cs │ │ └── PropertyFetcherTest.cs │ ├── Logging/ │ │ ├── LoggingDependencyInjectionTest.cs │ │ └── LoggingTest.cs │ ├── OpenTracing.Contrib.NetCore.Tests.csproj │ └── XunitLogging/ │ ├── XunitLoggerFactoryExtensions.cs │ └── XunitLoggerProvider.cs └── version.props ================================================ FILE CONTENTS ================================================ ================================================ FILE: .appveyor.yml ================================================ # AppVeyor Build number is incremental and not related to actual version number of the product version: '{build}' image: Visual Studio 2019 init: - cmd: git config --global core.autocrlf true environment: global: DOTNET_SKIP_FIRST_TIME_EXPERIENCE: true DOTNET_CLI_TELEMETRY_OPTOUT: 1 build_script: - ps: Invoke-WebRequest https://dot.net/v1/dotnet-install.ps1 -OutFile .\dotnet-install.ps1 - ps: .\dotnet-install.ps1 -Runtime dotnet -Version 3.1.10 - ps: .\dotnet-install.ps1 -Version 6.0.100 - ps: .\dotnet-install.ps1 -Version 7.0.100 - ps: .\build.ps1 test: off artifacts: - path: artifacts\nuget\*.nupkg name: NuGet - path: artifacts\nuget\*.snupkg name: Symbols # Deploy every successful build (except PRs) to development feed nuget: account_feed: true project_feed: true disable_publish_on_pr: true ================================================ FILE: .editorconfig ================================================ # editorconfig.org # top-most EditorConfig file root = true # Default settings: # A newline ending every file # Use 4 spaces as indentation [*] insert_final_newline = true indent_style = space indent_size = 4 [project.json] indent_size = 2 # C# files [*.cs] # New line preferences csharp_new_line_before_open_brace = all csharp_new_line_before_else = true csharp_new_line_before_catch = true csharp_new_line_before_finally = true csharp_new_line_before_members_in_object_initializers = true csharp_new_line_before_members_in_anonymous_types = true csharp_new_line_between_query_expression_clauses = true # Indentation preferences csharp_indent_block_contents = true csharp_indent_braces = false csharp_indent_case_contents = true csharp_indent_switch_labels = true csharp_indent_labels = flush_left # avoid this. unless absolutely necessary dotnet_style_qualification_for_field = false:suggestion dotnet_style_qualification_for_property = false:suggestion dotnet_style_qualification_for_method = false:suggestion dotnet_style_qualification_for_event = false:suggestion # only use var when it's obvious what the variable type is csharp_style_var_for_built_in_types = false:none csharp_style_var_when_type_is_apparent = false:none csharp_style_var_elsewhere = false:suggestion # use language keywords instead of BCL types dotnet_style_predefined_type_for_locals_parameters_members = true:suggestion dotnet_style_predefined_type_for_member_access = true:suggestion # name all constant fields using PascalCase dotnet_naming_rule.constant_fields_should_be_pascal_case.severity = suggestion dotnet_naming_rule.constant_fields_should_be_pascal_case.symbols = constant_fields dotnet_naming_rule.constant_fields_should_be_pascal_case.style = pascal_case_style dotnet_naming_symbols.constant_fields.applicable_kinds = field dotnet_naming_symbols.constant_fields.required_modifiers = const dotnet_naming_style.pascal_case_style.capitalization = pascal_case # static fields should have s_ prefix dotnet_naming_rule.static_fields_should_have_prefix.severity = suggestion dotnet_naming_rule.static_fields_should_have_prefix.symbols = static_fields dotnet_naming_rule.static_fields_should_have_prefix.style = static_prefix_style dotnet_naming_symbols.static_fields.applicable_kinds = field dotnet_naming_symbols.static_fields.required_modifiers = static dotnet_naming_style.static_prefix_style.required_prefix = s_ dotnet_naming_style.static_prefix_style.capitalization = camel_case # internal and private fields should be _camelCase dotnet_naming_rule.camel_case_for_private_internal_fields.severity = suggestion dotnet_naming_rule.camel_case_for_private_internal_fields.symbols = private_internal_fields dotnet_naming_rule.camel_case_for_private_internal_fields.style = camel_case_underscore_style dotnet_naming_symbols.private_internal_fields.applicable_kinds = field dotnet_naming_symbols.private_internal_fields.applicable_accessibilities = private, internal dotnet_naming_style.camel_case_underscore_style.required_prefix = _ dotnet_naming_style.camel_case_underscore_style.capitalization = camel_case # Code style defaults dotnet_sort_system_directives_first = true csharp_preserve_single_line_blocks = true csharp_preserve_single_line_statements = false # Expression-level preferences dotnet_style_object_initializer = true:suggestion dotnet_style_collection_initializer = true:suggestion dotnet_style_explicit_tuple_names = true:suggestion dotnet_style_coalesce_expression = true:suggestion dotnet_style_null_propagation = true:suggestion # Expression-bodied members csharp_style_expression_bodied_methods = false:none csharp_style_expression_bodied_constructors = false:none csharp_style_expression_bodied_operators = false:none csharp_style_expression_bodied_properties = true:none csharp_style_expression_bodied_indexers = true:none csharp_style_expression_bodied_accessors = true:none # Pattern matching csharp_style_pattern_matching_over_is_with_cast_check = true:suggestion csharp_style_pattern_matching_over_as_with_null_check = true:suggestion csharp_style_inlined_variable_declaration = true:suggestion # Null checking preferences csharp_style_throw_expression = true:suggestion csharp_style_conditional_delegate_call = true:suggestion # Space preferences csharp_space_after_cast = false csharp_space_after_colon_in_inheritance_clause = true csharp_space_after_comma = true csharp_space_after_dot = false csharp_space_after_keywords_in_control_flow_statements = true csharp_space_after_semicolon_in_for_statement = true csharp_space_around_binary_operators = before_and_after csharp_space_around_declaration_statements = do_not_ignore csharp_space_before_colon_in_inheritance_clause = true csharp_space_before_comma = false csharp_space_before_dot = false csharp_space_before_open_square_brackets = false csharp_space_before_semicolon_in_for_statement = false csharp_space_between_empty_square_brackets = false csharp_space_between_method_call_empty_parameter_list_parentheses = false csharp_space_between_method_call_name_and_opening_parenthesis = false csharp_space_between_method_call_parameter_list_parentheses = false csharp_space_between_method_declaration_empty_parameter_list_parentheses = false csharp_space_between_method_declaration_name_and_open_parenthesis = false csharp_space_between_method_declaration_parameter_list_parentheses = false csharp_space_between_parentheses = false csharp_space_between_square_brackets = false # C++ Files [*.{cpp,h,in}] curly_bracket_next_line = true indent_brace_style = Allman # Xml project files [*.{csproj,vcxproj,vcxproj.filters,proj,nativeproj,locproj}] indent_size = 2 # Xml build files [*.builds] indent_size = 2 # Xml files [*.{xml,stylecop,resx,ruleset}] indent_size = 2 # Xml config files [*.{props,targets,config,nuspec}] indent_size = 2 # Shell scripts [*.sh] end_of_line = lf [*.{cmd, bat}] end_of_line = crlf ================================================ FILE: .gitattributes ================================================ * text=auto ================================================ FILE: .gitignore ================================================ # Sqlite DBs in samples *.db ## Ignore Visual Studio temporary files, build results, and ## files generated by popular Visual Studio add-ons. BenchmarkDotNet.Artifacts/ # User-specific files *.suo *.user *.userosscache *.sln.docstates # User-specific files (MonoDevelop/Xamarin Studio) *.userprefs # Build results [Dd]ebug/ [Dd]ebugPublic/ [Rr]elease/ [Rr]eleases/ x64/ x86/ bld/ [Bb]in/ [Oo]bj/ [Ll]og/ # Visual Studio 2015 cache/options directory .vs/ # Uncomment if you have tasks that create the project's static files in wwwroot #wwwroot/ # MSTest test Results [Tt]est[Rr]esult*/ [Bb]uild[Ll]og.* # NUNIT *.VisualState.xml TestResult.xml # Build Results of an ATL Project [Dd]ebugPS/ [Rr]eleasePS/ dlldata.c # DNX project.lock.json artifacts/ .build/ *_i.c *_p.c *_i.h *.ilk *.meta *.obj *.pch *.pdb *.pgc *.pgd *.rsp *.sbr *.tlb *.tli *.tlh *.tmp *.tmp_proj *.log *.vspscc *.vssscc .builds *.pidb *.svclog *.scc # Chutzpah Test files _Chutzpah* # Visual C++ cache files ipch/ *.aps *.ncb *.opendb *.opensdf *.sdf *.cachefile *.VC.db *.VC.VC.opendb # Visual Studio profiler *.psess *.vsp *.vspx *.sap # TFS 2012 Local Workspace $tf/ # Guidance Automation Toolkit *.gpState # ReSharper is a .NET coding add-in _ReSharper*/ *.[Rr]e[Ss]harper *.DotSettings.user # JustCode is a .NET coding add-in .JustCode # TeamCity is a build add-in _TeamCity* # DotCover is a Code Coverage Tool *.dotCover # NCrunch _NCrunch_* .*crunch*.local.xml nCrunchTemp_* # MightyMoose *.mm.* AutoTest.Net/ # Web workbench (sass) .sass-cache/ # Installshield output folder [Ee]xpress/ # DocProject is a documentation generator add-in DocProject/buildhelp/ DocProject/Help/*.HxT DocProject/Help/*.HxC DocProject/Help/*.hhc DocProject/Help/*.hhk DocProject/Help/*.hhp DocProject/Help/Html2 DocProject/Help/html # Click-Once directory publish/ # Publish Web Output *.[Pp]ublish.xml *.azurePubxml # TODO: Comment the next line if you want to checkin your web deploy settings # but database connection strings (with potential passwords) will be unencrypted *.pubxml *.publishproj # Microsoft Azure Web App publish settings. Comment the next line if you want to # checkin your Azure Web App publish settings, but sensitive information contained # in these scripts will be unencrypted PublishScripts/ # NuGet Packages *.nupkg # The packages folder can be ignored because of Package Restore **/packages/* # except build/, which is used as an MSBuild target. !**/packages/build/ # Uncomment if necessary however generally it will be regenerated when needed #!**/packages/repositories.config # NuGet v3's project.json files produces more ignoreable files *.nuget.props *.nuget.targets # Microsoft Azure Build Output csx/ *.build.csdef # Microsoft Azure Emulator ecf/ rcf/ # Windows Store app package directories and files AppPackages/ BundleArtifacts/ Package.StoreAssociation.xml _pkginfo.txt # Visual Studio cache files # files ending in .cache can be ignored *.[Cc]ache # but keep track of directories ending in .cache !*.[Cc]ache/ # Others ClientBin/ ~$* *~ *.dbmdl *.dbproj.schemaview *.pfx *.publishsettings node_modules/ orleans.codegen.cs # Since there are multiple workflows, uncomment next line to ignore bower_components # (https://github.com/github/gitignore/pull/1529#issuecomment-104372622) #bower_components/ # RIA/Silverlight projects Generated_Code/ # Backup & report files from converting an old project file # to a newer Visual Studio version. Backup files are not needed, # because we have git ;-) _UpgradeReport_Files/ Backup*/ UpgradeLog*.XML UpgradeLog*.htm # SQL Server files *.mdf *.ldf # Business Intelligence projects *.rdl.data *.bim.layout *.bim_*.settings # Microsoft Fakes FakesAssemblies/ # GhostDoc plugin setting file *.GhostDoc.xml # Node.js Tools for Visual Studio .ntvs_analysis.dat # Visual Studio 6 build log *.plg # Visual Studio 6 workspace options file *.opt # Visual Studio LightSwitch build output **/*.HTMLClient/GeneratedArtifacts **/*.DesktopClient/GeneratedArtifacts **/*.DesktopClient/ModelManifest.xml **/*.Server/GeneratedArtifacts **/*.Server/ModelManifest.xml _Pvt_Extensions # Paket dependency manager .paket/paket.exe paket-files/ # FAKE - F# Make .fake/ # JetBrains Rider .idea/ *.sln.iml ================================================ FILE: .travis.yml ================================================ language: csharp matrix: include: - os: linux dist: xenial sudo: required mono: none dotnet: 6.0.100 addons: apt: sources: - sourceline: "deb [arch=amd64] https://packages.microsoft.com/ubuntu/16.04/prod xenial main" key_url: "https://packages.microsoft.com/keys/microsoft.asc" packages: - powershell - dotnet-hosting-2.0.7 - aspnetcore-runtime-2.1 - aspnetcore-runtime-3.1 - aspnetcore-runtime-5.0 env: global: - DOTNET_SKIP_FIRST_TIME_EXPERIENCE: true - DOTNET_CLI_TELEMETRY_OPTOUT: 1 script: - pwsh ./build.ps1 ================================================ FILE: .vscode/extensions.json ================================================ { "recommendations": [ "EditorConfig.EditorConfig", "formulahendry.dotnet-test-explorer", "ms-vscode.csharp", "ms-vscode.powershell" ] } ================================================ FILE: .vscode/settings.json ================================================ { "dotnet-test-explorer.testProjectPath": "test/OpenTracing.Contrib.NetCore.Tests" } ================================================ FILE: .vscode/tasks.json ================================================ { "version": "2.0.0", "tasks": [ { "label": "build", "command": "dotnet", "type": "process", "args": [ "build", "${workspaceFolder}", "--no-restore" ], "problemMatcher": "$msCompile", "group": { "kind": "build", "isDefault": true } } ] } ================================================ FILE: Directory.Build.props ================================================ false latest true true $(MSBuildThisFileDirectory)SignKey.snk true ================================================ FILE: LICENSE ================================================ Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS APPENDIX: How to apply the Apache License to your work. To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. Copyright [yyyy] [name of copyright owner] Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ================================================ FILE: NuGet.config ================================================ ================================================ FILE: OpenTracing.Contrib.sln ================================================  Microsoft Visual Studio Solution File, Format Version 12.00 # Visual Studio Version 17 VisualStudioVersion = 17.4.33103.184 MinimumVisualStudioVersion = 10.0.40219.1 Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "src", "src", "{420F640A-E23F-457C-BEC7-1DEAD1C592F1}" ProjectSection(SolutionItems) = preProject src\Directory.Build.props = src\Directory.Build.props EndProjectSection EndProject Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "test", "test", "{F9AD8B6F-1F59-4678-B9CF-9CD87172A111}" EndProject Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "samples", "samples", "{36333C22-54F7-403C-ABC4-BECE4EE3F52D}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "OpenTracing.Contrib.NetCore", "src\OpenTracing.Contrib.NetCore\OpenTracing.Contrib.NetCore.csproj", "{10729E17-3C79-477B-BBEB-B727D7B5B60B}" EndProject Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution Items", "{A47B38EB-246E-4CD5-9655-539466C71067}" ProjectSection(SolutionItems) = preProject .appveyor.yml = .appveyor.yml .travis.yml = .travis.yml build.ps1 = build.ps1 Directory.Build.props = Directory.Build.props global.json = global.json launch-sample.ps1 = launch-sample.ps1 README.md = README.md EndProjectSection EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "OpenTracing.Contrib.NetCore.Tests", "test\OpenTracing.Contrib.NetCore.Tests\OpenTracing.Contrib.NetCore.Tests.csproj", "{70707714-F09D-48A7-B6BC-3C58B243A753}" EndProject Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "benchmarks", "benchmarks", "{FCB84E77-6B0A-4969-8DF2-7E74197E29BB}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "OpenTracing.Contrib.NetCore.Benchmarks", "benchmarks\OpenTracing.Contrib.NetCore.Benchmarks\OpenTracing.Contrib.NetCore.Benchmarks.csproj", "{E92B106E-1DEF-43D9-B7FF-30132DB6254B}" EndProject Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "netcoreapp3.1", "netcoreapp3.1", "{02A299C4-1D35-4A37-8258-A3DBEB76D9B0}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Shared", "samples\netcoreapp3.1\Shared\Shared.csproj", "{D537C2F7-00F7-4C7B-8F79-95971C0F2019}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "CustomersApi", "samples\netcoreapp3.1\CustomersApi\CustomersApi.csproj", "{A3EB1F40-43D4-4917-A1C3-7102D183EFF8}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "FrontendWeb", "samples\netcoreapp3.1\FrontendWeb\FrontendWeb.csproj", "{1B474D5E-B041-4EB9-AA16-6980C26965F3}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "OrdersApi", "samples\netcoreapp3.1\OrdersApi\OrdersApi.csproj", "{42CB5830-7366-421A-9588-D7B03CF2478E}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "TrafficGenerator", "samples\netcoreapp3.1\TrafficGenerator\TrafficGenerator.csproj", "{CE6A1977-11FB-4192-A533-BB31427B6DE2}" EndProject Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "net6.0", "net6.0", "{03935477-E35E-4EEE-9944-8742E0CB5CFD}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "CustomersApi", "samples\net6.0\CustomersApi\CustomersApi.csproj", "{872A3B2E-1A28-4B3C-A83D-7C99513B36FB}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "FrontendWeb", "samples\net6.0\FrontendWeb\FrontendWeb.csproj", "{4756D99B-BAA2-4B9E-AAE3-F521C38134DD}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "OrdersApi", "samples\net6.0\OrdersApi\OrdersApi.csproj", "{73108F76-DAF0-48A1-9FE7-F17395672316}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Shared", "samples\net6.0\Shared\Shared.csproj", "{85F652F4-BF5E-4CBF-BD1F-5BE305DC4589}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "TrafficGenerator", "samples\net6.0\TrafficGenerator\TrafficGenerator.csproj", "{AE063835-3A23-4037-900D-9FFCC3234C8F}" EndProject Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "net7.0", "net7.0", "{E46F4333-859A-4CC5-BD2A-7FE8892861BE}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "CustomersApi", "samples\net7.0\CustomersApi\CustomersApi.csproj", "{36742677-A185-47FC-A1C6-028BF0C45CEE}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "FrontendWeb", "samples\net7.0\FrontendWeb\FrontendWeb.csproj", "{5613E36C-A0B0-4B9B-80D8-A89470CFA7AF}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "OrdersApi", "samples\net7.0\OrdersApi\OrdersApi.csproj", "{48CD3687-6EB7-47CD-A611-8D579FBCBB3B}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Shared", "samples\net7.0\Shared\Shared.csproj", "{B4A8B209-AA79-4C34-9A12-F03E3423B330}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "TrafficGenerator", "samples\net7.0\TrafficGenerator\TrafficGenerator.csproj", "{69E6E77E-646D-475A-9B6B-C5511C21B11C}" EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU Release|Any CPU = Release|Any CPU EndGlobalSection GlobalSection(ProjectConfigurationPlatforms) = postSolution {10729E17-3C79-477B-BBEB-B727D7B5B60B}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {10729E17-3C79-477B-BBEB-B727D7B5B60B}.Debug|Any CPU.Build.0 = Debug|Any CPU {10729E17-3C79-477B-BBEB-B727D7B5B60B}.Release|Any CPU.ActiveCfg = Release|Any CPU {10729E17-3C79-477B-BBEB-B727D7B5B60B}.Release|Any CPU.Build.0 = Release|Any CPU {70707714-F09D-48A7-B6BC-3C58B243A753}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {70707714-F09D-48A7-B6BC-3C58B243A753}.Debug|Any CPU.Build.0 = Debug|Any CPU {70707714-F09D-48A7-B6BC-3C58B243A753}.Release|Any CPU.ActiveCfg = Release|Any CPU {70707714-F09D-48A7-B6BC-3C58B243A753}.Release|Any CPU.Build.0 = Release|Any CPU {E92B106E-1DEF-43D9-B7FF-30132DB6254B}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {E92B106E-1DEF-43D9-B7FF-30132DB6254B}.Debug|Any CPU.Build.0 = Debug|Any CPU {E92B106E-1DEF-43D9-B7FF-30132DB6254B}.Release|Any CPU.ActiveCfg = Release|Any CPU {E92B106E-1DEF-43D9-B7FF-30132DB6254B}.Release|Any CPU.Build.0 = Release|Any CPU {D537C2F7-00F7-4C7B-8F79-95971C0F2019}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {D537C2F7-00F7-4C7B-8F79-95971C0F2019}.Debug|Any CPU.Build.0 = Debug|Any CPU {D537C2F7-00F7-4C7B-8F79-95971C0F2019}.Release|Any CPU.ActiveCfg = Release|Any CPU {D537C2F7-00F7-4C7B-8F79-95971C0F2019}.Release|Any CPU.Build.0 = Release|Any CPU {A3EB1F40-43D4-4917-A1C3-7102D183EFF8}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {A3EB1F40-43D4-4917-A1C3-7102D183EFF8}.Debug|Any CPU.Build.0 = Debug|Any CPU {A3EB1F40-43D4-4917-A1C3-7102D183EFF8}.Release|Any CPU.ActiveCfg = Release|Any CPU {A3EB1F40-43D4-4917-A1C3-7102D183EFF8}.Release|Any CPU.Build.0 = Release|Any CPU {1B474D5E-B041-4EB9-AA16-6980C26965F3}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {1B474D5E-B041-4EB9-AA16-6980C26965F3}.Debug|Any CPU.Build.0 = Debug|Any CPU {1B474D5E-B041-4EB9-AA16-6980C26965F3}.Release|Any CPU.ActiveCfg = Release|Any CPU {1B474D5E-B041-4EB9-AA16-6980C26965F3}.Release|Any CPU.Build.0 = Release|Any CPU {42CB5830-7366-421A-9588-D7B03CF2478E}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {42CB5830-7366-421A-9588-D7B03CF2478E}.Debug|Any CPU.Build.0 = Debug|Any CPU {42CB5830-7366-421A-9588-D7B03CF2478E}.Release|Any CPU.ActiveCfg = Release|Any CPU {42CB5830-7366-421A-9588-D7B03CF2478E}.Release|Any CPU.Build.0 = Release|Any CPU {CE6A1977-11FB-4192-A533-BB31427B6DE2}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {CE6A1977-11FB-4192-A533-BB31427B6DE2}.Debug|Any CPU.Build.0 = Debug|Any CPU {CE6A1977-11FB-4192-A533-BB31427B6DE2}.Release|Any CPU.ActiveCfg = Release|Any CPU {CE6A1977-11FB-4192-A533-BB31427B6DE2}.Release|Any CPU.Build.0 = Release|Any CPU {872A3B2E-1A28-4B3C-A83D-7C99513B36FB}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {872A3B2E-1A28-4B3C-A83D-7C99513B36FB}.Debug|Any CPU.Build.0 = Debug|Any CPU {872A3B2E-1A28-4B3C-A83D-7C99513B36FB}.Release|Any CPU.ActiveCfg = Release|Any CPU {872A3B2E-1A28-4B3C-A83D-7C99513B36FB}.Release|Any CPU.Build.0 = Release|Any CPU {4756D99B-BAA2-4B9E-AAE3-F521C38134DD}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {4756D99B-BAA2-4B9E-AAE3-F521C38134DD}.Debug|Any CPU.Build.0 = Debug|Any CPU {4756D99B-BAA2-4B9E-AAE3-F521C38134DD}.Release|Any CPU.ActiveCfg = Release|Any CPU {4756D99B-BAA2-4B9E-AAE3-F521C38134DD}.Release|Any CPU.Build.0 = Release|Any CPU {73108F76-DAF0-48A1-9FE7-F17395672316}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {73108F76-DAF0-48A1-9FE7-F17395672316}.Debug|Any CPU.Build.0 = Debug|Any CPU {73108F76-DAF0-48A1-9FE7-F17395672316}.Release|Any CPU.ActiveCfg = Release|Any CPU {73108F76-DAF0-48A1-9FE7-F17395672316}.Release|Any CPU.Build.0 = Release|Any CPU {85F652F4-BF5E-4CBF-BD1F-5BE305DC4589}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {85F652F4-BF5E-4CBF-BD1F-5BE305DC4589}.Debug|Any CPU.Build.0 = Debug|Any CPU {85F652F4-BF5E-4CBF-BD1F-5BE305DC4589}.Release|Any CPU.ActiveCfg = Release|Any CPU {85F652F4-BF5E-4CBF-BD1F-5BE305DC4589}.Release|Any CPU.Build.0 = Release|Any CPU {AE063835-3A23-4037-900D-9FFCC3234C8F}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {AE063835-3A23-4037-900D-9FFCC3234C8F}.Debug|Any CPU.Build.0 = Debug|Any CPU {AE063835-3A23-4037-900D-9FFCC3234C8F}.Release|Any CPU.ActiveCfg = Release|Any CPU {AE063835-3A23-4037-900D-9FFCC3234C8F}.Release|Any CPU.Build.0 = Release|Any CPU {36742677-A185-47FC-A1C6-028BF0C45CEE}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {36742677-A185-47FC-A1C6-028BF0C45CEE}.Debug|Any CPU.Build.0 = Debug|Any CPU {36742677-A185-47FC-A1C6-028BF0C45CEE}.Release|Any CPU.ActiveCfg = Release|Any CPU {36742677-A185-47FC-A1C6-028BF0C45CEE}.Release|Any CPU.Build.0 = Release|Any CPU {5613E36C-A0B0-4B9B-80D8-A89470CFA7AF}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {5613E36C-A0B0-4B9B-80D8-A89470CFA7AF}.Debug|Any CPU.Build.0 = Debug|Any CPU {5613E36C-A0B0-4B9B-80D8-A89470CFA7AF}.Release|Any CPU.ActiveCfg = Release|Any CPU {5613E36C-A0B0-4B9B-80D8-A89470CFA7AF}.Release|Any CPU.Build.0 = Release|Any CPU {48CD3687-6EB7-47CD-A611-8D579FBCBB3B}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {48CD3687-6EB7-47CD-A611-8D579FBCBB3B}.Debug|Any CPU.Build.0 = Debug|Any CPU {48CD3687-6EB7-47CD-A611-8D579FBCBB3B}.Release|Any CPU.ActiveCfg = Release|Any CPU {48CD3687-6EB7-47CD-A611-8D579FBCBB3B}.Release|Any CPU.Build.0 = Release|Any CPU {B4A8B209-AA79-4C34-9A12-F03E3423B330}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {B4A8B209-AA79-4C34-9A12-F03E3423B330}.Debug|Any CPU.Build.0 = Debug|Any CPU {B4A8B209-AA79-4C34-9A12-F03E3423B330}.Release|Any CPU.ActiveCfg = Release|Any CPU {B4A8B209-AA79-4C34-9A12-F03E3423B330}.Release|Any CPU.Build.0 = Release|Any CPU {69E6E77E-646D-475A-9B6B-C5511C21B11C}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {69E6E77E-646D-475A-9B6B-C5511C21B11C}.Debug|Any CPU.Build.0 = Debug|Any CPU {69E6E77E-646D-475A-9B6B-C5511C21B11C}.Release|Any CPU.ActiveCfg = Release|Any CPU {69E6E77E-646D-475A-9B6B-C5511C21B11C}.Release|Any CPU.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE EndGlobalSection GlobalSection(NestedProjects) = preSolution {10729E17-3C79-477B-BBEB-B727D7B5B60B} = {420F640A-E23F-457C-BEC7-1DEAD1C592F1} {70707714-F09D-48A7-B6BC-3C58B243A753} = {F9AD8B6F-1F59-4678-B9CF-9CD87172A111} {E92B106E-1DEF-43D9-B7FF-30132DB6254B} = {FCB84E77-6B0A-4969-8DF2-7E74197E29BB} {02A299C4-1D35-4A37-8258-A3DBEB76D9B0} = {36333C22-54F7-403C-ABC4-BECE4EE3F52D} {D537C2F7-00F7-4C7B-8F79-95971C0F2019} = {02A299C4-1D35-4A37-8258-A3DBEB76D9B0} {A3EB1F40-43D4-4917-A1C3-7102D183EFF8} = {02A299C4-1D35-4A37-8258-A3DBEB76D9B0} {1B474D5E-B041-4EB9-AA16-6980C26965F3} = {02A299C4-1D35-4A37-8258-A3DBEB76D9B0} {42CB5830-7366-421A-9588-D7B03CF2478E} = {02A299C4-1D35-4A37-8258-A3DBEB76D9B0} {CE6A1977-11FB-4192-A533-BB31427B6DE2} = {02A299C4-1D35-4A37-8258-A3DBEB76D9B0} {03935477-E35E-4EEE-9944-8742E0CB5CFD} = {36333C22-54F7-403C-ABC4-BECE4EE3F52D} {872A3B2E-1A28-4B3C-A83D-7C99513B36FB} = {03935477-E35E-4EEE-9944-8742E0CB5CFD} {4756D99B-BAA2-4B9E-AAE3-F521C38134DD} = {03935477-E35E-4EEE-9944-8742E0CB5CFD} {73108F76-DAF0-48A1-9FE7-F17395672316} = {03935477-E35E-4EEE-9944-8742E0CB5CFD} {85F652F4-BF5E-4CBF-BD1F-5BE305DC4589} = {03935477-E35E-4EEE-9944-8742E0CB5CFD} {AE063835-3A23-4037-900D-9FFCC3234C8F} = {03935477-E35E-4EEE-9944-8742E0CB5CFD} {E46F4333-859A-4CC5-BD2A-7FE8892861BE} = {36333C22-54F7-403C-ABC4-BECE4EE3F52D} {36742677-A185-47FC-A1C6-028BF0C45CEE} = {E46F4333-859A-4CC5-BD2A-7FE8892861BE} {5613E36C-A0B0-4B9B-80D8-A89470CFA7AF} = {E46F4333-859A-4CC5-BD2A-7FE8892861BE} {48CD3687-6EB7-47CD-A611-8D579FBCBB3B} = {E46F4333-859A-4CC5-BD2A-7FE8892861BE} {B4A8B209-AA79-4C34-9A12-F03E3423B330} = {E46F4333-859A-4CC5-BD2A-7FE8892861BE} {69E6E77E-646D-475A-9B6B-C5511C21B11C} = {E46F4333-859A-4CC5-BD2A-7FE8892861BE} EndGlobalSection GlobalSection(ExtensibilityGlobals) = postSolution SolutionGuid = {832F86C2-4B74-4259-8073-04EE0C37FBCD} EndGlobalSection EndGlobal ================================================ FILE: README.md ================================================ [![nuget](https://img.shields.io/nuget/v/OpenTracing.Contrib.NetCore.svg?logo=nuget)](https://www.nuget.org/packages/OpenTracing.Contrib.NetCore) # OpenTracing instrumentation for .NET Core apps This repository provides OpenTracing instrumentation for .NET Core based applications. It can be used with any OpenTracing compatible tracer. _**IMPORTANT:** OpenTracing and OpenCensus have merget to form **[OpenTelemetry](https://opentelemetry.io)**! The OpenTelemetry .NET library can be found at [https://github.com/open-telemetry/opentelemetry-dotnet](https://github.com/open-telemetry/opentelemetry-dotnet)._ ## Supported .NET versions This project currently only supports apps targeting .NET Core 3.1, .NET 6.0, or .NET 7.0! This project DOES NOT support the full .NET framework as that uses different instrumentation code. ## Supported libraries and frameworks #### DiagnosticSource based instrumentation This project supports any library or framework that uses .NET's [`DiagnosticSource`](https://github.com/dotnet/runtime/blob/master/src/libraries/System.Diagnostics.DiagnosticSource/src/DiagnosticSourceUsersGuide.md) to instrument its code. It will create a span for every [`Activity`](https://github.com/dotnet/runtime/blob/master/src/libraries/System.Diagnostics.DiagnosticSource/src/ActivityUserGuide.md) and it will create `span.Log` calls for all other diagnostic events. To further improve the tracing output, the library provides enhanced instrumentation (Inject/Extract, tags, configuration options) for the following libraries / frameworks: * ASP.NET Core * Entity Framework Core * System.Net.Http (HttpClient) * System.Data.SqlClient * Microsoft.Data.SqlClient #### Microsoft.Extensions.Logging based instrumentation This project also adds itself as a logger provider for logging events from the `Microsoft.Extensions.Logging` system. It will create `span.Log` calls for each logging event, however it will only create them if there is an active span (`ITracer.ActiveSpan`). ## Usage This project depends on several packages from Microsofts `Microsoft.Extensions.*` stack (e.g. Dependency Injection, Logging) so its main use case is ASP.NET Core apps and any other Microsoft.Extensions-based console apps. ##### 1. Add the NuGet package `OpenTracing.Contrib.NetCore` to your project. ##### 2. Add the OpenTracing services to your `IServiceCollection` via `services.AddOpenTracing()`. How you do this depends on how you've setup the `Microsoft.Extensions.DependencyInjection` system in your app. In ASP.NET Core apps you can add the call to your `ConfigureServices` method (of your `Program.cs` file): ```csharp public static IWebHost BuildWebHost(string[] args) { return WebHost.CreateDefaultBuilder(args) .UseStartup() .ConfigureServices(services => { // Enables and automatically starts the instrumentation! services.AddOpenTracing(); }) .Build(); } ``` ##### 3. Make sure `InstrumentationService`, which implements `IHostedService`, is started. `InstrumentationService` is responsible for starting and stopping the instrumentation. The service implements `IHostedService` so **it is automatically started in ASP.NET Core**, however if you have your own console host, you manually have to call `StartAsync` and `StopAsync`. Note that .NET Core 2.1 greatly simplified this setup by introducing a generic `HostBuilder` that works similar to the existing `WebHostBuilder` from ASP.NET Core. Have a look at the `TrafficGenerator` sample for an example of a `HostBuilder` based console application. ================================================ FILE: RELEASE.md ================================================ # Release Process The release process consists of these steps: 1. Create a GitHub release with release notes. The tag name must be a semantic version, prefixed with "v" - e.g. `v0.1.0` or `v0.1.0-rc1` 1. Wait for the AppVeyor build to finish the *tag* build: https://ci.appveyor.com/project/opentracing/csharp-netcore 1. As a signed-in AppVeyor user, click "Deploy" on the build details page and select "NuGet (OpenTracing)". This will upload the packages to NuGet.org ================================================ FILE: benchmarks/OpenTracing.Contrib.NetCore.Benchmarks/AspNetCore/RequestDiagnosticsBenchmark.cs ================================================ using System; using System.Net.Http; using System.Threading.Tasks; using BenchmarkDotNet.Attributes; using Microsoft.AspNetCore; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc.Testing; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; namespace OpenTracing.Contrib.NetCore.Benchmarks.AspNetCore { public class TestProgramFactory : WebApplicationFactory { protected override IWebHostBuilder CreateWebHostBuilder() { var host = WebHost.CreateDefaultBuilder() // https://stackoverflow.com/a/69776251/5214796 .UseSetting("TEST_CONTENTROOT_OPENTRACING_CONTRIB_NETCORE_TESTS", "") .ConfigureServices(services => { }) .Configure(app => { app.UseRouting(); app.UseEndpoints(endpoints => { endpoints.MapGet("/foo", async context => { await context.Response.WriteAsync("Hello"); }); endpoints.MapGet("/exception", _ => { throw new InvalidOperationException("You shall not pass"); }); }); }); return host; } } public class RequestDiagnosticsBenchmark { private WebApplicationFactory _factory; private HttpClient _client; [Params(InstrumentationMode.None, InstrumentationMode.Noop, InstrumentationMode.Mock)] public InstrumentationMode Mode { get; set; } [GlobalSetup] public void GlobalSetup() { _factory = new TestProgramFactory() .WithWebHostBuilder(x => { x.ConfigureLogging(l => l.ClearProviders()); x.ConfigureServices(services => { services.AddOpenTracingCoreServices(builder => { builder.AddAspNetCore(); builder.AddBenchmarkTracer(Mode); }); }); }); _client = _factory.CreateClient(); } [GlobalCleanup] public void GlobalCleanup() { _factory.Dispose(); } [Benchmark] public async Task GetAsync() { await _client.GetAsync("/foo"); } } } ================================================ FILE: benchmarks/OpenTracing.Contrib.NetCore.Benchmarks/CoreFx/HttpHandlerDiagnosticsBenchmark.cs ================================================ using System; using System.Net; using System.Net.Http; using System.Reflection; using System.Threading; using System.Threading.Tasks; using BenchmarkDotNet.Attributes; using Microsoft.Extensions.DependencyInjection; using OpenTracing.Contrib.NetCore.Internal; namespace OpenTracing.Contrib.NetCore.Benchmarks.CoreFx { public class HttpHandlerDiagnosticsBenchmark { private HttpClient _httpClient; private ServiceProvider _serviceProvider; [Params(InstrumentationMode.None, InstrumentationMode.Noop, InstrumentationMode.Mock)] public InstrumentationMode Mode { get; set; } [GlobalSetup] public void GlobalSetup() { _httpClient = CreateHttpClient(); _serviceProvider = new ServiceCollection() .AddLogging() .AddOpenTracingCoreServices(builder => { builder.AddBenchmarkTracer(Mode); builder.AddHttpHandler(); }) .BuildServiceProvider(); var diagnosticsManager = _serviceProvider.GetRequiredService(); diagnosticsManager.Start(); } [GlobalCleanup] public void GlobalCleanup() { (_serviceProvider as IDisposable).Dispose(); } [Benchmark] public Task HttpClient_GetAsync() { return _httpClient.GetAsync("http://www.example.com"); } private static HttpClient CreateHttpClient() { // Inner handler for mocking the result var httpHandler = new MockHttpMessageHandler(); // Wrap with DiagnosticsHandler (which is internal :( ) Type type = typeof(HttpClientHandler).Assembly.GetType("System.Net.Http.DiagnosticsHandler"); ConstructorInfo constructor = type.GetConstructors(BindingFlags.Instance | BindingFlags.Public)[0]; HttpMessageHandler diagnosticsHandler = (HttpMessageHandler)constructor.Invoke(new object[] { httpHandler }); return new HttpClient(diagnosticsHandler); } private class MockHttpMessageHandler : HttpMessageHandler { protected override async Task SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) { // HACK: There MUST be an awaiter otherwise exceptions are not caught by the DiagnosticsHandler. // https://github.com/dotnet/corefx/pull/27472 await Task.CompletedTask; return new HttpResponseMessage(HttpStatusCode.OK) { RequestMessage = request, Content = new StringContent("Response") }; } } } } ================================================ FILE: benchmarks/OpenTracing.Contrib.NetCore.Benchmarks/InstrumentationMode.cs ================================================ namespace OpenTracing.Contrib.NetCore.Benchmarks { public enum InstrumentationMode { None, Noop, Mock } } ================================================ FILE: benchmarks/OpenTracing.Contrib.NetCore.Benchmarks/OpenTracing.Contrib.NetCore.Benchmarks.csproj ================================================  Exe netcoreapp3.1;net6.0;net7.0 ================================================ FILE: benchmarks/OpenTracing.Contrib.NetCore.Benchmarks/OpenTracingBuilderExtensions.cs ================================================ using System; using Microsoft.Extensions.DependencyInjection; using OpenTracing.Contrib.NetCore.Internal; using OpenTracing.Mock; using OpenTracing.Noop; namespace OpenTracing.Contrib.NetCore.Benchmarks { public static class OpenTracingBuilderExtensions { public static IOpenTracingBuilder AddBenchmarkTracer(this IOpenTracingBuilder builder, InstrumentationMode mode) { if (builder == null) throw new ArgumentNullException(nameof(builder)); ITracer tracer = mode == InstrumentationMode.Mock ? new MockTracer() : NoopTracerFactory.Create(); bool startInstrumentationForNoopTracer = mode == InstrumentationMode.Noop; builder.Services.AddSingleton(tracer); builder.Services.Configure(options => options.StartInstrumentationForNoopTracer = startInstrumentationForNoopTracer); return builder; } } } ================================================ FILE: benchmarks/OpenTracing.Contrib.NetCore.Benchmarks/Program.cs ================================================ using BenchmarkDotNet.Running; namespace OpenTracing.Contrib.NetCore.Benchmarks { class Program { static void Main(string[] args) { BenchmarkSwitcher.FromAssembly(typeof(Program).Assembly).Run(args); } } } ================================================ FILE: build.ps1 ================================================ [CmdletBinding(PositionalBinding = $false)] param( [string] $ArtifactsPath = (Join-Path $PWD "artifacts"), [string] $BuildConfiguration = "Release", [bool] $RunBuild = $true, [bool] $RunTests = $true ) $ErrorActionPreference = "Stop" $Stopwatch = [System.Diagnostics.Stopwatch]::StartNew() function Task { [CmdletBinding()] param ( [Parameter(Mandatory = $true)] [string] $name, [Parameter(Mandatory = $false)] [bool] $runTask, [Parameter(Mandatory = $false)] [scriptblock] $cmd ) if ($cmd -eq $null) { throw "Command is missing for task '$name'. Make sure the starting '{' is on the same line as the term 'Task'. E.g. 'Task `"$name`" `$Run$name {'" } if ($runTask -eq $true) { Write-Host "`n------------------------- [$name] -------------------------`n" -ForegroundColor Cyan $sw = [System.Diagnostics.Stopwatch]::StartNew() & $cmd Write-Host "`nTask '$name' finished in $($sw.Elapsed.TotalSeconds) sec." } else { Write-Host "`n------------------ Skipping task '$name' ------------------" -ForegroundColor Yellow } } Task "Init" $true { if ($ArtifactsPath -eq $null) { "Property 'ArtifactsPath' may not be null." } if ($BuildConfiguration -eq $null) { throw "Property 'BuildConfiguration' may not be null." } if ((Get-Command "dotnet" -ErrorAction SilentlyContinue) -eq $null) { throw "'dotnet' command not found. Is .NET Core SDK installed?" } Write-Host "ArtifactsPath: $ArtifactsPath" Write-Host "BuildConfiguration: $BuildConfiguration" Write-Host ".NET Core SDK: $(dotnet --version)`n" Remove-Item -Path $ArtifactsPath -Recurse -Force -ErrorAction Ignore New-Item $ArtifactsPath -ItemType Directory -ErrorAction Ignore | Out-Null Write-Host "Created artifacts folder '$ArtifactsPath'" } Task "Build" $RunBuild { dotnet msbuild "/t:Restore;Build;Pack" "/p:CI=true" ` "/p:Configuration=$BuildConfiguration" ` "/p:PackageOutputPath=$(Join-Path $ArtifactsPath "nuget")" if ($LASTEXITCODE -ne 0) { throw "Build failed." } } Task "Tests" $RunTests { $testsFailed = $false Get-ChildItem -Filter *.csproj -Recurse | ForEach-Object { if (Select-Xml -Path $_.FullName -XPath "/Project/ItemGroup/PackageReference[@Include='Microsoft.NET.Test.Sdk']") { dotnet test $_.FullName -c $BuildConfiguration --no-build if ($LASTEXITCODE -ne 0) { $testsFailed = $true } } } if ($testsFailed) { throw "At least one test failed." } } Write-Host "`nBuild finished in $($Stopwatch.Elapsed.TotalSeconds) sec." -ForegroundColor Green ================================================ FILE: global.json ================================================ { "sdk": { "version": "7.0.100", "rollForward": "feature" } } ================================================ FILE: launch-sample.ps1 ================================================ [CmdletBinding(PositionalBinding = $false)] param( [ValidateSet("net7.0", "net6.0", "netcoreapp3.1")] [string] $Framework = "net6.0" ) dotnet build if ($LASTEXITCODE -ne 0) { throw "build error" } Write-Host "Launching samples with framework $Framework" Start-Process ` -FilePath powershell.exe ` -ArgumentList @( "dotnet run -f $Framework --no-build; Read-Host 'Press enter to exit'" ) ` -WorkingDirectory "samples\$Framework\CustomersApi" Start-Sleep -Seconds 2 Start-Process ` -FilePath powershell.exe ` -ArgumentList @( "dotnet run -f $Framework --no-build; Read-Host 'Press enter to exit'" ) ` -WorkingDirectory "samples\$Framework\OrdersApi" Start-Sleep -Seconds 5 Start-Process ` -FilePath powershell.exe ` -ArgumentList @( "dotnet run -f $Framework --no-build; Read-Host 'Press enter to exit'" ) ` -WorkingDirectory "samples\$Framework\FrontendWeb" Start-Process ` -FilePath powershell.exe ` -ArgumentList @( "dotnet run -f $Framework --no-build; Read-Host 'Press enter to exit'" ) ` -WorkingDirectory "samples\$Framework\TrafficGenerator" ================================================ FILE: samples/net6.0/CustomersApi/Controllers/CustomersController.cs ================================================ using System.Linq; using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Logging; using Samples.CustomersApi.DataStore; namespace Samples.CustomersApi.Controllers { [Route("customers")] public class CustomersController : Controller { private readonly CustomerDbContext _dbContext; private readonly ILogger _logger; public CustomersController(CustomerDbContext dbContext, ILogger logger) { _dbContext = dbContext; _logger = logger; } [HttpGet] public IActionResult Index() { return Json(_dbContext.Customers.ToList()); } [HttpGet("{id:int}")] public IActionResult Index(int id) { var customer = _dbContext.Customers.FirstOrDefault(x => x.CustomerId == id); if (customer == null) return NotFound(); // ILogger events are sent to OpenTracing as well! _logger.LogInformation("Returning data for customer {CustomerId}", id); return Json(customer); } } } ================================================ FILE: samples/net6.0/CustomersApi/CustomersApi.csproj ================================================  net6.0 ================================================ FILE: samples/net6.0/CustomersApi/DataStore/CustomerDbContext.cs ================================================ using Microsoft.EntityFrameworkCore; using Shared; namespace Samples.CustomersApi.DataStore { public class CustomerDbContext : DbContext { public CustomerDbContext(DbContextOptions options) : base(options) { } public DbSet Customers { get; set; } public void Seed() { if (Database.EnsureCreated()) { Database.Migrate(); Customers.Add(new Customer(1, "Marcel Belding")); Customers.Add(new Customer(2, "Phyllis Schriver")); Customers.Add(new Customer(3, "Estefana Balderrama")); Customers.Add(new Customer(4, "Kenyetta Lone")); Customers.Add(new Customer(5, "Vernita Fernald")); Customers.Add(new Customer(6, "Tessie Storrs")); SaveChanges(); } } } } ================================================ FILE: samples/net6.0/CustomersApi/Program.cs ================================================ using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; using Shared; namespace Samples.CustomersApi { public class Program { public static void Main(string[] args) { CreateHostBuilder(args).Build().Run(); } public static IHostBuilder CreateHostBuilder(string[] args) { return Host.CreateDefaultBuilder(args) .ConfigureWebHostDefaults(webBuilder => { webBuilder .UseStartup() .UseUrls(Constants.CustomersUrl); }) .ConfigureServices(services => { // Registers and starts Jaeger (see Shared.JaegerServiceCollectionExtensions) services.AddJaeger(); // Enables OpenTracing instrumentation for ASP.NET Core, CoreFx, EF Core services.AddOpenTracing(builder => { builder.ConfigureAspNetCore(options => { // We don't need any tracing data for our health endpoint. options.Hosting.IgnorePatterns.Add(ctx => ctx.Request.Path == "/health"); }); builder.ConfigureEntityFrameworkCore(options => { // This is an example for how certain EF Core commands can be ignored. // As en example, we're ignoring the "PRAGMA foreign_keys=ON;" commands that are executed by Sqlite. // Remove this code to see those statements. options.IgnorePatterns.Add(cmd => cmd.Command.CommandText.StartsWith("PRAGMA")); }); }); }); } } } ================================================ FILE: samples/net6.0/CustomersApi/Properties/launchSettings.json ================================================ { "profiles": { "CustomersApi": { "commandName": "Project", "launchBrowser": false, "launchUrl": "http://localhost:5001", "environmentVariables": { "ASPNETCORE_ENVIRONMENT": "Development" } } } } ================================================ FILE: samples/net6.0/CustomersApi/Startup.cs ================================================ using System; using Microsoft.AspNetCore.Builder; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.DependencyInjection; using Samples.CustomersApi.DataStore; namespace Samples.CustomersApi { public class Startup { public void ConfigureServices(IServiceCollection services) { // Adds a Sqlite DB to show EFCore traces. services .AddDbContext(options => { options.UseSqlite("Data Source=DataStore/customers.db"); }); services.AddMvc(); services.AddHealthChecks() .AddDbContextCheck(); } public void Configure(IApplicationBuilder app) { // Load some dummy data into the db. BootstrapDataStore(app.ApplicationServices); app.UseDeveloperExceptionPage(); app.UseRouting(); app.UseAuthentication(); app.UseAuthorization(); app.UseEndpoints(endpoints => { endpoints.MapControllers(); endpoints.MapHealthChecks("/health"); }); } private void BootstrapDataStore(IServiceProvider serviceProvider) { using (var scope = serviceProvider.CreateScope()) { var dbContext = scope.ServiceProvider.GetRequiredService(); dbContext.Seed(); } } } } ================================================ FILE: samples/net6.0/CustomersApi/appsettings.json ================================================ { "Logging": { "IncludeScopes": false, "LogLevel": { "Default": "Debug", "System": "Information", "Microsoft": "Information" } } } ================================================ FILE: samples/net6.0/FrontendWeb/Controllers/HomeController.cs ================================================ using System; using System.Collections.Generic; using System.Linq; using System.Net.Http; using System.Text; using System.Threading.Tasks; using Shared; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.Rendering; using Newtonsoft.Json; namespace Samples.FrontendWeb.Controllers { public class HomeController : Controller { private readonly HttpClient _httpClient; public HomeController(HttpClient httpClient) { _httpClient = httpClient; } [HttpGet] public IActionResult Index() { return View(); } [HttpGet] public async Task PlaceOrder() { ViewBag.Customers = await GetCustomers(); return View(new PlaceOrderCommand { ItemNumber = "ABC11", Quantity = 1 }); } [HttpPost, ValidateAntiForgeryToken] public async Task PlaceOrder(PlaceOrderCommand cmd) { if (!ModelState.IsValid) { ViewBag.Customers = await GetCustomers(); return View(cmd); } string body = JsonConvert.SerializeObject(cmd); var request = new HttpRequestMessage { Method = HttpMethod.Post, RequestUri = new Uri(Constants.OrdersUrl + "orders"), Content = new StringContent(body, Encoding.UTF8, "application/json") }; await _httpClient.SendAsync(request); return RedirectToAction("Index"); } private async Task> GetCustomers() { var request = new HttpRequestMessage { Method = HttpMethod.Get, RequestUri = new Uri(Constants.CustomersUrl + "customers") }; var response = await _httpClient.SendAsync(request); response.EnsureSuccessStatusCode(); var body = await response.Content.ReadAsStringAsync(); return JsonConvert.DeserializeObject>(body) .Select(x => new SelectListItem { Value = x.CustomerId.ToString(), Text = x.Name }); } } } ================================================ FILE: samples/net6.0/FrontendWeb/FrontendWeb.csproj ================================================  net6.0 ================================================ FILE: samples/net6.0/FrontendWeb/Program.cs ================================================ using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; using Shared; namespace Samples.FrontendWeb { public class Program { public static void Main(string[] args) { CreateHostBuilder(args).Build().Run(); } public static IHostBuilder CreateHostBuilder(string[] args) { return Host.CreateDefaultBuilder(args) .ConfigureWebHostDefaults(webBuilder => { webBuilder .UseStartup() .UseUrls(Constants.FrontendUrl); }) .ConfigureServices(services => { // Registers and starts Jaeger (see Shared.JaegerServiceCollectionExtensions) services.AddJaeger(); // Enables OpenTracing instrumentation for ASP.NET Core, CoreFx, EF Core services.AddOpenTracing(); }); } } } ================================================ FILE: samples/net6.0/FrontendWeb/Properties/launchSettings.json ================================================ { "profiles": { "FrontendWeb": { "commandName": "Project", "launchBrowser": false, "launchUrl": "http://localhost:5000", "environmentVariables": { "ASPNETCORE_ENVIRONMENT": "Development" } } } } ================================================ FILE: samples/net6.0/FrontendWeb/Startup.cs ================================================ using System.Net.Http; using Microsoft.AspNetCore.Builder; using Microsoft.Extensions.DependencyInjection; namespace Samples.FrontendWeb { public class Startup { public void ConfigureServices(IServiceCollection services) { services.AddSingleton(); services.AddMvc(); } public void Configure(IApplicationBuilder app) { app.UseDeveloperExceptionPage(); app.UseRouting(); app.UseAuthentication(); app.UseAuthorization(); app.UseEndpoints(endpoints => { endpoints.MapDefaultControllerRoute(); }); } } } ================================================ FILE: samples/net6.0/FrontendWeb/Views/Home/Index.cshtml ================================================  FrontendWeb

FrontendWeb

This is the beautiful web frontend.

Refresh this page a few times and check the Jaeger UI - you should already see traces!

Place an order

================================================ FILE: samples/net6.0/FrontendWeb/Views/Home/PlaceOrder.cshtml ================================================ @model Shared.PlaceOrderCommand FrontendWeb

FrontendWeb

Place an order

Customer: @Html.DropDownListFor(x => x.CustomerId, (IEnumerable)ViewBag.Customers)
ItemNumber: @Html.TextBoxFor(x => x.ItemNumber)
Quantity: @Html.TextBoxFor(x => x.Quantity)
================================================ FILE: samples/net6.0/FrontendWeb/Views/_ViewImports.cshtml ================================================ @using Samples.FrontendWeb @addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers ================================================ FILE: samples/net6.0/FrontendWeb/appsettings.json ================================================ { "Logging": { "IncludeScopes": false, "LogLevel": { "Default": "Debug", "System": "Information", "Microsoft": "Information", "OpenTracing": "Debug" } } } ================================================ FILE: samples/net6.0/OrdersApi/Controllers/OrdersController.cs ================================================ using System; using System.Collections.Generic; using System.Linq; using System.Net.Http; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using Microsoft.EntityFrameworkCore; using Newtonsoft.Json; using OpenTracing; using OrdersApi.DataStore; using Shared; namespace Samples.OrdersApi.Controllers { [Route("orders")] public class OrdersController : Controller { private readonly OrdersDbContext _dbContext; private readonly HttpClient _httpClient; private readonly ITracer _tracer; public OrdersController(OrdersDbContext dbContext, HttpClient httpClient, ITracer tracer) { _dbContext = dbContext ?? throw new ArgumentNullException(nameof(dbContext)); _httpClient = httpClient ?? throw new ArgumentNullException(nameof(httpClient)); _tracer = tracer ?? throw new ArgumentNullException(nameof(tracer)); } [HttpGet] public async Task Index() { var orders = await _dbContext.Orders.ToListAsync(); return Ok(orders.Select(x => new { x.OrderId }).ToList()); } [HttpPost] public async Task Index([FromBody] PlaceOrderCommand cmd) { var customer = await GetCustomer(cmd.CustomerId.Value); var order = new Order { CustomerId = cmd.CustomerId.Value, ItemNumber = cmd.ItemNumber, Quantity = cmd.Quantity }; _dbContext.Orders.Add(order); await _dbContext.SaveChangesAsync(); _tracer.ActiveSpan?.Log(new Dictionary { { "event", "OrderPlaced" }, { "orderId", order.OrderId }, { "customer", order.CustomerId }, { "customer_name", customer.Name }, { "item_number", order.ItemNumber }, { "quantity", order.Quantity } }); return Ok(); } private async Task GetCustomer(int customerId) { var request = new HttpRequestMessage { Method = HttpMethod.Get, RequestUri = new Uri(Constants.CustomersUrl + "customers/" + customerId) }; var response = await _httpClient.SendAsync(request); response.EnsureSuccessStatusCode(); var body = await response.Content.ReadAsStringAsync(); return JsonConvert.DeserializeObject(body); } } } ================================================ FILE: samples/net6.0/OrdersApi/DataStore/Order.cs ================================================ using System; using System.ComponentModel.DataAnnotations; namespace OrdersApi.DataStore { public class Order { [Key] public int OrderId { get; set; } public int CustomerId { get; set; } [Required, StringLength(10)] public string ItemNumber { get; set; } [Required, Range(1, 100)] public int Quantity { get; set; } } } ================================================ FILE: samples/net6.0/OrdersApi/DataStore/OrdersDbContext.cs ================================================ using Microsoft.EntityFrameworkCore; namespace OrdersApi.DataStore { public class OrdersDbContext : DbContext { public OrdersDbContext(DbContextOptions options) : base(options) { } public DbSet Orders { get; set; } public void Seed() { if (Database.EnsureCreated()) { Database.Migrate(); SaveChanges(); } } } } ================================================ FILE: samples/net6.0/OrdersApi/OrdersApi.csproj ================================================  net6.0 ================================================ FILE: samples/net6.0/OrdersApi/Program.cs ================================================ using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; using Shared; namespace Samples.OrdersApi { public class Program { public static void Main(string[] args) { CreateHostBuilder(args).Build().Run(); } public static IHostBuilder CreateHostBuilder(string[] args) { return Host.CreateDefaultBuilder(args) .ConfigureWebHostDefaults(webBuilder => { webBuilder .UseStartup() .UseUrls(Constants.OrdersUrl); }) .ConfigureServices(services => { // Registers and starts Jaeger (see Shared.JaegerServiceCollectionExtensions) services.AddJaeger(); // Enables OpenTracing instrumentation for ASP.NET Core, CoreFx, EF Core services.AddOpenTracing(builder => { builder.ConfigureAspNetCore(options => { // We don't need any tracing data for our health endpoint. options.Hosting.IgnorePatterns.Add(ctx => ctx.Request.Path == "/health"); }); }); }); } } } ================================================ FILE: samples/net6.0/OrdersApi/Properties/launchSettings.json ================================================ { "profiles": { "OrdersApi": { "commandName": "Project", "launchBrowser": false, "launchUrl": "http://localhost:5002", "environmentVariables": { "ASPNETCORE_ENVIRONMENT": "Development" } } } } ================================================ FILE: samples/net6.0/OrdersApi/Startup.cs ================================================ using System; using System.Net.Http; using Microsoft.AspNetCore.Builder; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.DependencyInjection; using OrdersApi.DataStore; namespace Samples.OrdersApi { public class Startup { public void ConfigureServices(IServiceCollection services) { // Adds a SqlServer DB to show EFCore traces. services .AddDbContext(options => { options.UseSqlServer("Server=(localdb)\\mssqllocaldb;Database=Orders-net5;Trusted_Connection=True;MultipleActiveResultSets=true"); }); services.AddSingleton(); services.AddMvc(); services.AddHealthChecks() .AddDbContextCheck(); } public void Configure(IApplicationBuilder app) { // Load some dummy data into the db. BootstrapDataStore(app.ApplicationServices); app.UseDeveloperExceptionPage(); app.UseRouting(); app.UseAuthentication(); app.UseAuthorization(); app.UseEndpoints(endpoints => { endpoints.MapDefaultControllerRoute(); endpoints.MapHealthChecks("/health"); }); } private void BootstrapDataStore(IServiceProvider serviceProvider) { using (var scope = serviceProvider.CreateScope()) { var dbContext = scope.ServiceProvider.GetRequiredService(); dbContext.Seed(); } } } } ================================================ FILE: samples/net6.0/OrdersApi/appsettings.json ================================================ { "Logging": { "IncludeScopes": false, "LogLevel": { "Default": "Debug", "System": "Information", "Microsoft": "Information" } } } ================================================ FILE: samples/net6.0/Shared/Constants.cs ================================================ namespace Shared { public class Constants { public const string FrontendUrl = "http://localhost:5000/"; public const string CustomersUrl = "http://localhost:5001/"; public const string OrdersUrl = "http://localhost:5002/"; } } ================================================ FILE: samples/net6.0/Shared/Customer.cs ================================================ namespace Shared { public class Customer { public int CustomerId { get; set; } public string Name { get; set; } public Customer() { } public Customer(int customerId, string name) { CustomerId = customerId; Name = name; } } } ================================================ FILE: samples/net6.0/Shared/JaegerServiceCollectionExtensions.cs ================================================ using System; using System.Reflection; using Jaeger; using Jaeger.Reporters; using Jaeger.Samplers; using Jaeger.Senders.Thrift; using Microsoft.Extensions.Logging; using OpenTracing; using OpenTracing.Contrib.NetCore.Configuration; using OpenTracing.Util; namespace Microsoft.Extensions.DependencyInjection { public static class JaegerServiceCollectionExtensions { private static readonly Uri _jaegerUri = new Uri("http://localhost:14268/api/traces"); public static IServiceCollection AddJaeger(this IServiceCollection services) { if (services == null) throw new ArgumentNullException(nameof(services)); services.AddSingleton(serviceProvider => { string serviceName = Assembly.GetEntryAssembly().GetName().Name; ILoggerFactory loggerFactory = serviceProvider.GetRequiredService(); ISampler sampler = new ConstSampler(sample: true); IReporter reporter = new RemoteReporter.Builder() .WithSender(new HttpSender.Builder(_jaegerUri.ToString()).Build()) .Build(); ITracer tracer = new Tracer.Builder(serviceName) .WithLoggerFactory(loggerFactory) .WithSampler(sampler) .WithReporter(reporter) .Build(); GlobalTracer.Register(tracer); return tracer; }); // Prevent endless loops when OpenTracing is tracking HTTP requests to Jaeger. services.Configure(options => { options.IgnorePatterns.Add(request => _jaegerUri.IsBaseOf(request.RequestUri)); }); return services; } } } ================================================ FILE: samples/net6.0/Shared/PlaceOrderCommand.cs ================================================ using System.ComponentModel.DataAnnotations; namespace Shared { public class PlaceOrderCommand { [Required] public int? CustomerId { get; set; } [Required, StringLength(10)] public string ItemNumber { get; set; } [Required, Range(1, 100)] public int Quantity { get; set; } } } ================================================ FILE: samples/net6.0/Shared/Shared.csproj ================================================  net6.0 ================================================ FILE: samples/net6.0/TrafficGenerator/Program.cs ================================================ using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; namespace TrafficGenerator { class Program { public static void Main(string[] args) { CreateHostBuilder(args).Build().Run(); } public static IHostBuilder CreateHostBuilder(string[] args) => Host.CreateDefaultBuilder(args) .ConfigureServices(services => { // Registers and starts Jaeger (see Shared.JaegerServiceCollectionExtensions) services.AddJaeger(); services.AddOpenTracing(); services.AddHostedService(); }); } } ================================================ FILE: samples/net6.0/TrafficGenerator/TrafficGenerator.csproj ================================================ net6.0 ================================================ FILE: samples/net6.0/TrafficGenerator/Worker.cs ================================================ using System; using System.Net.Http; using System.Threading; using System.Threading.Tasks; using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Logging; using Shared; namespace TrafficGenerator { public class Worker : BackgroundService { private readonly ILogger _logger; public Worker(ILogger logger) { _logger = logger ?? throw new ArgumentNullException(nameof(logger)); } protected override async Task ExecuteAsync(CancellationToken stoppingToken) { try { HttpClient customersHttpClient = new HttpClient(); customersHttpClient.BaseAddress = new Uri(Constants.CustomersUrl); HttpClient ordersHttpClient = new HttpClient(); ordersHttpClient.BaseAddress = new Uri(Constants.OrdersUrl); while (!stoppingToken.IsCancellationRequested) { HttpResponseMessage ordershealthResponse = await ordersHttpClient.GetAsync("health"); _logger.LogInformation($"Health of 'orders'-endpoint: '{ordershealthResponse.StatusCode}'"); HttpResponseMessage customersHealthResponse = await customersHttpClient.GetAsync("health"); _logger.LogInformation($"Health of 'customers'-endpoint: '{customersHealthResponse.StatusCode}'"); _logger.LogInformation("Requesting customers"); HttpResponseMessage response = await customersHttpClient.GetAsync("customers"); _logger.LogInformation($"Response was '{response.StatusCode}'"); await Task.Delay(TimeSpan.FromSeconds(5), stoppingToken); } } catch (TaskCanceledException) { /* Application should be stopped -> no-op */ } catch (Exception ex) { _logger.LogError(ex, "Unhandled exception"); } } } } ================================================ FILE: samples/net6.0/TrafficGenerator/appsettings.json ================================================ { "Logging": { "LogLevel": { "Default": "Debug", "System": "Information", "Microsoft": "Warning", "Microsoft.AspNetCore.Hosting": "Information" } } } ================================================ FILE: samples/net7.0/CustomersApi/CustomersApi.csproj ================================================  net7.0 enable enable ================================================ FILE: samples/net7.0/CustomersApi/DataStore/CustomerDbContext.cs ================================================ using Microsoft.EntityFrameworkCore; using Shared; namespace CustomersApi.DataStore; public class CustomerDbContext : DbContext { public CustomerDbContext(DbContextOptions options) : base(options) { } public DbSet Customers => Set(); public void Seed() { if (Database.EnsureCreated()) { Database.Migrate(); Customers.Add(new Customer(1, "Marcel Belding")); Customers.Add(new Customer(2, "Phyllis Schriver")); Customers.Add(new Customer(3, "Estefana Balderrama")); Customers.Add(new Customer(4, "Kenyetta Lone")); Customers.Add(new Customer(5, "Vernita Fernald")); Customers.Add(new Customer(6, "Tessie Storrs")); SaveChanges(); } } } ================================================ FILE: samples/net7.0/CustomersApi/Program.cs ================================================ using CustomersApi.DataStore; using Microsoft.EntityFrameworkCore; using Shared; var builder = WebApplication.CreateBuilder(args); // Add services to the container. builder.WebHost.UseUrls(Constants.CustomersUrl); // Registers and starts Jaeger (see Shared.JaegerServiceCollectionExtensions) builder.Services.AddJaeger(); // Enables OpenTracing instrumentation for ASP.NET Core, CoreFx, EF Core builder.Services.AddOpenTracing(ot => { ot.ConfigureAspNetCore(options => { // We don't need any tracing data for our health endpoint. options.Hosting.IgnorePatterns.Add(ctx => ctx.Request.Path == "/health"); }); ot.ConfigureEntityFrameworkCore(options => { // This is an example for how certain EF Core commands can be ignored. // As en example, we're ignoring the "PRAGMA foreign_keys=ON;" commands that are executed by Sqlite. // Remove this code to see those statements. options.IgnorePatterns.Add(cmd => cmd.Command.CommandText.StartsWith("PRAGMA")); }); }); // Adds a Sqlite DB to show EFCore traces. builder.Services.AddDbContext(options => { options.UseSqlite("Data Source=DataStore/customers.db"); }); builder.Services.AddHealthChecks() .AddDbContextCheck(); var app = builder.Build(); // Load some dummy data into the db. using (var scope = app.Services.CreateScope()) { var dbContext = scope.ServiceProvider.GetRequiredService(); dbContext.Seed(); } // Configure the HTTP request pipeline. app.MapGet("/", () => "Customers API"); app.MapHealthChecks("/health"); app.MapGet("/customers", async (CustomerDbContext dbContext) => await dbContext.Customers.ToListAsync()); app.MapGet("/customers/{id}", async (int id, CustomerDbContext dbContext, ILogger logger) => { var customer = await dbContext.Customers.FirstOrDefaultAsync(x => x.CustomerId == id); if (customer == null) return Results.NotFound(); // ILogger events are sent to OpenTracing as well! logger.LogInformation("Returning data for customer {CustomerId}", id); return Results.Ok(customer); }); app.Run(); ================================================ FILE: samples/net7.0/CustomersApi/Properties/launchSettings.json ================================================ { "profiles": { "CustomersApi": { "commandName": "Project", "launchBrowser": false, "launchUrl": "http://localhost:5001", "environmentVariables": { "ASPNETCORE_ENVIRONMENT": "Development" } } } } ================================================ FILE: samples/net7.0/CustomersApi/appsettings.json ================================================ { "Logging": { "IncludeScopes": false, "LogLevel": { "Default": "Debug", "System": "Information", "Microsoft": "Information" } } } ================================================ FILE: samples/net7.0/FrontendWeb/Controllers/HomeController.cs ================================================ using System.Text; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.Rendering; using Newtonsoft.Json; using Shared; namespace FrontendWeb.Controllers; public class HomeController : Controller { private readonly HttpClient _httpClient; public HomeController(HttpClient httpClient) { _httpClient = httpClient; } [HttpGet] public IActionResult Index() { return View(); } [HttpGet] public async Task PlaceOrder() { ViewBag.Customers = await GetCustomers(); return View(new PlaceOrderCommand { ItemNumber = "ABC11", Quantity = 1 }); } [HttpPost, ValidateAntiForgeryToken] public async Task PlaceOrder(PlaceOrderCommand cmd) { if (!ModelState.IsValid) { ViewBag.Customers = await GetCustomers(); return View(cmd); } string body = JsonConvert.SerializeObject(cmd); var request = new HttpRequestMessage { Method = HttpMethod.Post, RequestUri = new Uri(Constants.OrdersUrl + "orders"), Content = new StringContent(body, Encoding.UTF8, "application/json") }; await _httpClient.SendAsync(request); return RedirectToAction("Index"); } private async Task> GetCustomers() { var request = new HttpRequestMessage { Method = HttpMethod.Get, RequestUri = new Uri(Constants.CustomersUrl + "customers") }; var response = await _httpClient.SendAsync(request); response.EnsureSuccessStatusCode(); var body = await response.Content.ReadAsStringAsync(); return JsonConvert.DeserializeObject>(body) .Select(x => new SelectListItem { Value = x.CustomerId.ToString(), Text = x.Name }); } } ================================================ FILE: samples/net7.0/FrontendWeb/FrontendWeb.csproj ================================================  net7.0 enable enable ================================================ FILE: samples/net7.0/FrontendWeb/Program.cs ================================================ using Shared; var builder = WebApplication.CreateBuilder(args); // Add services to the container. builder.WebHost.UseUrls(Constants.FrontendUrl); // Registers and starts Jaeger (see Shared.JaegerServiceCollectionExtensions) builder.Services.AddJaeger(); // Enables OpenTracing instrumentation for ASP.NET Core, CoreFx, EF Core builder.Services.AddOpenTracing(); builder.Services.AddSingleton(); builder.Services.AddMvc(); var app = builder.Build(); // Configure the HTTP request pipeline. app.MapDefaultControllerRoute(); app.Run(); ================================================ FILE: samples/net7.0/FrontendWeb/Properties/launchSettings.json ================================================ { "profiles": { "FrontendWeb": { "commandName": "Project", "launchBrowser": false, "launchUrl": "http://localhost:5000", "environmentVariables": { "ASPNETCORE_ENVIRONMENT": "Development" } } } } ================================================ FILE: samples/net7.0/FrontendWeb/Views/Home/Index.cshtml ================================================  FrontendWeb

FrontendWeb

This is the beautiful web frontend.

Refresh this page a few times and check the Jaeger UI - you should already see traces!

Place an order

================================================ FILE: samples/net7.0/FrontendWeb/Views/Home/PlaceOrder.cshtml ================================================ @model Shared.PlaceOrderCommand FrontendWeb

FrontendWeb

Place an order

Customer: @Html.DropDownListFor(x => x.CustomerId, (IEnumerable)ViewBag.Customers)
ItemNumber: @Html.TextBoxFor(x => x.ItemNumber)
Quantity: @Html.TextBoxFor(x => x.Quantity)
================================================ FILE: samples/net7.0/FrontendWeb/Views/_ViewImports.cshtml ================================================ @using FrontendWeb @addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers ================================================ FILE: samples/net7.0/FrontendWeb/appsettings.json ================================================ { "Logging": { "IncludeScopes": false, "LogLevel": { "Default": "Debug", "System": "Information", "Microsoft": "Information", "OpenTracing": "Debug" } } } ================================================ FILE: samples/net7.0/OrdersApi/Controllers/OrdersController.cs ================================================ using Microsoft.AspNetCore.Mvc; using Microsoft.EntityFrameworkCore; using Newtonsoft.Json; using OpenTracing; using OrdersApi.DataStore; using Shared; namespace OrdersApi.Controllers; [Route("orders")] public class OrdersController : Controller { private readonly OrdersDbContext _dbContext; private readonly HttpClient _httpClient; private readonly ITracer _tracer; public OrdersController(OrdersDbContext dbContext, HttpClient httpClient, ITracer tracer) { _dbContext = dbContext ?? throw new ArgumentNullException(nameof(dbContext)); _httpClient = httpClient ?? throw new ArgumentNullException(nameof(httpClient)); _tracer = tracer ?? throw new ArgumentNullException(nameof(tracer)); } [HttpGet] public async Task Index() { var orders = await _dbContext.Orders.ToListAsync(); return Ok(orders.Select(x => new { x.OrderId }).ToList()); } [HttpPost] public async Task Index([FromBody] PlaceOrderCommand cmd) { var customer = await GetCustomer(cmd.CustomerId); var order = new Order { CustomerId = cmd.CustomerId, ItemNumber = cmd.ItemNumber, Quantity = cmd.Quantity }; _dbContext.Orders.Add(order); await _dbContext.SaveChangesAsync(); _tracer.ActiveSpan?.Log(new Dictionary { { "event", "OrderPlaced" }, { "orderId", order.OrderId }, { "customer", order.CustomerId }, { "customer_name", customer.Name }, { "item_number", order.ItemNumber }, { "quantity", order.Quantity } }); return Ok(); } private async Task GetCustomer(int customerId) { var request = new HttpRequestMessage { Method = HttpMethod.Get, RequestUri = new Uri(Constants.CustomersUrl + "customers/" + customerId) }; var response = await _httpClient.SendAsync(request); response.EnsureSuccessStatusCode(); var body = await response.Content.ReadAsStringAsync(); return JsonConvert.DeserializeObject(body); } } ================================================ FILE: samples/net7.0/OrdersApi/DataStore/Order.cs ================================================ using System.ComponentModel.DataAnnotations; namespace OrdersApi.DataStore; public class Order { [Key] public int OrderId { get; set; } public int CustomerId { get; set; } [Required, StringLength(10)] public string ItemNumber { get; set; } = string.Empty; [Required, Range(1, 100)] public int Quantity { get; set; } } ================================================ FILE: samples/net7.0/OrdersApi/DataStore/OrdersDbContext.cs ================================================ using Microsoft.EntityFrameworkCore; namespace OrdersApi.DataStore; public class OrdersDbContext : DbContext { public OrdersDbContext(DbContextOptions options) : base(options) { } public DbSet Orders => Set(); public void Seed() { if (Database.EnsureCreated()) { Database.Migrate(); SaveChanges(); } } } ================================================ FILE: samples/net7.0/OrdersApi/OrdersApi.csproj ================================================  net7.0 enable enable ================================================ FILE: samples/net7.0/OrdersApi/Program.cs ================================================ using Microsoft.EntityFrameworkCore; using OrdersApi.DataStore; using Shared; var builder = WebApplication.CreateBuilder(args); // Add services to the container. builder.WebHost.UseUrls(Constants.OrdersUrl); // Registers and starts Jaeger (see Shared.JaegerServiceCollectionExtensions) builder.Services.AddJaeger(); // Enables OpenTracing instrumentation for ASP.NET Core, CoreFx, EF Core builder.Services.AddOpenTracing(builder => { builder.ConfigureAspNetCore(options => { // We don't need any tracing data for our health endpoint. options.Hosting.IgnorePatterns.Add(ctx => ctx.Request.Path == "/health"); }); }); // Adds a SqlServer DB to show EFCore traces. builder.Services.AddDbContext(options => { options.UseSqlServer("Server=(localdb)\\mssqllocaldb;Database=Orders-net5;Trusted_Connection=True;MultipleActiveResultSets=true"); }); builder.Services.AddSingleton(); builder.Services.AddMvc(); builder.Services.AddHealthChecks() .AddDbContextCheck(); var app = builder.Build(); // Load some dummy data into the db. using (var scope = app.Services.CreateScope()) { var dbContext = scope.ServiceProvider.GetRequiredService(); dbContext.Seed(); } // Configure the HTTP request pipeline. app.MapGet("/", () => "Orders API"); app.MapHealthChecks("/health"); app.MapDefaultControllerRoute(); app.Run(); ================================================ FILE: samples/net7.0/OrdersApi/Properties/launchSettings.json ================================================ { "profiles": { "OrdersApi": { "commandName": "Project", "launchBrowser": false, "launchUrl": "http://localhost:5002", "environmentVariables": { "ASPNETCORE_ENVIRONMENT": "Development" } } } } ================================================ FILE: samples/net7.0/OrdersApi/appsettings.json ================================================ { "Logging": { "IncludeScopes": false, "LogLevel": { "Default": "Debug", "System": "Information", "Microsoft": "Information" } } } ================================================ FILE: samples/net7.0/Shared/Constants.cs ================================================ namespace Shared; public class Constants { public const string FrontendUrl = "http://localhost:5000/"; public const string CustomersUrl = "http://localhost:5001/"; public const string OrdersUrl = "http://localhost:5002/"; } ================================================ FILE: samples/net7.0/Shared/Customer.cs ================================================ namespace Shared; public class Customer { public int CustomerId { get; set; } public string Name { get; set; } public Customer() { CustomerId = 0; Name = string.Empty; } public Customer(int customerId, string name) { CustomerId = customerId; Name = name; } } ================================================ FILE: samples/net7.0/Shared/JaegerServiceCollectionExtensions.cs ================================================ using System.Reflection; using Jaeger; using Jaeger.Reporters; using Jaeger.Samplers; using Jaeger.Senders.Thrift; using Microsoft.Extensions.Logging; using OpenTracing; using OpenTracing.Contrib.NetCore.Configuration; using OpenTracing.Util; namespace Microsoft.Extensions.DependencyInjection; public static class JaegerServiceCollectionExtensions { private static readonly Uri _jaegerUri = new Uri("http://localhost:14268/api/traces"); public static IServiceCollection AddJaeger(this IServiceCollection services) { if (services == null) throw new ArgumentNullException(nameof(services)); services.AddSingleton(serviceProvider => { string serviceName = Assembly.GetEntryAssembly()?.GetName().Name ?? "unknown-service"; ILoggerFactory loggerFactory = serviceProvider.GetRequiredService(); ISampler sampler = new ConstSampler(sample: true); IReporter reporter = new RemoteReporter.Builder() .WithSender(new HttpSender.Builder(_jaegerUri.ToString()).Build()) .Build(); ITracer tracer = new Tracer.Builder(serviceName) .WithLoggerFactory(loggerFactory) .WithSampler(sampler) .WithReporter(reporter) .Build(); GlobalTracer.Register(tracer); return tracer; }); // Prevent endless loops when OpenTracing is tracking HTTP requests to Jaeger. services.Configure(options => { options.IgnorePatterns.Add(request => request.RequestUri != null && _jaegerUri.IsBaseOf(request.RequestUri)); }); return services; } } ================================================ FILE: samples/net7.0/Shared/PlaceOrderCommand.cs ================================================ using System.ComponentModel.DataAnnotations; namespace Shared; public class PlaceOrderCommand { [Required, Range(1, int.MaxValue)] public int CustomerId { get; set; } [Required, StringLength(10)] public string ItemNumber { get; set; } = string.Empty; [Required, Range(1, 100)] public int Quantity { get; set; } } ================================================ FILE: samples/net7.0/Shared/Shared.csproj ================================================  net7.0 enable enable ================================================ FILE: samples/net7.0/TrafficGenerator/Program.cs ================================================ using TrafficGenerator; using var host = Host.CreateDefaultBuilder(args) .ConfigureServices((hostContext, services) => { // Registers and starts Jaeger (see Shared.JaegerServiceCollectionExtensions) services.AddJaeger(); services.AddOpenTracing(); services.AddHostedService(); }) .Build(); await host.RunAsync(); ================================================ FILE: samples/net7.0/TrafficGenerator/TrafficGenerator.csproj ================================================ net7.0 enable enable ================================================ FILE: samples/net7.0/TrafficGenerator/Worker.cs ================================================ using Shared; namespace TrafficGenerator; public class Worker : BackgroundService { private readonly ILogger _logger; public Worker(ILogger logger) { _logger = logger ?? throw new ArgumentNullException(nameof(logger)); } protected override async Task ExecuteAsync(CancellationToken stoppingToken) { try { HttpClient customersHttpClient = new HttpClient(); customersHttpClient.BaseAddress = new Uri(Constants.CustomersUrl); HttpClient ordersHttpClient = new HttpClient(); ordersHttpClient.BaseAddress = new Uri(Constants.OrdersUrl); while (!stoppingToken.IsCancellationRequested) { HttpResponseMessage ordersHealthResponse = await ordersHttpClient.GetAsync("health"); _logger.LogInformation($"Health of 'orders'-endpoint: '{ordersHealthResponse.StatusCode}'"); HttpResponseMessage customersHealthResponse = await customersHttpClient.GetAsync("health"); _logger.LogInformation($"Health of 'customers'-endpoint: '{customersHealthResponse.StatusCode}'"); _logger.LogInformation("Requesting customers"); HttpResponseMessage response = await customersHttpClient.GetAsync("customers"); _logger.LogInformation($"Response was '{response.StatusCode}'"); await Task.Delay(TimeSpan.FromSeconds(5), stoppingToken); } } catch (TaskCanceledException) { /* Application should be stopped -> no-op */ } catch (Exception ex) { _logger.LogError(ex, "Unhandled exception"); } } } ================================================ FILE: samples/net7.0/TrafficGenerator/appsettings.json ================================================ { "Logging": { "LogLevel": { "Default": "Debug", "System": "Information", "Microsoft": "Warning", "Microsoft.AspNetCore.Hosting": "Information" } } } ================================================ FILE: samples/netcoreapp3.1/CustomersApi/Controllers/CustomersController.cs ================================================ using System.Linq; using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Logging; using Samples.CustomersApi.DataStore; namespace Samples.CustomersApi.Controllers { [Route("customers")] public class CustomersController : Controller { private readonly CustomerDbContext _dbContext; private readonly ILogger _logger; public CustomersController(CustomerDbContext dbContext, ILogger logger) { _dbContext = dbContext; _logger = logger; } [HttpGet] public IActionResult Index() { return Json(_dbContext.Customers.ToList()); } [HttpGet("{id:int}")] public IActionResult Index(int id) { var customer = _dbContext.Customers.FirstOrDefault(x => x.CustomerId == id); if (customer == null) return NotFound(); // ILogger events are sent to OpenTracing as well! _logger.LogInformation("Returning data for customer {CustomerId}", id); return Json(customer); } } } ================================================ FILE: samples/netcoreapp3.1/CustomersApi/CustomersApi.csproj ================================================  netcoreapp3.1 ================================================ FILE: samples/netcoreapp3.1/CustomersApi/DataStore/CustomerDbContext.cs ================================================ using Microsoft.EntityFrameworkCore; using Shared; namespace Samples.CustomersApi.DataStore { public class CustomerDbContext : DbContext { public CustomerDbContext(DbContextOptions options) : base(options) { } public DbSet Customers { get; set; } public void Seed() { if (Database.EnsureCreated()) { Database.Migrate(); Customers.Add(new Customer(1, "Marcel Belding")); Customers.Add(new Customer(2, "Phyllis Schriver")); Customers.Add(new Customer(3, "Estefana Balderrama")); Customers.Add(new Customer(4, "Kenyetta Lone")); Customers.Add(new Customer(5, "Vernita Fernald")); Customers.Add(new Customer(6, "Tessie Storrs")); SaveChanges(); } } } } ================================================ FILE: samples/netcoreapp3.1/CustomersApi/Program.cs ================================================ using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; using Shared; namespace Samples.CustomersApi { public class Program { public static void Main(string[] args) { CreateHostBuilder(args).Build().Run(); } public static IHostBuilder CreateHostBuilder(string[] args) { return Host.CreateDefaultBuilder(args) .ConfigureWebHostDefaults(webBuilder => { webBuilder .UseStartup() .UseUrls(Constants.CustomersUrl); }) .ConfigureServices(services => { // Registers and starts Jaeger (see Shared.JaegerServiceCollectionExtensions) services.AddJaeger(); // Enables OpenTracing instrumentation for ASP.NET Core, CoreFx, EF Core services.AddOpenTracing(builder => { builder.ConfigureAspNetCore(options => { // We don't need any tracing data for our health endpoint. options.Hosting.IgnorePatterns.Add(ctx => ctx.Request.Path == "/health"); }); builder.ConfigureEntityFrameworkCore(options => { // This is an example for how certain EF Core commands can be ignored. // As en example, we're ignoring the "PRAGMA foreign_keys=ON;" commands that are executed by Sqlite. // Remove this code to see those statements. options.IgnorePatterns.Add(cmd => cmd.Command.CommandText.StartsWith("PRAGMA")); }); }); }); } } } ================================================ FILE: samples/netcoreapp3.1/CustomersApi/Properties/launchSettings.json ================================================ { "profiles": { "CustomersApi": { "commandName": "Project", "launchBrowser": false, "launchUrl": "http://localhost:5001", "environmentVariables": { "ASPNETCORE_ENVIRONMENT": "Development" } } } } ================================================ FILE: samples/netcoreapp3.1/CustomersApi/Startup.cs ================================================ using System; using Microsoft.AspNetCore.Builder; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.DependencyInjection; using Samples.CustomersApi.DataStore; namespace Samples.CustomersApi { public class Startup { public void ConfigureServices(IServiceCollection services) { // Adds a Sqlite DB to show EFCore traces. services .AddDbContext(options => { options.UseSqlite("Data Source=DataStore/customers.db"); }); services.AddMvc(); services.AddHealthChecks() .AddDbContextCheck(); } public void Configure(IApplicationBuilder app) { // Load some dummy data into the InMemory db. BootstrapDataStore(app.ApplicationServices); app.UseDeveloperExceptionPage(); app.UseRouting(); app.UseAuthentication(); app.UseAuthorization(); app.UseEndpoints(endpoints => { endpoints.MapControllers(); endpoints.MapHealthChecks("/health"); }); } public void BootstrapDataStore(IServiceProvider serviceProvider) { using (var scope = serviceProvider.CreateScope()) { var dbContext = scope.ServiceProvider.GetRequiredService(); dbContext.Seed(); } } } } ================================================ FILE: samples/netcoreapp3.1/CustomersApi/appsettings.json ================================================ { "Logging": { "IncludeScopes": false, "LogLevel": { "Default": "Debug", "System": "Information", "Microsoft": "Information" } } } ================================================ FILE: samples/netcoreapp3.1/FrontendWeb/Controllers/HomeController.cs ================================================ using System; using System.Collections.Generic; using System.Linq; using System.Net.Http; using System.Text; using System.Threading.Tasks; using Shared; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.Rendering; using Newtonsoft.Json; namespace Samples.FrontendWeb.Controllers { public class HomeController : Controller { private readonly HttpClient _httpClient; public HomeController(HttpClient httpClient) { _httpClient = httpClient; } [HttpGet] public IActionResult Index() { return View(); } [HttpGet] public async Task PlaceOrder() { ViewBag.Customers = await GetCustomers(); return View(new PlaceOrderCommand { ItemNumber = "ABC11", Quantity = 1 }); } [HttpPost, ValidateAntiForgeryToken] public async Task PlaceOrder(PlaceOrderCommand cmd) { if (!ModelState.IsValid) { ViewBag.Customers = await GetCustomers(); return View(cmd); } string body = JsonConvert.SerializeObject(cmd); var request = new HttpRequestMessage { Method = HttpMethod.Post, RequestUri = new Uri(Constants.OrdersUrl + "orders"), Content = new StringContent(body, Encoding.UTF8, "application/json") }; await _httpClient.SendAsync(request); return RedirectToAction("Index"); } private async Task> GetCustomers() { var request = new HttpRequestMessage { Method = HttpMethod.Get, RequestUri = new Uri(Constants.CustomersUrl + "customers") }; var response = await _httpClient.SendAsync(request); response.EnsureSuccessStatusCode(); var body = await response.Content.ReadAsStringAsync(); return JsonConvert.DeserializeObject>(body) .Select(x => new SelectListItem { Value = x.CustomerId.ToString(), Text = x.Name }); } } } ================================================ FILE: samples/netcoreapp3.1/FrontendWeb/FrontendWeb.csproj ================================================  netcoreapp3.1 ================================================ FILE: samples/netcoreapp3.1/FrontendWeb/Program.cs ================================================ using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; using Shared; namespace Samples.FrontendWeb { public class Program { public static void Main(string[] args) { CreateHostBuilder(args).Build().Run(); } public static IHostBuilder CreateHostBuilder(string[] args) { return Host.CreateDefaultBuilder(args) .ConfigureWebHostDefaults(webBuilder => { webBuilder .UseStartup() .UseUrls(Constants.FrontendUrl); }) .ConfigureServices(services => { // Registers and starts Jaeger (see Shared.JaegerServiceCollectionExtensions) services.AddJaeger(); // Enables OpenTracing instrumentation for ASP.NET Core, CoreFx, EF Core services.AddOpenTracing(); }); } } } ================================================ FILE: samples/netcoreapp3.1/FrontendWeb/Properties/launchSettings.json ================================================ { "profiles": { "FrontendWeb": { "commandName": "Project", "launchBrowser": false, "launchUrl": "http://localhost:5000", "environmentVariables": { "ASPNETCORE_ENVIRONMENT": "Development" } } } } ================================================ FILE: samples/netcoreapp3.1/FrontendWeb/Startup.cs ================================================ using System.Net.Http; using Microsoft.AspNetCore.Builder; using Microsoft.Extensions.DependencyInjection; namespace Samples.FrontendWeb { public class Startup { public void ConfigureServices(IServiceCollection services) { services.AddSingleton(); services.AddMvc(); } public void Configure(IApplicationBuilder app) { app.UseDeveloperExceptionPage(); app.UseRouting(); app.UseAuthentication(); app.UseAuthorization(); app.UseEndpoints(endpoints => { endpoints.MapDefaultControllerRoute(); }); } } } ================================================ FILE: samples/netcoreapp3.1/FrontendWeb/Views/Home/Index.cshtml ================================================  FrontendWeb

FrontendWeb

This is the beautiful web frontend.

Refresh this page a few times and check the Jaeger UI - you should already see traces!

Place an order

================================================ FILE: samples/netcoreapp3.1/FrontendWeb/Views/Home/PlaceOrder.cshtml ================================================ @model Shared.PlaceOrderCommand FrontendWeb

FrontendWeb

Place an order

Customer: @Html.DropDownListFor(x => x.CustomerId, (IEnumerable)ViewBag.Customers)
ItemNumber: @Html.TextBoxFor(x => x.ItemNumber)
Quantity: @Html.TextBoxFor(x => x.Quantity)
================================================ FILE: samples/netcoreapp3.1/FrontendWeb/Views/_ViewImports.cshtml ================================================ @using Samples.FrontendWeb @addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers ================================================ FILE: samples/netcoreapp3.1/FrontendWeb/appsettings.json ================================================ { "Logging": { "IncludeScopes": false, "LogLevel": { "Default": "Debug", "System": "Information", "Microsoft": "Information", "OpenTracing": "Debug" } } } ================================================ FILE: samples/netcoreapp3.1/OrdersApi/Controllers/OrdersController.cs ================================================ using System; using System.Collections.Generic; using System.Linq; using System.Net.Http; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using Microsoft.EntityFrameworkCore; using Newtonsoft.Json; using OpenTracing; using OrdersApi.DataStore; using Shared; namespace Samples.OrdersApi.Controllers { [Route("orders")] public class OrdersController : Controller { private readonly OrdersDbContext _dbContext; private readonly HttpClient _httpClient; private readonly ITracer _tracer; public OrdersController(OrdersDbContext dbContext, HttpClient httpClient, ITracer tracer) { _dbContext = dbContext ?? throw new ArgumentNullException(nameof(dbContext)); _httpClient = httpClient ?? throw new ArgumentNullException(nameof(httpClient)); _tracer = tracer ?? throw new ArgumentNullException(nameof(tracer)); } [HttpGet] public async Task Index() { var orders = await _dbContext.Orders.ToListAsync(); return Ok(orders.Select(x => new { x.OrderId }).ToList()); } [HttpPost] public async Task Index([FromBody] PlaceOrderCommand cmd) { var customer = await GetCustomer(cmd.CustomerId.Value); var order = new Order { CustomerId = cmd.CustomerId.Value, ItemNumber = cmd.ItemNumber, Quantity = cmd.Quantity }; _dbContext.Orders.Add(order); await _dbContext.SaveChangesAsync(); _tracer.ActiveSpan?.Log(new Dictionary { { "event", "OrderPlaced" }, { "orderId", order.OrderId }, { "customer", order.CustomerId }, { "customer_name", customer.Name }, { "item_number", order.ItemNumber }, { "quantity", order.Quantity } }); return Ok(); } private async Task GetCustomer(int customerId) { var request = new HttpRequestMessage { Method = HttpMethod.Get, RequestUri = new Uri(Constants.CustomersUrl + "customers/" + customerId) }; var response = await _httpClient.SendAsync(request); response.EnsureSuccessStatusCode(); var body = await response.Content.ReadAsStringAsync(); return JsonConvert.DeserializeObject(body); } } } ================================================ FILE: samples/netcoreapp3.1/OrdersApi/DataStore/Order.cs ================================================ using System; using System.ComponentModel.DataAnnotations; namespace OrdersApi.DataStore { public class Order { [Key] public int OrderId { get; set; } public int CustomerId { get; set; } [Required, StringLength(10)] public string ItemNumber { get; set; } [Required, Range(1, 100)] public int Quantity { get; set; } } } ================================================ FILE: samples/netcoreapp3.1/OrdersApi/DataStore/OrdersDbContext.cs ================================================ using Microsoft.EntityFrameworkCore; namespace OrdersApi.DataStore { public class OrdersDbContext : DbContext { public OrdersDbContext(DbContextOptions options) : base(options) { } public DbSet Orders { get; set; } public void Seed() { if (Database.EnsureCreated()) { Database.Migrate(); SaveChanges(); } } } } ================================================ FILE: samples/netcoreapp3.1/OrdersApi/OrdersApi.csproj ================================================  netcoreapp3.1 ================================================ FILE: samples/netcoreapp3.1/OrdersApi/Program.cs ================================================ using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; using Shared; namespace Samples.OrdersApi { public class Program { public static void Main(string[] args) { CreateHostBuilder(args).Build().Run(); } public static IHostBuilder CreateHostBuilder(string[] args) { return Host.CreateDefaultBuilder(args) .ConfigureWebHostDefaults(webBuilder => { webBuilder .UseStartup() .UseUrls(Constants.OrdersUrl); }) .ConfigureServices(services => { // Registers and starts Jaeger (see Shared.JaegerServiceCollectionExtensions) services.AddJaeger(); // Enables OpenTracing instrumentation for ASP.NET Core, CoreFx, EF Core services.AddOpenTracing(builder => { builder.ConfigureAspNetCore(options => { // We don't need any tracing data for our health endpoint. options.Hosting.IgnorePatterns.Add(ctx => ctx.Request.Path == "/health"); }); }); }); } } } ================================================ FILE: samples/netcoreapp3.1/OrdersApi/Properties/launchSettings.json ================================================ { "profiles": { "OrdersApi": { "commandName": "Project", "launchBrowser": false, "launchUrl": "http://localhost:5002", "environmentVariables": { "ASPNETCORE_ENVIRONMENT": "Development" } } } } ================================================ FILE: samples/netcoreapp3.1/OrdersApi/Startup.cs ================================================ using System; using System.Net.Http; using Microsoft.AspNetCore.Builder; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.DependencyInjection; using OrdersApi.DataStore; namespace Samples.OrdersApi { public class Startup { public void ConfigureServices(IServiceCollection services) { // Adds a SqlServer DB to show EFCore traces. services .AddDbContext(options => { options.UseSqlServer("Server=(localdb)\\mssqllocaldb;Database=Orders-netcoreapp31;Trusted_Connection=True;MultipleActiveResultSets=true"); }); services.AddSingleton(); services.AddMvc(); services.AddHealthChecks() .AddDbContextCheck(); } public void Configure(IApplicationBuilder app) { // Load some dummy data into the db. BootstrapDataStore(app.ApplicationServices); app.UseDeveloperExceptionPage(); app.UseRouting(); app.UseAuthentication(); app.UseAuthorization(); app.UseEndpoints(endpoints => { endpoints.MapDefaultControllerRoute(); endpoints.MapHealthChecks("/health"); }); } private void BootstrapDataStore(IServiceProvider serviceProvider) { using (var scope = serviceProvider.CreateScope()) { var dbContext = scope.ServiceProvider.GetRequiredService(); dbContext.Seed(); } } } } ================================================ FILE: samples/netcoreapp3.1/OrdersApi/appsettings.json ================================================ { "Logging": { "IncludeScopes": false, "LogLevel": { "Default": "Debug", "System": "Information", "Microsoft": "Information" } } } ================================================ FILE: samples/netcoreapp3.1/Shared/Constants.cs ================================================ namespace Shared { public class Constants { public const string FrontendUrl = "http://localhost:5000/"; public const string CustomersUrl = "http://localhost:5001/"; public const string OrdersUrl = "http://localhost:5002/"; } } ================================================ FILE: samples/netcoreapp3.1/Shared/Customer.cs ================================================ namespace Shared { public class Customer { public int CustomerId { get; set; } public string Name { get; set; } public Customer() { } public Customer(int customerId, string name) { CustomerId = customerId; Name = name; } } } ================================================ FILE: samples/netcoreapp3.1/Shared/JaegerServiceCollectionExtensions.cs ================================================ using System; using System.Reflection; using Jaeger; using Jaeger.Reporters; using Jaeger.Samplers; using Jaeger.Senders.Thrift; using Microsoft.Extensions.Logging; using OpenTracing; using OpenTracing.Contrib.NetCore.Configuration; using OpenTracing.Util; namespace Microsoft.Extensions.DependencyInjection { public static class JaegerServiceCollectionExtensions { private static readonly Uri _jaegerUri = new Uri("http://localhost:14268/api/traces"); public static IServiceCollection AddJaeger(this IServiceCollection services) { if (services == null) throw new ArgumentNullException(nameof(services)); services.AddSingleton(serviceProvider => { string serviceName = Assembly.GetEntryAssembly().GetName().Name; ILoggerFactory loggerFactory = serviceProvider.GetRequiredService(); ISampler sampler = new ConstSampler(sample: true); IReporter reporter = new RemoteReporter.Builder() .WithSender(new HttpSender.Builder(_jaegerUri.ToString()).Build()) .Build(); ITracer tracer = new Tracer.Builder(serviceName) .WithLoggerFactory(loggerFactory) .WithSampler(sampler) .WithReporter(reporter) .Build(); GlobalTracer.Register(tracer); return tracer; }); // Prevent endless loops when OpenTracing is tracking HTTP requests to Jaeger. services.Configure(options => { options.IgnorePatterns.Add(request => _jaegerUri.IsBaseOf(request.RequestUri)); }); return services; } } } ================================================ FILE: samples/netcoreapp3.1/Shared/PlaceOrderCommand.cs ================================================ using System.ComponentModel.DataAnnotations; namespace Shared { public class PlaceOrderCommand { [Required] public int? CustomerId { get; set; } [Required, StringLength(10)] public string ItemNumber { get; set; } [Required, Range(1, 100)] public int Quantity { get; set; } } } ================================================ FILE: samples/netcoreapp3.1/Shared/Shared.csproj ================================================  netcoreapp3.1 ================================================ FILE: samples/netcoreapp3.1/TrafficGenerator/Program.cs ================================================ using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; namespace TrafficGenerator { class Program { public static void Main(string[] args) { CreateHostBuilder(args).Build().Run(); } public static IHostBuilder CreateHostBuilder(string[] args) => Host.CreateDefaultBuilder(args) .ConfigureServices(services => { // Registers and starts Jaeger (see Shared.JaegerServiceCollectionExtensions) services.AddJaeger(); services.AddOpenTracing(); services.AddHostedService(); }); } } ================================================ FILE: samples/netcoreapp3.1/TrafficGenerator/TrafficGenerator.csproj ================================================ netcoreapp3.1 ================================================ FILE: samples/netcoreapp3.1/TrafficGenerator/Worker.cs ================================================ using System; using System.Net.Http; using System.Threading; using System.Threading.Tasks; using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Logging; using Shared; namespace TrafficGenerator { public class Worker : BackgroundService { private readonly ILogger _logger; public Worker(ILogger logger) { _logger = logger ?? throw new ArgumentNullException(nameof(logger)); } protected override async Task ExecuteAsync(CancellationToken stoppingToken) { try { HttpClient customersHttpClient = new HttpClient(); customersHttpClient.BaseAddress = new Uri(Constants.CustomersUrl); HttpClient ordersHttpClient = new HttpClient(); ordersHttpClient.BaseAddress = new Uri(Constants.OrdersUrl); while (!stoppingToken.IsCancellationRequested) { HttpResponseMessage ordershealthResponse = await ordersHttpClient.GetAsync("health"); _logger.LogInformation($"Health of 'orders'-endpoint: '{ordershealthResponse.StatusCode}'"); HttpResponseMessage customersHealthResponse = await customersHttpClient.GetAsync("health"); _logger.LogInformation($"Health of 'customers'-endpoint: '{customersHealthResponse.StatusCode}'"); _logger.LogInformation("Requesting customers"); HttpResponseMessage response = await customersHttpClient.GetAsync("customers"); _logger.LogInformation($"Response was '{response.StatusCode}'"); await Task.Delay(TimeSpan.FromSeconds(5), stoppingToken); } } catch (TaskCanceledException) { /* Application should be stopped -> no-op */ } catch (Exception ex) { _logger.LogError(ex, "Unhandled exception"); } } } } ================================================ FILE: samples/netcoreapp3.1/TrafficGenerator/appsettings.json ================================================ { "Logging": { "LogLevel": { "Default": "Debug", "System": "Information", "Microsoft": "Warning", "Microsoft.AspNetCore.Hosting": "Information" } } } ================================================ FILE: src/Directory.Build.props ================================================ true Christian Weiss package-icon.png https://avatars0.githubusercontent.com/u/15482765 https://github.com/opentracing-contrib/csharp-netcore Apache-2.0 https://github.com/opentracing-contrib/csharp-netcore/releases/tag/v$(Version) $(NoWarn);CS1591 true true true snupkg ================================================ FILE: src/OpenTracing.Contrib.NetCore/AspNetCore/AspNetCoreDiagnosticOptions.cs ================================================ using OpenTracing.Contrib.NetCore.AspNetCore; namespace OpenTracing.Contrib.NetCore.Configuration { public class AspNetCoreDiagnosticOptions : DiagnosticOptions { public HostingOptions Hosting { get; } = new HostingOptions(); public AspNetCoreDiagnosticOptions() { // We create separate spans for MVC actions & results so we don't need these additional events by default. IgnoredEvents.Add("Microsoft.AspNetCore.Mvc.BeforeOnResourceExecuting"); IgnoredEvents.Add("Microsoft.AspNetCore.Mvc.BeforeOnActionExecution"); IgnoredEvents.Add("Microsoft.AspNetCore.Mvc.BeforeOnActionExecuting"); IgnoredEvents.Add("Microsoft.AspNetCore.Mvc.AfterOnActionExecuting"); IgnoredEvents.Add("Microsoft.AspNetCore.Mvc.BeforeActionMethod"); IgnoredEvents.Add("Microsoft.AspNetCore.Mvc.BeforeControllerActionMethod"); IgnoredEvents.Add("Microsoft.AspNetCore.Mvc.AfterControllerActionMethod"); IgnoredEvents.Add("Microsoft.AspNetCore.Mvc.AfterActionMethod"); IgnoredEvents.Add("Microsoft.AspNetCore.Mvc.BeforeOnActionExecuted"); IgnoredEvents.Add("Microsoft.AspNetCore.Mvc.AfterOnActionExecuted"); IgnoredEvents.Add("Microsoft.AspNetCore.Mvc.AfterOnActionExecution"); IgnoredEvents.Add("Microsoft.AspNetCore.Mvc.BeforeOnActionExecuted"); IgnoredEvents.Add("Microsoft.AspNetCore.Mvc.AfterOnActionExecuted"); IgnoredEvents.Add("Microsoft.AspNetCore.Mvc.AfterOnActionExecution"); IgnoredEvents.Add("Microsoft.AspNetCore.Mvc.BeforeOnResultExecuting"); IgnoredEvents.Add("Microsoft.AspNetCore.Mvc.AfterOnResultExecuting"); IgnoredEvents.Add("Microsoft.AspNetCore.Mvc.BeforeOnResultExecuted"); IgnoredEvents.Add("Microsoft.AspNetCore.Mvc.AfterOnResultExecuted"); IgnoredEvents.Add("Microsoft.AspNetCore.Mvc.BeforeOnResourceExecuted"); IgnoredEvents.Add("Microsoft.AspNetCore.Mvc.AfterOnResourceExecuted"); IgnoredEvents.Add("Microsoft.AspNetCore.Mvc.AfterOnResourceExecuting"); IgnoredEvents.Add("Microsoft.AspNetCore.Mvc.Razor.BeginInstrumentationContext"); IgnoredEvents.Add("Microsoft.AspNetCore.Mvc.Razor.EndInstrumentationContext"); } } } ================================================ FILE: src/OpenTracing.Contrib.NetCore/AspNetCore/AspNetCoreDiagnostics.cs ================================================ using System; using System.Collections.Generic; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Http.Extensions; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.Abstractions; using Microsoft.AspNetCore.Mvc.Controllers; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; using OpenTracing.Contrib.NetCore.Configuration; using OpenTracing.Contrib.NetCore.Internal; using OpenTracing.Propagation; using OpenTracing.Tag; namespace OpenTracing.Contrib.NetCore.AspNetCore { /// /// Instruments ASP.NET Core. /// /// Unfortunately, ASP.NET Core only uses one instance /// for everything so we also only create one observer to ensure best performance. /// Hosting events: https://github.com/aspnet/Hosting/blob/dev/src/Microsoft.AspNetCore.Hosting/Internal/HostingApplicationDiagnostics.cs /// internal sealed class AspNetCoreDiagnostics : DiagnosticEventObserver { public const string DiagnosticListenerName = "Microsoft.AspNetCore"; private const string HostingScopeItemsKey = "ot-HttpRequestIn"; private const string ActionScopeItemsKey = "ot-MvcAction"; private const string ActionResultScopeItemsKey = "ot-MvcActionResult"; private const string ActionComponent = "AspNetCore.MvcAction"; private const string ActionTagActionName = "action"; private const string ActionTagControllerName = "controller"; private const string ResultComponent = "AspNetCore.MvcResult"; private const string ResultTagType = "result.type"; private static readonly PropertyFetcher _httpRequestIn_start_HttpContextFetcher = new PropertyFetcher("HttpContext"); private static readonly PropertyFetcher _httpRequestIn_stop_HttpContextFetcher = new PropertyFetcher("HttpContext"); private static readonly PropertyFetcher _unhandledException_HttpContextFetcher = new PropertyFetcher("httpContext"); private static readonly PropertyFetcher _unhandledException_ExceptionFetcher = new PropertyFetcher("exception"); private static readonly PropertyFetcher _beforeAction_httpContextFetcher = new PropertyFetcher("httpContext"); private static readonly PropertyFetcher _beforeAction_ActionDescriptorFetcher = new PropertyFetcher("actionDescriptor"); private static readonly PropertyFetcher _afterAction_httpContextFetcher = new PropertyFetcher("httpContext"); private static readonly PropertyFetcher _beforeActionResult_actionContextFetcher = new PropertyFetcher("actionContext"); private static readonly PropertyFetcher _beforeActionResult_ResultFetcher = new PropertyFetcher("result"); private static readonly PropertyFetcher _afterActionResult_actionContextFetcher = new PropertyFetcher("actionContext"); internal static readonly string NoHostSpecified = string.Empty; private readonly AspNetCoreDiagnosticOptions _options; public AspNetCoreDiagnostics(ILoggerFactory loggerFactory, ITracer tracer, IOptions options) : base(loggerFactory, tracer, options?.Value) { _options = options?.Value ?? throw new ArgumentNullException(nameof(options)); } protected override string GetListenerName() => DiagnosticListenerName; protected override bool IsSupportedEvent(string eventName) { return eventName switch { // We don't want to get the old deprecated Hosting events. "Microsoft.AspNetCore.Hosting.BeginRequest" => false, "Microsoft.AspNetCore.Hosting.EndRequest" => false, _ => true, }; } protected override IEnumerable HandledEventNames() { yield return "Microsoft.AspNetCore.Hosting.HttpRequestIn.Start"; yield return "Microsoft.AspNetCore.Hosting.UnhandledException"; yield return "Microsoft.AspNetCore.Hosting.HttpRequestIn.Stop"; yield return "Microsoft.AspNetCore.Mvc.BeforeAction"; yield return "Microsoft.AspNetCore.Mvc.AfterAction"; yield return "Microsoft.AspNetCore.Mvc.BeforeActionResult"; yield return "Microsoft.AspNetCore.Mvc.AfterActionResult"; } protected override void HandleEvent(string eventName, object untypedArg) { switch (eventName) { case "Microsoft.AspNetCore.Hosting.HttpRequestIn.Start": { var httpContext = (HttpContext)_httpRequestIn_start_HttpContextFetcher.Fetch(untypedArg); if (Tracer.ActiveSpan == null && !_options.StartRootSpans) { if (IsLogLevelTraceEnabled) { Logger.LogTrace("Ignoring request due to missing parent span"); } return; } if (ShouldIgnore(httpContext)) { if (IsLogLevelTraceEnabled) { Logger.LogTrace("Ignoring request"); } } else { var request = httpContext.Request; ISpanContext extractedSpanContext = null; if (_options.Hosting.ExtractEnabled?.Invoke(httpContext) ?? true) { extractedSpanContext = Tracer.Extract(BuiltinFormats.HttpHeaders, new RequestHeadersExtractAdapter(request.Headers)); } string operationName = _options.Hosting.OperationNameResolver(httpContext); IScope scope = Tracer.BuildSpan(operationName) .AsChildOf(extractedSpanContext) .WithTag(Tags.Component, _options.Hosting.ComponentName) .WithTag(Tags.SpanKind, Tags.SpanKindServer) .WithTag(Tags.HttpMethod, request.Method) .WithTag(Tags.HttpUrl, GetDisplayUrl(request)) .StartActive(); _options.Hosting.OnRequest?.Invoke(scope.Span, httpContext); httpContext.Items[HostingScopeItemsKey] = scope; } } break; case "Microsoft.AspNetCore.Hosting.UnhandledException": { var httpContext = (HttpContext)_unhandledException_HttpContextFetcher.Fetch(untypedArg); var exception = (Exception)_unhandledException_ExceptionFetcher.Fetch(untypedArg); var scope = httpContext.Items[HostingScopeItemsKey] as IScope; if (scope != null) { var span = scope.Span; span.SetException(exception); _options.Hosting.OnError?.Invoke(span, exception, httpContext); } } break; case "Microsoft.AspNetCore.Hosting.HttpRequestIn.Stop": { var httpContext = (HttpContext)_httpRequestIn_stop_HttpContextFetcher.Fetch(untypedArg); var scope = httpContext.Items[HostingScopeItemsKey] as IScope; if (scope != null) { httpContext.Items.Remove(HostingScopeItemsKey); scope.Span.SetTag(Tags.HttpStatus, httpContext.Response.StatusCode); scope.Dispose(); } httpContext.Items.Remove(ActionResultScopeItemsKey); httpContext.Items.Remove(ActionScopeItemsKey); } break; case "Microsoft.AspNetCore.Mvc.BeforeAction": { var httpContext = (HttpContext)_beforeAction_httpContextFetcher.Fetch(untypedArg); // We only create this span if the entire request should be traced. var scope = httpContext.Items[HostingScopeItemsKey] as IScope; if (scope != null) { // NOTE: This event is the start of the action pipeline. The action has been selected, the route // has been selected but no filters have run and model binding hasn't occured. var actionDescriptor = (ActionDescriptor)_beforeAction_ActionDescriptorFetcher.Fetch(untypedArg); var controllerActionDescriptor = actionDescriptor as ControllerActionDescriptor; string operationName = controllerActionDescriptor != null ? $"Action {controllerActionDescriptor.ControllerTypeInfo.FullName}/{controllerActionDescriptor.ActionName}" : $"Action {actionDescriptor.DisplayName}"; var actionScope = Tracer.BuildSpan(operationName) .AsChildOf(scope.Span) .WithTag(Tags.Component, ActionComponent) .WithTag(ActionTagControllerName, controllerActionDescriptor?.ControllerTypeInfo.FullName) .WithTag(ActionTagActionName, controllerActionDescriptor?.ActionName) .StartActive(); httpContext.Items[ActionScopeItemsKey] = actionScope; } } break; case "Microsoft.AspNetCore.Mvc.AfterAction": { var httpContext = (HttpContext)_afterAction_httpContextFetcher.Fetch(untypedArg); var scope = httpContext.Items[ActionScopeItemsKey] as IScope; if (scope != null) { httpContext.Items.Remove(ActionScopeItemsKey); scope.Dispose(); } } break; case "Microsoft.AspNetCore.Mvc.BeforeActionResult": { var httpContext = ((ActionContext)_beforeActionResult_actionContextFetcher.Fetch(untypedArg)).HttpContext; // We only create this span if the entire request should be traced. var scope = httpContext.Items[HostingScopeItemsKey] as IScope; if (scope != null) { // NOTE: This event is the start of the result pipeline. The action has been executed, but // we haven't yet determined which view (if any) will handle the request object result = _beforeActionResult_ResultFetcher.Fetch(untypedArg); string resultType = result.GetType().Name; string operationName = $"Result {resultType}"; var actionResultScope = Tracer.BuildSpan(operationName) .AsChildOf(scope.Span) .WithTag(Tags.Component, ResultComponent) .WithTag(ResultTagType, resultType) .StartActive(); httpContext.Items[ActionResultScopeItemsKey] = actionResultScope; } } break; case "Microsoft.AspNetCore.Mvc.AfterActionResult": { var httpContext = ((ActionContext)_afterActionResult_actionContextFetcher.Fetch(untypedArg)).HttpContext; var scope = httpContext.Items[ActionResultScopeItemsKey] as IScope; if (scope != null) { httpContext.Items.Remove(ActionResultScopeItemsKey); scope.Dispose(); } } break; default: HandleUnknownEvent(eventName, untypedArg); break; } } private static string GetDisplayUrl(HttpRequest request) { if (request.Host.HasValue) { return request.GetDisplayUrl(); } // HTTP 1.0 requests are not required to provide a Host to be valid // Since this is just for display, we can provide a string that is // not an actual Uri with only the fields that are specified. // request.GetDisplayUrl(), used above, will throw an exception // if request.Host is null. return $"{request.Scheme}://{NoHostSpecified}{request.PathBase.Value}{request.Path.Value}{request.QueryString.Value}"; } private bool ShouldIgnore(HttpContext httpContext) { foreach (Func ignore in _options.Hosting.IgnorePatterns) { if (ignore(httpContext)) return true; } return false; } } } ================================================ FILE: src/OpenTracing.Contrib.NetCore/AspNetCore/HostingOptions.cs ================================================ using System; using System.Collections.Generic; using Microsoft.AspNetCore.Http; namespace OpenTracing.Contrib.NetCore.AspNetCore { public class HostingOptions { public const string DefaultComponent = "HttpIn"; // Variables are lazily instantiated to prevent the app from crashing if the required assemblies are not referenced. private string _componentName = DefaultComponent; private List> _ignorePatterns; private Func _operationNameResolver; /// /// Allows changing the "component" tag of created spans. /// public string ComponentName { get => _componentName; set => _componentName = value ?? throw new ArgumentNullException(nameof(ComponentName)); } /// /// A list of delegates that define whether or not a given request should be ignored. /// /// If any delegate in the list returns true, the request will be ignored. /// public List> IgnorePatterns { get { if (_ignorePatterns == null) { _ignorePatterns = new List>(); } return _ignorePatterns; } } /// /// A delegates that defines from which requests tracing headers are extracted. /// public Func ExtractEnabled { get; set; } /// /// A delegate that returns the OpenTracing "operation name" for the given request. /// public Func OperationNameResolver { get { if (_operationNameResolver == null) { _operationNameResolver = (httpContext) => "HTTP " + httpContext.Request.Method; } return _operationNameResolver; } set => _operationNameResolver = value ?? throw new ArgumentNullException(nameof(OperationNameResolver)); } /// /// Allows the modification of the created span to e.g. add further tags. /// public Action OnRequest { get; set; } /// /// Allows the modification of the created span when error occured to e.g. add further tags. /// public Action OnError { get; set; } } } ================================================ FILE: src/OpenTracing.Contrib.NetCore/AspNetCore/RequestHeadersExtractAdapter.cs ================================================ using System; using System.Collections; using System.Collections.Generic; using Microsoft.AspNetCore.Http; using OpenTracing.Propagation; namespace OpenTracing.Contrib.NetCore.AspNetCore { internal sealed class RequestHeadersExtractAdapter : ITextMap { private readonly IHeaderDictionary _headers; public RequestHeadersExtractAdapter(IHeaderDictionary headers) { _headers = headers ?? throw new ArgumentNullException(nameof(headers)); } public void Set(string key, string value) { throw new NotSupportedException("This class should only be used with ITracer.Extract"); } public IEnumerator> GetEnumerator() { foreach (var kvp in _headers) { yield return new KeyValuePair(kvp.Key, kvp.Value); } } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } } } ================================================ FILE: src/OpenTracing.Contrib.NetCore/Configuration/DiagnosticOptions.cs ================================================ using System.Collections.Generic; namespace OpenTracing.Contrib.NetCore.Configuration { public abstract class DiagnosticOptions { /// /// Defines whether or not generic events from this DiagnostSource should be logged as events. /// public bool LogEvents { get; set; } = true; /// /// Defines specific event names that should NOT be logged as events. Set to `false` if you don't want any events to be logged. /// public HashSet IgnoredEvents { get; } = new HashSet(); /// /// Defines whether or not a span should be created if there is no parent span. /// public bool StartRootSpans { get; set; } = true; } } ================================================ FILE: src/OpenTracing.Contrib.NetCore/Configuration/IOpenTracingBuilder.cs ================================================ namespace Microsoft.Extensions.DependencyInjection { /// /// An interface for configuring OpenTracing services. /// public interface IOpenTracingBuilder { /// /// Gets the where OpenTracing services are configured. /// IServiceCollection Services { get; } } } ================================================ FILE: src/OpenTracing.Contrib.NetCore/Configuration/OpenTracingBuilder.cs ================================================ using System; using Microsoft.Extensions.DependencyInjection; namespace OpenTracing.Contrib.NetCore.Configuration { internal class OpenTracingBuilder : IOpenTracingBuilder { public IServiceCollection Services { get; } public OpenTracingBuilder(IServiceCollection services) { Services = services ?? throw new ArgumentNullException(nameof(services)); } } } ================================================ FILE: src/OpenTracing.Contrib.NetCore/Configuration/OpenTracingBuilderExtensions.cs ================================================ using System; using Microsoft.Extensions.DependencyInjection.Extensions; using Microsoft.Extensions.Logging; using OpenTracing.Contrib.NetCore.AspNetCore; using OpenTracing.Contrib.NetCore.Configuration; using OpenTracing.Contrib.NetCore.EntityFrameworkCore; using OpenTracing.Contrib.NetCore.GenericListeners; using OpenTracing.Contrib.NetCore.HttpHandler; using OpenTracing.Contrib.NetCore.Internal; using OpenTracing.Contrib.NetCore.Logging; using OpenTracing.Contrib.NetCore.MicrosoftSqlClient; using OpenTracing.Contrib.NetCore.SystemSqlClient; namespace Microsoft.Extensions.DependencyInjection { public static class OpenTracingBuilderExtensions { internal static IOpenTracingBuilder AddDiagnosticSubscriber(this IOpenTracingBuilder builder) where TDiagnosticSubscriber : DiagnosticObserver { if (builder == null) throw new ArgumentNullException(nameof(builder)); builder.Services.TryAddEnumerable(ServiceDescriptor.Singleton()); return builder; } /// /// Adds instrumentation for ASP.NET Core. /// public static IOpenTracingBuilder AddAspNetCore(this IOpenTracingBuilder builder, Action options = null) { if (builder == null) throw new ArgumentNullException(nameof(builder)); builder.AddDiagnosticSubscriber(); builder.ConfigureGenericDiagnostics(genericOptions => genericOptions.IgnoredListenerNames.Add(AspNetCoreDiagnostics.DiagnosticListenerName)); // Our default behavior for ASP.NET is that we only want spans if the request itself is traced builder.ConfigureEntityFrameworkCore(opt => opt.StartRootSpans = false); builder.ConfigureHttpHandler(opt => opt.StartRootSpans = false); builder.ConfigureMicrosoftSqlClient(opt => opt.StartRootSpans = false); builder.ConfigureSystemSqlClient(opt => opt.StartRootSpans = false); return ConfigureAspNetCore(builder, options); } public static IOpenTracingBuilder ConfigureAspNetCore(this IOpenTracingBuilder builder, Action options) { if (builder == null) throw new ArgumentNullException(nameof(builder)); if (options != null) { builder.Services.Configure(options); } return builder; } /// /// Adds instrumentation for System.Net.Http. /// public static IOpenTracingBuilder AddHttpHandler(this IOpenTracingBuilder builder, Action options = null) { if (builder == null) throw new ArgumentNullException(nameof(builder)); builder.AddDiagnosticSubscriber(); builder.ConfigureGenericDiagnostics(options => options.IgnoredListenerNames.Add(HttpHandlerDiagnostics.DiagnosticListenerName)); return ConfigureHttpHandler(builder, options); } public static IOpenTracingBuilder ConfigureHttpHandler(this IOpenTracingBuilder builder, Action options) { if (builder == null) throw new ArgumentNullException(nameof(builder)); if (options != null) { builder.Services.Configure(options); } return builder; } /// /// Adds instrumentation for Entity Framework Core. /// public static IOpenTracingBuilder AddEntityFrameworkCore(this IOpenTracingBuilder builder, Action options = null) { if (builder == null) throw new ArgumentNullException(nameof(builder)); builder.AddDiagnosticSubscriber(); builder.ConfigureGenericDiagnostics(genericOptions => genericOptions.IgnoredListenerNames.Add(EntityFrameworkCoreDiagnostics.DiagnosticListenerName)); return ConfigureEntityFrameworkCore(builder, options); } /// /// Configuration options for the instrumentation of Entity Framework Core. /// public static IOpenTracingBuilder ConfigureEntityFrameworkCore(this IOpenTracingBuilder builder, Action options) { if (builder == null) throw new ArgumentNullException(nameof(builder)); if (options != null) { builder.Services.Configure(options); } return builder; } /// /// Adds instrumentation for generic DiagnosticListeners. /// public static IOpenTracingBuilder AddGenericDiagnostics(this IOpenTracingBuilder builder, Action options = null) { builder.AddDiagnosticSubscriber(); return ConfigureGenericDiagnostics(builder, options); } public static IOpenTracingBuilder ConfigureGenericDiagnostics(this IOpenTracingBuilder builder, Action options) { if (builder == null) throw new ArgumentNullException(nameof(builder)); if (options != null) { builder.Services.Configure(options); } return builder; } /// /// Disables tracing for all diagnostic listeners that don't have an explicit implementation. /// public static IOpenTracingBuilder RemoveGenericDiagnostics(this IOpenTracingBuilder builder) { if (builder == null) throw new ArgumentNullException(nameof(builder)); builder.Services.RemoveAll(); return builder; } /// /// Adds instrumentation for Microsoft.Data.SqlClient. /// public static IOpenTracingBuilder AddMicrosoftSqlClient(this IOpenTracingBuilder builder, Action options = null) { if (builder == null) throw new ArgumentNullException(nameof(builder)); builder.AddDiagnosticSubscriber(); builder.ConfigureGenericDiagnostics(genericOptions => genericOptions.IgnoredListenerNames.Add(MicrosoftSqlClientDiagnostics.DiagnosticListenerName)); return ConfigureMicrosoftSqlClient(builder, options); } /// /// Configuration options for the instrumentation of Microsoft.Data.SqlClient. /// public static IOpenTracingBuilder ConfigureMicrosoftSqlClient(this IOpenTracingBuilder builder, Action options) { if (builder == null) throw new ArgumentNullException(nameof(builder)); if (options != null) { builder.Services.Configure(options); } return builder; } /// /// Adds instrumentation for System.Data.SqlClient. /// public static IOpenTracingBuilder AddSystemSqlClient(this IOpenTracingBuilder builder, Action options = null) { if (builder == null) throw new ArgumentNullException(nameof(builder)); builder.AddDiagnosticSubscriber(); builder.ConfigureGenericDiagnostics(options => options.IgnoredListenerNames.Add(SqlClientDiagnostics.DiagnosticListenerName)); return ConfigureSystemSqlClient(builder, options); } public static IOpenTracingBuilder ConfigureSystemSqlClient(this IOpenTracingBuilder builder, Action options) { if (builder == null) throw new ArgumentNullException(nameof(builder)); if (options != null) { builder.Services.Configure(options); } return builder; } public static IOpenTracingBuilder AddLoggerProvider(this IOpenTracingBuilder builder) { if (builder == null) throw new ArgumentNullException(nameof(builder)); builder.Services.TryAddEnumerable(ServiceDescriptor.Singleton()); builder.Services.Configure(options => { // All interesting request-specific logs are instrumented via DiagnosticSource. options.AddFilter("Microsoft.AspNetCore.Hosting", LogLevel.None); // The "Information"-level in ASP.NET Core is too verbose. options.AddFilter("Microsoft.AspNetCore", LogLevel.Warning); // EF Core is sending everything to DiagnosticSource AND ILogger so we completely disable the category. options.AddFilter("Microsoft.EntityFrameworkCore", LogLevel.None); }); return builder; } } } ================================================ FILE: src/OpenTracing.Contrib.NetCore/Configuration/ServiceCollectionExtensions.cs ================================================ using System; using Microsoft.Extensions.DependencyInjection.Extensions; using Microsoft.Extensions.Hosting; using OpenTracing; using OpenTracing.Contrib.NetCore; using OpenTracing.Contrib.NetCore.Configuration; using OpenTracing.Contrib.NetCore.Internal; using OpenTracing.Util; namespace Microsoft.Extensions.DependencyInjection { public static class ServiceCollectionExtensions { /// /// Adds OpenTracing instrumentation for ASP.NET Core, CoreFx (BCL), Entity Framework Core. /// public static IServiceCollection AddOpenTracing(this IServiceCollection services, Action builder = null) { if (services == null) throw new ArgumentNullException(nameof(services)); return services.AddOpenTracingCoreServices(otBuilder => { otBuilder.AddLoggerProvider(); otBuilder.AddEntityFrameworkCore(); otBuilder.AddGenericDiagnostics(); otBuilder.AddHttpHandler(); otBuilder.AddMicrosoftSqlClient(); otBuilder.AddSystemSqlClient(); if (AssemblyExists("Microsoft.AspNetCore.Hosting")) { otBuilder.AddAspNetCore(); } builder?.Invoke(otBuilder); }); } /// /// Adds the core services required for OpenTracing without any actual instrumentations. /// public static IServiceCollection AddOpenTracingCoreServices(this IServiceCollection services, Action builder = null) { if (services == null) throw new ArgumentNullException(nameof(services)); services.TryAddSingleton(GlobalTracer.Instance); services.TryAddSingleton(); services.TryAddSingleton(); services.TryAddEnumerable(ServiceDescriptor.Singleton()); var builderInstance = new OpenTracingBuilder(services); builder?.Invoke(builderInstance); return services; } private static bool AssemblyExists(string assemblyName) { var assemblies = AppDomain.CurrentDomain.GetAssemblies(); foreach (var assembly in assemblies) { if (assembly.FullName.StartsWith(assemblyName)) return true; } return false; } } } ================================================ FILE: src/OpenTracing.Contrib.NetCore/EntityFrameworkCore/EntityFrameworkCoreDiagnosticOptions.cs ================================================ using System; using System.Collections.Generic; using Microsoft.EntityFrameworkCore.Diagnostics; namespace OpenTracing.Contrib.NetCore.Configuration { public class EntityFrameworkCoreDiagnosticOptions : DiagnosticOptions { // NOTE: Everything here that references any EFCore types MUST NOT be initialized in the constructor as that would throw on applications that don't reference EFCore. public const string DefaultComponent = "EFCore"; private string _componentName = DefaultComponent; private List> _ignorePatterns; private Func _operationNameResolver; public EntityFrameworkCoreDiagnosticOptions() { IgnoredEvents.Add("Microsoft.EntityFrameworkCore.ChangeTracking.StartedTracking"); IgnoredEvents.Add("Microsoft.EntityFrameworkCore.ChangeTracking.DetectChangesStarting"); IgnoredEvents.Add("Microsoft.EntityFrameworkCore.ChangeTracking.DetectChangesCompleted"); IgnoredEvents.Add("Microsoft.EntityFrameworkCore.ChangeTracking.ForeignKeyChangeDetected"); IgnoredEvents.Add("Microsoft.EntityFrameworkCore.ChangeTracking.StateChanged"); IgnoredEvents.Add("Microsoft.EntityFrameworkCore.ChangeTracking.ValueGenerated"); IgnoredEvents.Add("Microsoft.EntityFrameworkCore.Database.Command.CommandCreating"); IgnoredEvents.Add("Microsoft.EntityFrameworkCore.Database.Command.CommandCreated"); IgnoredEvents.Add("Microsoft.EntityFrameworkCore.Database.Command.DataReaderDisposing"); IgnoredEvents.Add("Microsoft.EntityFrameworkCore.Database.Connection.ConnectionOpening"); IgnoredEvents.Add("Microsoft.EntityFrameworkCore.Database.Connection.ConnectionOpened"); IgnoredEvents.Add("Microsoft.EntityFrameworkCore.Database.Connection.ConnectionClosing"); IgnoredEvents.Add("Microsoft.EntityFrameworkCore.Database.Connection.ConnectionClosed"); IgnoredEvents.Add("Microsoft.EntityFrameworkCore.Database.Transaction.TransactionStarting"); IgnoredEvents.Add("Microsoft.EntityFrameworkCore.Database.Transaction.TransactionStarted"); IgnoredEvents.Add("Microsoft.EntityFrameworkCore.Database.Transaction.TransactionCommitting"); IgnoredEvents.Add("Microsoft.EntityFrameworkCore.Database.Transaction.TransactionCommitted"); IgnoredEvents.Add("Microsoft.EntityFrameworkCore.Database.Transaction.TransactionDisposed"); IgnoredEvents.Add("Microsoft.EntityFrameworkCore.Infrastructure.ContextDisposed"); } /// /// A list of delegates that define whether or not a given EF Core command should be ignored. /// /// If any delegate in the list returns true, the EF Core command will be ignored. /// public List> IgnorePatterns => _ignorePatterns ??= new List>(); /// /// Allows changing the "component" tag of created spans. /// public string ComponentName { get => _componentName; set => _componentName = value ?? throw new ArgumentNullException(nameof(ComponentName)); } /// /// A delegate that returns the OpenTracing "operation name" for the given command. /// public Func OperationNameResolver { get { if (_operationNameResolver == null) { // Default value may not be set in the constructor because this would fail // if the target application does not reference EFCore. _operationNameResolver = (data) => "DB " + data.ExecuteMethod.ToString(); } return _operationNameResolver; } set => _operationNameResolver = value ?? throw new ArgumentNullException(nameof(OperationNameResolver)); } } } ================================================ FILE: src/OpenTracing.Contrib.NetCore/EntityFrameworkCore/EntityFrameworkCoreDiagnostics.cs ================================================ using System; using System.Collections.Concurrent; using System.Collections.Generic; using Microsoft.EntityFrameworkCore.Diagnostics; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; using OpenTracing.Contrib.NetCore.Configuration; using OpenTracing.Contrib.NetCore.Internal; using OpenTracing.Tag; namespace OpenTracing.Contrib.NetCore.EntityFrameworkCore { internal sealed class EntityFrameworkCoreDiagnostics : DiagnosticEventObserver { // https://github.com/aspnet/EntityFrameworkCore/blob/dev/src/EFCore/DbLoggerCategory.cs public const string DiagnosticListenerName = "Microsoft.EntityFrameworkCore"; private const string TagMethod = "db.method"; private const string TagIsAsync = "db.async"; private readonly EntityFrameworkCoreDiagnosticOptions _options; private readonly ConcurrentDictionary _scopeStorage; public EntityFrameworkCoreDiagnostics(ILoggerFactory loggerFactory, ITracer tracer, IOptions options) : base(loggerFactory, tracer, options?.Value) { _options = options?.Value ?? throw new ArgumentNullException(nameof(options)); _scopeStorage = new ConcurrentDictionary(); } protected override string GetListenerName() => DiagnosticListenerName; protected override IEnumerable HandledEventNames() { yield return "Microsoft.EntityFrameworkCore.Database.Command.CommandExecuting"; yield return "Microsoft.EntityFrameworkCore.Database.Command.CommandExecuted"; yield return "Microsoft.EntityFrameworkCore.Database.Command.CommandError"; } protected override void HandleEvent(string eventName, object untypedArg) { switch (eventName) { case "Microsoft.EntityFrameworkCore.Database.Command.CommandExecuting": { CommandEventData args = (CommandEventData)untypedArg; var activeSpan = Tracer.ActiveSpan; if (activeSpan == null && !_options.StartRootSpans) { if (IsLogLevelTraceEnabled) { Logger.LogTrace("Ignoring EF command due to missing parent span"); } return; } if (IgnoreEvent(args)) { if (IsLogLevelTraceEnabled) { Logger.LogTrace("Ignoring EF command due to IgnorePatterns"); } return; } string operationName = _options.OperationNameResolver(args); var scope = Tracer.BuildSpan(operationName) .AsChildOf(activeSpan) .WithTag(Tags.SpanKind, Tags.SpanKindClient) .WithTag(Tags.Component, _options.ComponentName) .WithTag(Tags.DbInstance, args.Command.Connection.Database) .WithTag(Tags.DbStatement, args.Command.CommandText) .WithTag(TagMethod, args.ExecuteMethod.ToString()) .WithTag(TagIsAsync, args.IsAsync) .StartActive(); _scopeStorage.TryAdd(args.CommandId, scope); } break; case "Microsoft.EntityFrameworkCore.Database.Command.CommandExecuted": { CommandExecutedEventData args = (CommandExecutedEventData)untypedArg; if (_scopeStorage.TryRemove(args.CommandId, out var scope)) { scope.Dispose(); } } break; case "Microsoft.EntityFrameworkCore.Database.Command.CommandError": { CommandErrorEventData args = (CommandErrorEventData)untypedArg; // The "CommandExecuted" event is NOT called in case of an exception, // so we have to dispose the scope here as well! if (_scopeStorage.TryRemove(args.CommandId, out var scope)) { scope.Span.SetException(args.Exception); scope.Dispose(); } } break; default: { Dictionary tags = null; if (untypedArg is EventData eventArgs) { tags = new Dictionary { { "level", eventArgs.LogLevel.ToString() }, }; } HandleUnknownEvent(eventName, untypedArg, tags); break; } } } private bool IgnoreEvent(CommandEventData eventData) { foreach (Func ignore in _options.IgnorePatterns) { if (ignore(eventData)) return true; } return false; } } } ================================================ FILE: src/OpenTracing.Contrib.NetCore/GenericListeners/GenericDiagnosticOptions.cs ================================================ using System.Collections.Generic; namespace OpenTracing.Contrib.NetCore.Configuration { public sealed class GenericDiagnosticOptions { public HashSet IgnoredListenerNames { get; } = new HashSet(); public Dictionary> IgnoredEvents { get; } = new Dictionary>(); public void IgnoreEvent(string diagnosticListenerName, string eventName) { if (diagnosticListenerName == null || eventName == null) return; HashSet ignoredListenerEvents; if (!IgnoredEvents.TryGetValue(diagnosticListenerName, out ignoredListenerEvents)) { ignoredListenerEvents = new HashSet(); IgnoredEvents.Add(diagnosticListenerName, ignoredListenerEvents); } ignoredListenerEvents.Add(eventName); } } } ================================================ FILE: src/OpenTracing.Contrib.NetCore/GenericListeners/GenericDiagnostics.cs ================================================ using System; using System.Collections.Generic; using System.Diagnostics; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; using OpenTracing.Contrib.NetCore.Configuration; using OpenTracing.Contrib.NetCore.Internal; namespace OpenTracing.Contrib.NetCore.GenericListeners { /// /// A subscriber that logs ALL events to . /// internal sealed class GenericDiagnostics : DiagnosticObserver { private readonly GenericDiagnosticOptions _options; public GenericDiagnostics(ILoggerFactory loggerFactory, ITracer tracer, IOptions options) : base(loggerFactory, tracer) { _options = options?.Value ?? throw new ArgumentNullException(nameof(options)); } public override IDisposable SubscribeIfMatch(DiagnosticListener diagnosticListener) { if (_options.IgnoredListenerNames.Contains(diagnosticListener.Name)) { return null; } _options.IgnoredEvents.TryGetValue(diagnosticListener.Name, out var ignoredListenerEvents); return new GenericDiagnosticsSubscription(this, diagnosticListener, ignoredListenerEvents); } private class GenericDiagnosticsSubscription : IObserver>, IDisposable { private readonly GenericDiagnostics _subscriber; private readonly string _listenerName; private readonly HashSet _ignoredEvents; private readonly GenericEventProcessor _genericEventProcessor; private readonly IDisposable _subscription; public GenericDiagnosticsSubscription(GenericDiagnostics subscriber, DiagnosticListener diagnosticListener, HashSet ignoredEvents) { _subscriber = subscriber; _ignoredEvents = ignoredEvents; _listenerName = diagnosticListener.Name; _genericEventProcessor = new GenericEventProcessor(_listenerName, _subscriber.Tracer, subscriber.Logger); _subscription = diagnosticListener.Subscribe(this, IsEnabled); } public void Dispose() { _subscription.Dispose(); } private bool IsEnabled(string eventName) { if (_ignoredEvents != null && _ignoredEvents.Contains(eventName)) { if (_subscriber.IsLogLevelTraceEnabled) { _subscriber.Logger.LogTrace("Ignoring event '{ListenerName}/{Event}'", _listenerName, eventName); } return false; } return true; } public void OnCompleted() { } public void OnError(Exception error) { } public void OnNext(KeyValuePair value) { string eventName = value.Key; object untypedArg = value.Value; try { // We have to check this twice because EVERY subscriber is called // if ANY subscriber returns IsEnabled=true. if (!IsEnabled(eventName)) return; _genericEventProcessor?.ProcessEvent(eventName, untypedArg); } catch (Exception ex) { _subscriber.Logger.LogWarning(ex, "Event-Exception: {ListenerName}/{Event}", _listenerName, value.Key); } } } } } ================================================ FILE: src/OpenTracing.Contrib.NetCore/HttpHandler/HttpHandlerDiagnosticOptions.cs ================================================ using System; using System.Collections.Generic; using System.Net.Http; namespace OpenTracing.Contrib.NetCore.Configuration { public class HttpHandlerDiagnosticOptions : DiagnosticOptions { public const string PropertyIgnore = "ot-ignore"; public const string DefaultComponent = "HttpOut"; private string _componentName; private Func _operationNameResolver; /// /// Allows changing the "component" tag of created spans. /// public string ComponentName { get => _componentName; set => _componentName = value ?? throw new ArgumentNullException(nameof(ComponentName)); } /// /// A list of delegates that define whether or not a given request should be ignored. /// /// If any delegate in the list returns true, the request will be ignored. /// public List> IgnorePatterns { get; } = new List>(); /// /// A delegates that defines on what requests tracing headers are propagated. /// public Func InjectEnabled { get; set; } /// /// A delegate that returns the OpenTracing "operation name" for the given request. /// public Func OperationNameResolver { get => _operationNameResolver; set => _operationNameResolver = value ?? throw new ArgumentNullException(nameof(OperationNameResolver)); } /// /// Allows the modification of the created span to e.g. add further tags. /// public Action OnRequest { get; set; } /// /// Allows the modification of the created span when error occured to e.g. add further tags. /// public Action OnError { get; set; } public HttpHandlerDiagnosticOptions() { // Default settings ComponentName = DefaultComponent; IgnorePatterns.Add((request) => { IDictionary requestOptions; #if NETCOREAPP3_1 requestOptions = request.Properties; #else requestOptions = request.Options; #endif return requestOptions.ContainsKey(PropertyIgnore); }); OperationNameResolver = (request) => { return "HTTP " + request.Method.Method; }; } } } ================================================ FILE: src/OpenTracing.Contrib.NetCore/HttpHandler/HttpHandlerDiagnostics.cs ================================================ using System; using System.Collections.Generic; using System.Net.Http; using System.Threading.Tasks; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; using OpenTracing.Contrib.NetCore.Configuration; using OpenTracing.Contrib.NetCore.Internal; using OpenTracing.Propagation; using OpenTracing.Tag; namespace OpenTracing.Contrib.NetCore.HttpHandler { /// /// Instruments outgoing HTTP calls that use . /// See https://github.com/dotnet/corefx/blob/master/src/System.Net.Http/src/System/Net/Http/DiagnosticsHandler.cs /// and https://github.com/dotnet/corefx/blob/master/src/System.Net.Http/src/System/Net/Http/DiagnosticsHandlerLoggingStrings.cs /// internal sealed class HttpHandlerDiagnostics : DiagnosticEventObserver { public const string DiagnosticListenerName = "HttpHandlerDiagnosticListener"; private const string PropertiesKey = "ot-Span"; private static readonly PropertyFetcher _activityStart_RequestFetcher = new PropertyFetcher("Request"); private static readonly PropertyFetcher _activityStop_RequestFetcher = new PropertyFetcher("Request"); private static readonly PropertyFetcher _activityStop_ResponseFetcher = new PropertyFetcher("Response"); private static readonly PropertyFetcher _activityStop_RequestTaskStatusFetcher = new PropertyFetcher("RequestTaskStatus"); private static readonly PropertyFetcher _exception_RequestFetcher = new PropertyFetcher("Request"); private static readonly PropertyFetcher _exception_ExceptionFetcher = new PropertyFetcher("Exception"); private readonly HttpHandlerDiagnosticOptions _options; public HttpHandlerDiagnostics(ILoggerFactory loggerFactory, ITracer tracer, IOptions options) : base(loggerFactory, tracer, options?.Value) { _options = options?.Value ?? throw new ArgumentNullException(nameof(options)); } protected override string GetListenerName() => DiagnosticListenerName; protected override bool IsSupportedEvent(string eventName) { return eventName switch { // We don't want to get the old deprecated events. // https://github.com/dotnet/runtime/blob/master/src/libraries/System.Net.Http/src/System/Net/Http/DiagnosticsHandlerLoggingStrings.cs "System.Net.Http.Request" => false, "System.Net.Http.Response" => false, _ => true, }; } protected override IEnumerable HandledEventNames() { yield return "System.Net.Http.HttpRequestOut.Start"; yield return "System.Net.Http.Exception"; yield return "System.Net.Http.HttpRequestOut.Stop"; } protected override void HandleEvent(string eventName, object untypedArg) { switch (eventName) { case "System.Net.Http.HttpRequestOut.Start": { var request = (HttpRequestMessage)_activityStart_RequestFetcher.Fetch(untypedArg); var activeSpan = Tracer.ActiveSpan; if (activeSpan == null && !_options.StartRootSpans) { if (IsLogLevelTraceEnabled) { Logger.LogTrace("Ignoring Request due to missing parent span"); } return; } if (IgnoreRequest(request)) { if (IsLogLevelTraceEnabled) { Logger.LogTrace("Ignoring Request {RequestUri}", request.RequestUri); } return; } string operationName = _options.OperationNameResolver(request); ISpan span = Tracer.BuildSpan(operationName) .AsChildOf(activeSpan) .WithTag(Tags.SpanKind, Tags.SpanKindClient) .WithTag(Tags.Component, _options.ComponentName) .WithTag(Tags.HttpMethod, request.Method.ToString()) .WithTag(Tags.HttpUrl, request.RequestUri.ToString()) .WithTag(Tags.PeerHostname, request.RequestUri.Host) .WithTag(Tags.PeerPort, request.RequestUri.Port) .Start(); _options.OnRequest?.Invoke(span, request); if (_options.InjectEnabled?.Invoke(request) ?? true) { Tracer.Inject(span.Context, BuiltinFormats.HttpHeaders, new HttpHeadersInjectAdapter(request.Headers)); } var requestOptions = GetRequestOptions(request); requestOptions[PropertiesKey] = span; } break; case "System.Net.Http.Exception": { var request = (HttpRequestMessage)_exception_RequestFetcher.Fetch(untypedArg); var requestOptions = GetRequestOptions(request); if (requestOptions.TryGetValue(PropertiesKey, out object objSpan) && objSpan is ISpan span) { var exception = (Exception)_exception_ExceptionFetcher.Fetch(untypedArg); span.SetException(exception); _options.OnError?.Invoke(span, exception, request); } } break; case "System.Net.Http.HttpRequestOut.Stop": { var request = (HttpRequestMessage)_activityStop_RequestFetcher.Fetch(untypedArg); var requestOptions = GetRequestOptions(request); if (requestOptions.TryGetValue(PropertiesKey, out object objSpan) && objSpan is ISpan span) { requestOptions.Remove(PropertiesKey); var response = (HttpResponseMessage)_activityStop_ResponseFetcher.Fetch(untypedArg); var requestTaskStatus = (TaskStatus)_activityStop_RequestTaskStatusFetcher.Fetch(untypedArg); if (response != null) { span.SetTag(Tags.HttpStatus, (int)response.StatusCode); } if (requestTaskStatus == TaskStatus.Canceled || requestTaskStatus == TaskStatus.Faulted) { span.SetTag(Tags.Error, true); } span.Finish(); } } break; default: HandleUnknownEvent(eventName, untypedArg); break; } } private bool IgnoreRequest(HttpRequestMessage request) { foreach (Func ignore in _options.IgnorePatterns) { if (ignore(request)) return true; } return false; } private IDictionary GetRequestOptions(HttpRequestMessage request) { IDictionary requestOptions; #if NETCOREAPP3_1 requestOptions = request.Properties; #else requestOptions = request.Options; #endif return requestOptions; } } } ================================================ FILE: src/OpenTracing.Contrib.NetCore/HttpHandler/HttpHeadersInjectAdapter.cs ================================================ using System; using System.Collections; using System.Collections.Generic; using System.Net.Http.Headers; using OpenTracing.Propagation; namespace OpenTracing.Contrib.NetCore.HttpHandler { internal sealed class HttpHeadersInjectAdapter : ITextMap { private readonly HttpHeaders _headers; public HttpHeadersInjectAdapter(HttpHeaders headers) { _headers = headers ?? throw new ArgumentNullException(nameof(headers)); } public void Set(string key, string value) { if (_headers.Contains(key)) { _headers.Remove(key); } _headers.Add(key, value); } public IEnumerator> GetEnumerator() { throw new NotSupportedException("This class should only be used with ITracer.Inject"); } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } } } ================================================ FILE: src/OpenTracing.Contrib.NetCore/InstrumentationService.cs ================================================ using System; using System.Threading; using System.Threading.Tasks; using Microsoft.Extensions.Hosting; using OpenTracing.Contrib.NetCore.Internal; namespace OpenTracing.Contrib.NetCore { /// /// Starts and stops all OpenTracing instrumentation components. /// internal class InstrumentationService : IHostedService { private readonly DiagnosticManager _diagnosticsManager; public InstrumentationService(DiagnosticManager diagnosticManager) { _diagnosticsManager = diagnosticManager ?? throw new ArgumentNullException(nameof(diagnosticManager)); } public Task StartAsync(CancellationToken cancellationToken) { _diagnosticsManager.Start(); return Task.CompletedTask; } public Task StopAsync(CancellationToken cancellationToken) { _diagnosticsManager.Stop(); return Task.CompletedTask; } } } ================================================ FILE: src/OpenTracing.Contrib.NetCore/Internal/DiagnosticEventObserver.cs ================================================ using System; using System.Collections.Generic; using System.Diagnostics; using Microsoft.Extensions.Logging; using OpenTracing.Contrib.NetCore.Configuration; namespace OpenTracing.Contrib.NetCore.Internal { /// /// Base class that allows handling events from a single . /// internal abstract class DiagnosticEventObserver : DiagnosticObserver, IObserver> { private readonly DiagnosticOptions _options; private readonly GenericEventProcessor _genericEventProcessor; protected DiagnosticEventObserver(ILoggerFactory loggerFactory, ITracer tracer, DiagnosticOptions options) : base(loggerFactory, tracer) { _options = options; if (options.LogEvents) { _genericEventProcessor = new GenericEventProcessor(GetListenerName(), Tracer, Logger); } } public override IDisposable SubscribeIfMatch(DiagnosticListener diagnosticListener) { if (diagnosticListener.Name == GetListenerName()) { return diagnosticListener.Subscribe(this, IsEnabled); } return null; } void IObserver>.OnCompleted() { } void IObserver>.OnError(Exception error) { } void IObserver>.OnNext(KeyValuePair value) { try { if (IsEnabled(value.Key)) { HandleEvent(value.Key, value.Value); } } catch (Exception ex) { Logger.LogWarning(ex, "Event-Exception: {Event}", value.Key); } } /// /// The name of the that should be instrumented. /// protected abstract string GetListenerName(); protected virtual bool IsSupportedEvent(string eventName) => true; protected abstract IEnumerable HandledEventNames(); private bool IsEnabled(string eventName) { if (!IsSupportedEvent(eventName)) return false; foreach (var handledEventName in HandledEventNames()) { if (handledEventName == eventName) return true; } if (!_options.LogEvents || _options.IgnoredEvents.Contains(eventName)) return false; return true; } protected abstract void HandleEvent(string eventName, object untypedArg); protected void HandleUnknownEvent(string eventName, object untypedArg, IEnumerable> tags = null) { _genericEventProcessor?.ProcessEvent(eventName, untypedArg, tags); } protected void DisposeActiveScope(bool isScopeRequired, Exception exception = null) { IScope scope = Tracer.ScopeManager.Active; if (scope != null) { if (exception != null) { scope.Span.SetException(exception); } scope.Dispose(); } else if (isScopeRequired) { Logger.LogWarning("Scope not found"); } } } } ================================================ FILE: src/OpenTracing.Contrib.NetCore/Internal/DiagnosticManager.cs ================================================ using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; namespace OpenTracing.Contrib.NetCore.Internal { /// /// Subscribes to and forwards events to individual instances. /// internal sealed class DiagnosticManager : IObserver, IDisposable { private readonly ILogger _logger; private readonly ITracer _tracer; private readonly IEnumerable _diagnosticSubscribers; private readonly DiagnosticManagerOptions _options; private readonly List _subscriptions = new List(); private IDisposable _allListenersSubscription; public bool IsRunning => _allListenersSubscription != null; public DiagnosticManager( ILoggerFactory loggerFactory, ITracer tracer, IEnumerable diagnosticSubscribers, IOptions options) { if (loggerFactory == null) throw new ArgumentNullException(nameof(loggerFactory)); if (diagnosticSubscribers == null) throw new ArgumentNullException(nameof(diagnosticSubscribers)); _tracer = tracer ?? throw new ArgumentNullException(nameof(tracer)); _options = options?.Value ?? throw new ArgumentNullException(nameof(options)); _logger = loggerFactory.CreateLogger(); _diagnosticSubscribers = diagnosticSubscribers; } public void Start() { if (_allListenersSubscription == null) { if (_tracer.IsNoopTracer() && !_options.StartInstrumentationForNoopTracer) { _logger.LogWarning("Instrumentation has not been started because no tracer was registered."); } else { _logger.LogTrace("Starting AllListeners subscription"); _allListenersSubscription = DiagnosticListener.AllListeners.Subscribe(this); } } } void IObserver.OnCompleted() { } void IObserver.OnError(Exception error) { } void IObserver.OnNext(DiagnosticListener listener) { foreach (var subscriber in _diagnosticSubscribers) { IDisposable subscription = subscriber.SubscribeIfMatch(listener); if (subscription != null) { _logger.LogTrace($"Subscriber '{subscriber.GetType().Name}' returned subscription for '{listener.Name}'"); _subscriptions.Add(subscription); } } } public void Stop() { if (_allListenersSubscription != null) { _logger.LogTrace("Stopping AllListeners subscription"); _allListenersSubscription.Dispose(); _allListenersSubscription = null; foreach (var subscription in _subscriptions) { subscription.Dispose(); } _subscriptions.Clear(); } } public void Dispose() { Stop(); } } } ================================================ FILE: src/OpenTracing.Contrib.NetCore/Internal/DiagnosticManagerOptions.cs ================================================ namespace OpenTracing.Contrib.NetCore.Internal { public class DiagnosticManagerOptions { public bool StartInstrumentationForNoopTracer { get; set; } } } ================================================ FILE: src/OpenTracing.Contrib.NetCore/Internal/DiagnosticObserver.cs ================================================ using System; using System.Diagnostics; using Microsoft.Extensions.Logging; namespace OpenTracing.Contrib.NetCore.Internal { internal abstract class DiagnosticObserver { protected ILogger Logger { get; } protected ITracer Tracer { get; } protected bool IsLogLevelTraceEnabled { get; } protected DiagnosticObserver(ILoggerFactory loggerFactory, ITracer tracer) { if (loggerFactory == null) throw new ArgumentNullException(nameof(loggerFactory)); if (tracer == null) throw new ArgumentNullException(nameof(tracer)); Logger = loggerFactory.CreateLogger(GetType()); Tracer = tracer; IsLogLevelTraceEnabled = Logger.IsEnabled(LogLevel.Trace); } public abstract IDisposable SubscribeIfMatch(DiagnosticListener diagnosticListener); } } ================================================ FILE: src/OpenTracing.Contrib.NetCore/Internal/GenericEventProcessor.cs ================================================ using System; using System.Collections.Generic; using System.Diagnostics; using Microsoft.Extensions.Logging; using OpenTracing.Tag; namespace OpenTracing.Contrib.NetCore.Internal { internal class GenericEventProcessor { private readonly string _listenerName; private readonly ITracer _tracer; private readonly ILogger _logger; private readonly bool _isLogLevelTraceEnabled; public GenericEventProcessor(string listenerName, ITracer tracer, ILogger logger) { _listenerName = listenerName ?? throw new ArgumentNullException(nameof(listenerName)); _tracer = tracer ?? throw new ArgumentNullException(nameof(tracer)); _logger = logger ?? throw new ArgumentNullException(nameof(logger)); _isLogLevelTraceEnabled = _logger.IsEnabled(LogLevel.Trace); } public void ProcessEvent(string eventName, object untypedArg, IEnumerable> tags = null) { Activity activity = Activity.Current; if (activity != null && eventName.EndsWith(".Start", StringComparison.Ordinal)) { HandleActivityStart(eventName, activity, untypedArg, tags); } else if (activity != null && eventName.EndsWith(".Stop", StringComparison.Ordinal)) { HandleActivityStop(eventName, activity); } else { HandleRegularEvent(eventName, untypedArg, tags); } } private void HandleActivityStart(string eventName, Activity activity, object untypedArg, IEnumerable> tags) { ISpanBuilder spanBuilder = _tracer.BuildSpan(activity.OperationName) .WithTag(Tags.Component, _listenerName); foreach (var tag in activity.Tags) { spanBuilder.WithTag(tag.Key, tag.Value); } if (tags != null) { foreach (var tag in tags) { spanBuilder.WithTag(tag.Key, tag.Value); } } spanBuilder.StartActive(); } private void HandleActivityStop(string eventName, Activity activity) { IScope scope = _tracer.ScopeManager.Active; if (scope != null) { scope.Dispose(); } else { _logger.LogWarning("No scope found. Event: {ListenerName}/{Event}", _listenerName, eventName); } } private void HandleRegularEvent(string eventName, object untypedArg, IEnumerable> tags) { var span = _tracer.ActiveSpan; if (span != null) { span.Log(GetLogFields(eventName, untypedArg, tags)); } else if (_isLogLevelTraceEnabled) { _logger.LogTrace("No ActiveSpan. Event: {ListenerName}/{Event}", _listenerName, eventName); } } private Dictionary GetLogFields(string eventName, object arg, IEnumerable> tags) { var fields = new Dictionary { { LogFields.Event, eventName }, { Tags.Component.Key, _listenerName } }; if (tags != null) { foreach (var tag in tags) { fields[tag.Key] = tag.Value; } } // TODO improve the hell out of this... :) if (arg != null) { Type argType = arg.GetType(); if (argType.IsPrimitive) { fields.Add("arg", arg); } else if (argType.Namespace == null) { // Anonymous types usually contain complex objects so their output is not really useful. // Ignoring them for now. } else { fields.Add("arg", arg.ToString()); if (_isLogLevelTraceEnabled) { _logger.LogTrace("Can not extract value for argument type '{Type}'. Using ToString()", argType); } } } return fields; } } } ================================================ FILE: src/OpenTracing.Contrib.NetCore/Internal/GlobalTracerAccessor.cs ================================================ using OpenTracing.Util; namespace OpenTracing.Contrib.NetCore.Internal { public class GlobalTracerAccessor : IGlobalTracerAccessor { public ITracer GetGlobalTracer() { return GlobalTracer.Instance; } } } ================================================ FILE: src/OpenTracing.Contrib.NetCore/Internal/IGlobalTracerAccessor.cs ================================================ namespace OpenTracing.Contrib.NetCore.Internal { /// /// Helper interface which allows unit tests to mock the . /// public interface IGlobalTracerAccessor { ITracer GetGlobalTracer(); } } ================================================ FILE: src/OpenTracing.Contrib.NetCore/Internal/PropertyFetcher.cs ================================================ // From https://github.com/dotnet/corefx/blob/master/src/System.Diagnostics.DiagnosticSource/src/System/Diagnostics/DiagnosticSourceEventSource.cs using System; using System.Linq; using System.Reflection; namespace OpenTracing.Contrib.NetCore.Internal { internal class PropertyFetcher { private readonly string _propertyName; private Type _expectedType; private PropertyFetch _fetchForExpectedType; /// /// Make a new PropertyFetcher for a property named 'propertyName'. /// public PropertyFetcher(string propertyName) { _propertyName = propertyName; } /// /// Given an object fetch the property that this PropertySpec represents. /// public object Fetch(object obj) { Type objType = obj.GetType(); if (objType != _expectedType) { TypeInfo typeInfo = objType.GetTypeInfo(); var propertyInfo = typeInfo.DeclaredProperties.FirstOrDefault(p => string.Equals(p.Name, _propertyName, StringComparison.InvariantCultureIgnoreCase)); _fetchForExpectedType = PropertyFetch.FetcherForProperty(propertyInfo); _expectedType = objType; } return _fetchForExpectedType.Fetch(obj); } /// /// PropertyFetch is a helper class. It takes a PropertyInfo and then knows how /// to efficiently fetch that property from a .NET object (See Fetch method). /// It hides some slightly complex generic code. /// private class PropertyFetch { /// /// Create a property fetcher from a .NET Reflection PropertyInfo class that /// represents a property of a particular type. /// public static PropertyFetch FetcherForProperty(PropertyInfo propertyInfo) { if (propertyInfo == null) return new PropertyFetch(); // returns null on any fetch. Type typedPropertyFetcher = typeof(TypedFetchProperty<,>); Type instantiatedTypedPropertyFetcher = typedPropertyFetcher.GetTypeInfo().MakeGenericType( propertyInfo.DeclaringType, propertyInfo.PropertyType); return (PropertyFetch)Activator.CreateInstance(instantiatedTypedPropertyFetcher, propertyInfo); } /// /// Given an object, fetch the property that this propertyFech represents. /// public virtual object Fetch(object obj) { return null; } private class TypedFetchProperty : PropertyFetch { public TypedFetchProperty(PropertyInfo property) { _propertyFetch = (Func)property.GetMethod.CreateDelegate(typeof(Func)); } public override object Fetch(object obj) { return _propertyFetch((TObject)obj); } private readonly Func _propertyFetch; } } } } ================================================ FILE: src/OpenTracing.Contrib.NetCore/Internal/SpanExtensions.cs ================================================ using System; using System.Collections.Generic; using OpenTracing.Tag; namespace OpenTracing.Contrib.NetCore.Internal { internal static class SpanExtensions { /// /// Sets the tag and adds information about the /// to the given . /// public static void SetException(this ISpan span, Exception exception) { if (span == null || exception == null) return; span.SetTag(Tags.Error, true); span.Log(new Dictionary(3) { { LogFields.Event, Tags.Error.Key }, { LogFields.ErrorKind, exception.GetType().Name }, { LogFields.ErrorObject, exception } }); } } } ================================================ FILE: src/OpenTracing.Contrib.NetCore/Internal/TracerExtensions.cs ================================================ using OpenTracing.Noop; using OpenTracing.Util; namespace OpenTracing.Contrib.NetCore.Internal { internal static class TracerExtensions { public static bool IsNoopTracer(this ITracer tracer) { if (tracer is NoopTracer) return true; // There's no way to check the underlying tracer on the instance so we have to check the static method. if (tracer is GlobalTracer && !GlobalTracer.IsRegistered()) return true; return false; } } } ================================================ FILE: src/OpenTracing.Contrib.NetCore/Logging/OpenTracingLogger.cs ================================================ using System; using System.Collections.Generic; using Microsoft.Extensions.Logging; using OpenTracing.Contrib.NetCore.Internal; using OpenTracing.Noop; using OpenTracing.Util; namespace OpenTracing.Contrib.NetCore.Logging { internal class OpenTracingLogger : ILogger { private const string OriginalFormatPropertyName = "{OriginalFormat}"; private readonly string _categoryName; private readonly IGlobalTracerAccessor _globalTracerAccessor; public OpenTracingLogger(IGlobalTracerAccessor globalTracerAccessor, string categoryName) { _globalTracerAccessor = globalTracerAccessor; _categoryName = categoryName; } public IDisposable BeginScope(TState state) { return NoopDisposable.Instance; } public bool IsEnabled(LogLevel logLevel) { // Filtering should be done via the general Logging filtering feature. ITracer tracer = _globalTracerAccessor.GetGlobalTracer(); return !( (tracer is NoopTracer) || (tracer is GlobalTracer && !GlobalTracer.IsRegistered())); } public void Log(LogLevel logLevel, EventId eventId, TState state, Exception exception, Func formatter) { if (formatter == null) { // This throws an Exception e.g. in Microsoft's DebugLogger but we don't want the app to crash if the logger has an issue. return; } ITracer tracer = _globalTracerAccessor.GetGlobalTracer(); ISpan span = tracer.ActiveSpan; if (span == null) { // Creating a new span for a log message seems brutal so we ignore messages if we can't attach it to an active span. return; } if (!IsEnabled(logLevel)) { return; } var fields = new Dictionary { { "component", _categoryName }, { "level", logLevel.ToString() } }; try { if (eventId.Id != 0) { fields["eventId"] = eventId.Id; } try { // This throws if the argument count (message format vs. actual args) doesn't match. // e.g. LogInformation("Foo {Arg1} {Arg2}", arg1); // We want to preserve as much as possible from the original log message so we just continue without this information. string message = formatter(state, exception); fields[LogFields.Message] = message; } catch (Exception) { /* no-op */ } if (exception != null) { fields[LogFields.ErrorKind] = exception.GetType().FullName; fields[LogFields.ErrorObject] = exception; } bool eventAdded = false; var structure = state as IEnumerable>; if (structure != null) { try { // The enumerator throws if the argument count (message format vs. actual args) doesn't match. // We want to preserve as much as possible from the original log message so we just ignore // this error and take as many properties as possible. foreach (var property in structure) { if (string.Equals(property.Key, OriginalFormatPropertyName, StringComparison.Ordinal) && property.Value is string messageTemplateString) { fields[LogFields.Event] = messageTemplateString; eventAdded = true; } else { fields[property.Key] = property.Value; } } } catch (IndexOutOfRangeException) { /* no-op */ } } if (!eventAdded) { fields[LogFields.Event] = "log"; } } catch (Exception logException) { fields["opentracing.contrib.netcore.error"] = logException.ToString(); } span.Log(fields); } private class NoopDisposable : IDisposable { public static NoopDisposable Instance = new NoopDisposable(); public void Dispose() { } } } } ================================================ FILE: src/OpenTracing.Contrib.NetCore/Logging/OpenTracingLoggerProvider.cs ================================================ using System; using Microsoft.Extensions.Logging; using OpenTracing.Contrib.NetCore.Internal; namespace OpenTracing.Contrib.NetCore.Logging { /// /// The provider for the . /// [ProviderAlias("OpenTracing")] internal class OpenTracingLoggerProvider : ILoggerProvider { private readonly IGlobalTracerAccessor _globalTracerAccessor; public OpenTracingLoggerProvider(IGlobalTracerAccessor globalTracerAccessor) { _globalTracerAccessor = globalTracerAccessor ?? throw new ArgumentNullException(nameof(globalTracerAccessor)); } /// public ILogger CreateLogger(string categoryName) { return new OpenTracingLogger(_globalTracerAccessor, categoryName); } public void Dispose() { } } } ================================================ FILE: src/OpenTracing.Contrib.NetCore/MicrosoftSqlClient/MicrosoftSqlClientDiagnosticOptions.cs ================================================ using System; using System.Collections.Generic; using System.Linq; using Microsoft.Data.SqlClient; namespace OpenTracing.Contrib.NetCore.Configuration { public class MicrosoftSqlClientDiagnosticOptions : DiagnosticOptions { public static class EventNames { // https://github.com/dotnet/SqlClient/blob/master/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/SqlClientDiagnosticListenerExtensions.cs private const string SqlClientPrefix = "Microsoft.Data.SqlClient."; public const string WriteCommandBefore = SqlClientPrefix + nameof(WriteCommandBefore); public const string WriteCommandAfter = SqlClientPrefix + nameof(WriteCommandAfter); public const string WriteCommandError = SqlClientPrefix + nameof(WriteCommandError); public const string WriteConnectionOpenBefore = SqlClientPrefix + nameof(WriteConnectionOpenBefore); public const string WriteConnectionOpenAfter = SqlClientPrefix + nameof(WriteConnectionOpenAfter); public const string WriteConnectionOpenError = SqlClientPrefix + nameof(WriteConnectionOpenError); public const string WriteConnectionCloseBefore = SqlClientPrefix + nameof(WriteConnectionCloseBefore); public const string WriteConnectionCloseAfter = SqlClientPrefix + nameof(WriteConnectionCloseAfter); public const string WriteConnectionCloseError = SqlClientPrefix + nameof(WriteConnectionCloseError); public const string WriteTransactionCommitBefore = SqlClientPrefix + nameof(WriteTransactionCommitBefore); public const string WriteTransactionCommitAfter = SqlClientPrefix + nameof(WriteTransactionCommitAfter); public const string WriteTransactionCommitError = SqlClientPrefix + nameof(WriteTransactionCommitError); public const string WriteTransactionRollbackBefore = SqlClientPrefix + nameof(WriteTransactionRollbackBefore); public const string WriteTransactionRollbackAfter = SqlClientPrefix + nameof(WriteTransactionRollbackAfter); public const string WriteTransactionRollbackError = SqlClientPrefix + nameof(WriteTransactionRollbackError); } public const string DefaultComponent = "SqlClient"; public const string SqlClientPrefix = "sqlClient "; private string _componentName = DefaultComponent; private List> _ignorePatterns; private Func _operationNameResolver; /// /// A list of delegates that define whether or not a given SQL command should be ignored. /// /// If any delegate in the list returns true, the SQL command will be ignored. /// public List> IgnorePatterns => _ignorePatterns ??= new List>(); /// /// Allows changing the "component" tag of created spans. /// public string ComponentName { get => _componentName; set => _componentName = value ?? throw new ArgumentNullException(nameof(ComponentName)); } /// /// A delegate that returns the OpenTracing "operation name" for the given command. /// public Func OperationNameResolver { get { if (_operationNameResolver == null) { // Default value may not be set in the constructor because this would fail // if the target application does not reference SqlClient. _operationNameResolver = (cmd) => { var commandType = cmd.CommandText?.Split(' '); return $"{SqlClientPrefix}{commandType?.FirstOrDefault()}"; }; } return _operationNameResolver; } set => _operationNameResolver = value ?? throw new ArgumentNullException(nameof(OperationNameResolver)); } } } ================================================ FILE: src/OpenTracing.Contrib.NetCore/MicrosoftSqlClient/MicrosoftSqlClientDiagnostics.cs ================================================ using System; using System.Collections.Concurrent; using System.Collections.Generic; using Microsoft.Data.SqlClient; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; using OpenTracing.Contrib.NetCore.Configuration; using OpenTracing.Contrib.NetCore.Internal; using OpenTracing.Tag; namespace OpenTracing.Contrib.NetCore.MicrosoftSqlClient { internal sealed class MicrosoftSqlClientDiagnostics : DiagnosticEventObserver { public const string DiagnosticListenerName = "SqlClientDiagnosticListener"; private static readonly PropertyFetcher _activityCommand_RequestFetcher = new PropertyFetcher("Command"); private static readonly PropertyFetcher _exception_ExceptionFetcher = new PropertyFetcher("Exception"); private readonly MicrosoftSqlClientDiagnosticOptions _options; private readonly ConcurrentDictionary _spanStorage; public MicrosoftSqlClientDiagnostics(ILoggerFactory loggerFactory, ITracer tracer, IOptions options) : base(loggerFactory, tracer, options?.Value) { _options = options?.Value ?? throw new ArgumentNullException(nameof(options)); _spanStorage = new ConcurrentDictionary(); } protected override string GetListenerName() => DiagnosticListenerName; /// /// Both diagnostic listeners for System.Data.SqlClient and Microsoft.Data.SqlClient use the same listener name, /// so we need to make sure this observer gets the correct events. /// protected override bool IsSupportedEvent(string eventName) => eventName.StartsWith("Microsoft."); protected override IEnumerable HandledEventNames() { yield return MicrosoftSqlClientDiagnosticOptions.EventNames.WriteCommandBefore; yield return MicrosoftSqlClientDiagnosticOptions.EventNames.WriteCommandError; yield return MicrosoftSqlClientDiagnosticOptions.EventNames.WriteCommandAfter; } protected override void HandleEvent(string eventName, object untypedArg) { switch (eventName) { case MicrosoftSqlClientDiagnosticOptions.EventNames.WriteCommandBefore: { var cmd = (SqlCommand)_activityCommand_RequestFetcher.Fetch(untypedArg); var activeSpan = Tracer.ActiveSpan; if (activeSpan == null && !_options.StartRootSpans) { if (IsLogLevelTraceEnabled) { Logger.LogTrace("Ignoring SQL command due to missing parent span"); } return; } if (IgnoreEvent(cmd)) { if (IsLogLevelTraceEnabled) { Logger.LogTrace("Ignoring SQL command due to IgnorePatterns"); } return; } string operationName = _options.OperationNameResolver(cmd); var span = Tracer.BuildSpan(operationName) .AsChildOf(activeSpan) .WithTag(Tags.SpanKind, Tags.SpanKindClient) .WithTag(Tags.Component, _options.ComponentName) .WithTag(Tags.DbInstance, cmd.Connection.Database) .WithTag(Tags.DbStatement, cmd.CommandText) .Start(); _spanStorage.TryAdd(cmd, span); } break; case MicrosoftSqlClientDiagnosticOptions.EventNames.WriteCommandError: { var cmd = (SqlCommand)_activityCommand_RequestFetcher.Fetch(untypedArg); var ex = (Exception)_exception_ExceptionFetcher.Fetch(untypedArg); if (_spanStorage.TryRemove(cmd, out var span)) { span.SetException(ex); span.Finish(); } } break; case MicrosoftSqlClientDiagnosticOptions.EventNames.WriteCommandAfter: { var cmd = (SqlCommand)_activityCommand_RequestFetcher.Fetch(untypedArg); if (_spanStorage.TryRemove(cmd, out var span)) { span.Finish(); } } break; default: HandleUnknownEvent(eventName, untypedArg); break; } } private bool IgnoreEvent(SqlCommand sqlCommand) { foreach (Func ignore in _options.IgnorePatterns) { if (ignore(sqlCommand)) return true; } return false; } } } ================================================ FILE: src/OpenTracing.Contrib.NetCore/OpenTracing.Contrib.NetCore.csproj ================================================  netcoreapp3.1;net6.0;net7.0 Adds OpenTracing instrumentation for .NET Core apps that use the `Microsoft.Extensions.*` stack. Instrumented components: HttpClient calls, ASP.NET Core, Entity Framework Core and any other library that uses DiagnosticSource events. opentracing;distributed-tracing;tracing;netcore ================================================ FILE: src/OpenTracing.Contrib.NetCore/Properties/AssemblyInfo.cs ================================================ using System.Runtime.CompilerServices; [assembly: InternalsVisibleTo("OpenTracing.Contrib.NetCore.Tests, PublicKey=" + "00240000048000009400000006020000002400005253413100040000010001005d933a901e4687" + "a5fad68c57b11f12b925922968cb9b7c4ef5744b4e3c7d7535095fb13a87169a4dde0ef547a035" + "0089ae94e192dfeddfa8272b12a76cd42bd36d8b7003bfff49bc825c1a9d510b3c37549efac581" + "0194d6cfdac8c4dc2f465e4c893a32b65a2f2d55faa3d24d6e68d861a7ccdec74d80ccf03b4489" + "f51328ba")] [assembly: InternalsVisibleTo("OpenTracing.Contrib.NetCore.Benchmarks, PublicKey=" + "00240000048000009400000006020000002400005253413100040000010001005d933a901e4687" + "a5fad68c57b11f12b925922968cb9b7c4ef5744b4e3c7d7535095fb13a87169a4dde0ef547a035" + "0089ae94e192dfeddfa8272b12a76cd42bd36d8b7003bfff49bc825c1a9d510b3c37549efac581" + "0194d6cfdac8c4dc2f465e4c893a32b65a2f2d55faa3d24d6e68d861a7ccdec74d80ccf03b4489" + "f51328ba")] ================================================ FILE: src/OpenTracing.Contrib.NetCore/SystemSqlClient/SqlClientDiagnosticOptions.cs ================================================ using System; using System.Collections.Generic; using System.Data.SqlClient; using System.Linq; namespace OpenTracing.Contrib.NetCore.Configuration { public class SqlClientDiagnosticOptions : DiagnosticOptions { public const string DefaultComponent = "SqlClient"; public const string SqlClientPrefix = "sqlClient "; private string _componentName = DefaultComponent; private List> _ignorePatterns; private Func _operationNameResolver; /// /// A list of delegates that define whether or not a given SQL command should be ignored. /// /// If any delegate in the list returns true, the SQL command will be ignored. /// public List> IgnorePatterns => _ignorePatterns ??= new List>(); /// /// Allows changing the "component" tag of created spans. /// public string ComponentName { get => _componentName; set => _componentName = value ?? throw new ArgumentNullException(nameof(ComponentName)); } /// /// A delegate that returns the OpenTracing "operation name" for the given command. /// public Func OperationNameResolver { get { if (_operationNameResolver == null) { // Default value may not be set in the constructor because this would fail // if the target application does not reference SqlClient. _operationNameResolver = (cmd) => { var commandType = cmd.CommandText?.Split(' '); return $"{SqlClientPrefix}{commandType?.FirstOrDefault()}"; }; } return _operationNameResolver; } set => _operationNameResolver = value ?? throw new ArgumentNullException(nameof(OperationNameResolver)); } } } ================================================ FILE: src/OpenTracing.Contrib.NetCore/SystemSqlClient/SqlClientDiagnostics.cs ================================================ using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Data.SqlClient; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; using OpenTracing.Contrib.NetCore.Configuration; using OpenTracing.Contrib.NetCore.Internal; using OpenTracing.Tag; namespace OpenTracing.Contrib.NetCore.SystemSqlClient { internal sealed class SqlClientDiagnostics : DiagnosticEventObserver { public const string DiagnosticListenerName = "SqlClientDiagnosticListener"; private static readonly PropertyFetcher _writeCommandBefore_CommandFetcher = new PropertyFetcher("Command"); private static readonly PropertyFetcher _writeCommandError_CommandFetcher = new PropertyFetcher("Command"); private static readonly PropertyFetcher _writeCommandAfter_CommandFetcher = new PropertyFetcher("Command"); private static readonly PropertyFetcher _exception_ExceptionFetcher = new PropertyFetcher("Exception"); private readonly SqlClientDiagnosticOptions _options; private readonly ConcurrentDictionary _spanStorage; public SqlClientDiagnostics(ILoggerFactory loggerFactory, ITracer tracer, IOptions options) : base(loggerFactory, tracer, options?.Value) { _options = options?.Value ?? throw new ArgumentNullException(nameof(options)); _spanStorage = new ConcurrentDictionary(); } protected override string GetListenerName() => DiagnosticListenerName; /// /// Both diagnostic listeners for System.Data.SqlClient and Microsoft.Data.SqlClient use the same listener name, /// so we need to make sure this observer gets the correct events. /// protected override bool IsSupportedEvent(string eventName) => eventName.StartsWith("System."); protected override IEnumerable HandledEventNames() { yield return "System.Data.SqlClient.WriteCommandBefore"; yield return "System.Data.SqlClient.WriteCommandError"; yield return "System.Data.SqlClient.WriteCommandAfter"; } protected override void HandleEvent(string eventName, object untypedArg) { switch (eventName) { case "System.Data.SqlClient.WriteCommandBefore": { var cmd = (SqlCommand)_writeCommandBefore_CommandFetcher.Fetch(untypedArg); var activeSpan = Tracer.ActiveSpan; if (activeSpan == null && !_options.StartRootSpans) { if (IsLogLevelTraceEnabled) { Logger.LogTrace("Ignoring SQL command due to missing parent span"); } return; } if (IgnoreEvent(cmd)) { if (IsLogLevelTraceEnabled) { Logger.LogTrace("Ignoring SQL command due to IgnorePatterns"); } return; } string operationName = _options.OperationNameResolver(cmd); var span = Tracer.BuildSpan(operationName) .AsChildOf(activeSpan) .WithTag(Tags.SpanKind, Tags.SpanKindClient) .WithTag(Tags.Component, _options.ComponentName) .WithTag(Tags.DbInstance, cmd.Connection.Database) .WithTag(Tags.DbStatement, cmd.CommandText) .Start(); _spanStorage.TryAdd(cmd, span); } break; case "System.Data.SqlClient.WriteCommandError": { var cmd = (SqlCommand)_writeCommandError_CommandFetcher.Fetch(untypedArg); var ex = (Exception)_exception_ExceptionFetcher.Fetch(untypedArg); if (_spanStorage.TryRemove(cmd, out var span)) { span.SetException(ex); span.Finish(); } } break; case "System.Data.SqlClient.WriteCommandAfter": { var cmd = (SqlCommand)_writeCommandAfter_CommandFetcher.Fetch(untypedArg); if (_spanStorage.TryRemove(cmd, out var span)) { span.Finish(); } } break; default: HandleUnknownEvent(eventName, untypedArg); break; } } private bool IgnoreEvent(SqlCommand sqlCommand) { foreach (Func ignore in _options.IgnorePatterns) { if (ignore(sqlCommand)) return true; } return false; } } } ================================================ FILE: test/OpenTracing.Contrib.NetCore.Tests/AspNetCore/HostingTest.cs ================================================ using System; using System.Linq; using System.Net.Http; using System.Threading.Tasks; using Microsoft.AspNetCore; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc.Testing; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; using OpenTracing.Contrib.NetCore.AspNetCore; using OpenTracing.Contrib.NetCore.Configuration; using OpenTracing.Mock; using OpenTracing.Tag; using Xunit; using Xunit.Abstractions; namespace OpenTracing.Contrib.NetCore.Tests.AspNetCore { public class TestProgramFactory : WebApplicationFactory { protected override IWebHostBuilder CreateWebHostBuilder() { var host = WebHost.CreateDefaultBuilder() // https://stackoverflow.com/a/69776251/5214796 .UseSetting("TEST_CONTENTROOT_OPENTRACING_CONTRIB_NETCORE_TESTS", "") .ConfigureServices(services => { }) .Configure(app => { app.UseRouting(); app.UseEndpoints(endpoints => { endpoints.MapGet("/foo", async context => { await context.Response.WriteAsync("Hello"); }); endpoints.MapGet("/exception", _ => { throw new InvalidOperationException("You shall not pass"); }); }); }); return host; } } [Collection("DiagnosticSource") /* All DiagnosticSource tests must be in the same collection to ensure they are NOT run in parallel. */] public class HostingTest : IClassFixture, IDisposable { private readonly WebApplicationFactory _factory; private readonly MockTracer _tracer; private readonly HostingOptions _options; public HostingTest(TestProgramFactory factory, ITestOutputHelper output) { _tracer = new MockTracer(); AspNetCoreDiagnosticOptions aspNetCoreOptions = new(); _options = aspNetCoreOptions.Hosting; _factory = factory .WithWebHostBuilder(x => { x.ConfigureServices(services => { services.AddLogging(logging => { logging.AddXunit(output); logging.AddFilter("OpenTracing", LogLevel.Trace); }); services.AddOpenTracingCoreServices(builder => { builder.AddAspNetCore(); builder.Services.AddSingleton(_tracer); builder.Services.AddSingleton(Options.Create(aspNetCoreOptions)); }); }); }); } public void Dispose() { _factory.Dispose(); } private HttpClient CreateClient() { var client = _factory.CreateClient(); return client; } [Fact] public async Task Request_creates_span() { var client = CreateClient(); await client.GetAsync("/foo"); var finishedSpans = _tracer.FinishedSpans(); Assert.Single(finishedSpans); } [Fact] public async Task Span_has_correct_properties() { var client = CreateClient(); await client.GetAsync("/foo"); var finishedSpans = _tracer.FinishedSpans(); Assert.Single(finishedSpans); var span = finishedSpans[0]; Assert.Empty(span.GeneratedErrors); Assert.Single(span.LogEntries); Assert.Equal("Microsoft.AspNetCore.Routing.EndpointMatched", span.LogEntries[0].Fields["event"]); Assert.Equal("HTTP GET", span.OperationName); Assert.Null(span.ParentId); Assert.Empty(span.References); Assert.Equal(5, span.Tags.Count); Assert.Equal(Tags.SpanKindServer, span.Tags[Tags.SpanKind.Key]); Assert.Equal("HttpIn", span.Tags[Tags.Component.Key]); Assert.Equal("GET", span.Tags[Tags.HttpMethod.Key]); Assert.Equal("http://localhost/foo", span.Tags[Tags.HttpUrl.Key]); Assert.Equal(200, span.Tags[Tags.HttpStatus.Key]); } [Fact] public async Task Span_has_status_404() { var client = CreateClient(); await client.GetAsync("/not-found"); var finishedSpans = _tracer.FinishedSpans(); Assert.Single(finishedSpans); var span = finishedSpans[0]; Assert.Equal(404, span.Tags[Tags.HttpStatus.Key]); } [Fact] public async Task Extracts_trace_headers() { var client = CreateClient(); await client.SendAsync(new HttpRequestMessage(HttpMethod.Get, "/foo") { Headers = { { "traceid", "100" }, { "spanid", "101" }, } }); var finishedSpans = _tracer.FinishedSpans(); Assert.Single(finishedSpans); var span = finishedSpans[0]; Assert.Equal("100", span.Context.TraceId); Assert.Single(span.References); var reference = span.References[0]; Assert.Equal(References.ChildOf, reference.ReferenceType); Assert.Equal("100", reference.Context.TraceId); Assert.Equal("101", reference.Context.SpanId); } [Fact] public async Task Does_not_Extract_trace_headers_if_disabled_in_options() { var client = CreateClient(); await client.SendAsync(new HttpRequestMessage(HttpMethod.Get, "/foo") { Headers = { { "ignore", "1" }, } }); _options.ExtractEnabled = context => !context.Request.Headers.ContainsKey("ignore"); var finishedSpans = _tracer.FinishedSpans(); Assert.Single(finishedSpans); var span = finishedSpans[0]; Assert.Empty(span.References); } [Fact] public async Task Ignores_requests_with_custom_rule() { _options.IgnorePatterns.Add(context => context.Request.Headers.ContainsKey("ignore")); var client = CreateClient(); await client.SendAsync(new HttpRequestMessage(HttpMethod.Get, "/foo") { Headers = { { "ignore", "1" }, } }); Assert.Empty(_tracer.FinishedSpans()); } [Fact] public async Task Calls_Options_OperationNameResolver() { _options.OperationNameResolver = _ => "test"; var client = CreateClient(); await client.GetAsync("/foo"); var finishedSpans = _tracer.FinishedSpans(); Assert.Single(finishedSpans); var span = finishedSpans[0]; Assert.Equal("test", span.OperationName); } [Fact] public async Task Calls_Options_OnRequest() { bool onRequestCalled = false; _options.OnRequest = (_, __) => onRequestCalled = true; var client = CreateClient(); await client.GetAsync("/foo"); Assert.True(onRequestCalled); } [Fact] public async Task Calls_Options_OnError() { bool onErrorCalled = false; _options.OnError = (_, __, ___) => onErrorCalled = true; var client = CreateClient(); try { await client.GetAsync("/exception"); } catch (InvalidOperationException) { // The OnError handler is invoked after the request has been finished, // so we need to wait a little bit to make sure this test isn't failing sometimes. await Task.Delay(TimeSpan.FromMilliseconds(100)); } Assert.True(onErrorCalled); } [Fact] public async Task Creates_error_span_if_request_throws_exception() { var client = CreateClient(); try { await client.GetAsync("/exception"); } catch (InvalidOperationException) { } var finishedSpans = _tracer.FinishedSpans(); Assert.Single(finishedSpans); var span = finishedSpans[0]; Assert.True(span.Tags[Tags.Error.Key] as bool?); var logs = span.LogEntries; var error = logs.FirstOrDefault(x => x.Fields.TryGetValue(LogFields.Event, out object val) && val is string and "error"); Assert.NotNull(error); Assert.Equal("InvalidOperationException", error.Fields[LogFields.ErrorKind]); } } } ================================================ FILE: test/OpenTracing.Contrib.NetCore.Tests/CoreFx/HttpHandlerDiagnosticTest.cs ================================================ using System; using System.Collections.Generic; using System.Diagnostics; using System.Net; using System.Net.Http; using System.Reflection; using System.Threading; using System.Threading.Tasks; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; using OpenTracing.Contrib.NetCore.Configuration; using OpenTracing.Contrib.NetCore.Internal; using OpenTracing.Mock; using OpenTracing.Tag; using Xunit; using Xunit.Abstractions; namespace OpenTracing.Contrib.NetCore.Tests.CoreFx { [Collection("DiagnosticSource") /* All DiagnosticSource tests must be in the same collection to ensure they are NOT run in parallel. */] public class HttpHandlerDiagnosticTest : IDisposable { private readonly MockTracer _tracer; private readonly HttpHandlerDiagnosticOptions _options; private readonly DiagnosticManager _diagnosticsManager; private readonly MockHttpMessageHandler _httpHandler; private readonly HttpClient _httpClient; private class MockHttpMessageHandler : HttpMessageHandler { public Func OnSend = request => { return new HttpResponseMessage(HttpStatusCode.OK) { RequestMessage = request, Content = new StringContent("Response") }; }; protected override async Task SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) { // HACK: There MUST be an awaiter otherwise exceptions are not caught by the DiagnosticsHandler. // https://github.com/dotnet/corefx/pull/27472 await Task.CompletedTask; return OnSend(request); } } public HttpHandlerDiagnosticTest(ITestOutputHelper output) { _tracer = new MockTracer(); _options = new HttpHandlerDiagnosticOptions(); IServiceProvider serviceProvider = new ServiceCollection() .AddLogging(logging => { logging.AddXunit(output); }) .AddOpenTracingCoreServices(builder => { builder.AddHttpHandler(); builder.Services.AddSingleton(_tracer); builder.Services.AddSingleton(Options.Create(_options)); }) .BuildServiceProvider(); _diagnosticsManager = serviceProvider.GetRequiredService(); _diagnosticsManager.Start(); // Inner handler for mocking the result _httpHandler = new MockHttpMessageHandler(); // Wrap with DiagnosticsHandler (which is internal :( ) #if NETCOREAPP3_1 Type type = typeof(HttpClientHandler).Assembly.GetType("System.Net.Http.DiagnosticsHandler"); ConstructorInfo constructor = type.GetConstructors(BindingFlags.Instance | BindingFlags.Public)[0]; HttpMessageHandler diagnosticsHandler = (HttpMessageHandler)constructor.Invoke(new object[] { _httpHandler }); #else DistributedContextPropagator propagator = DistributedContextPropagator.CreateDefaultPropagator(); Type type = typeof(HttpClientHandler).Assembly.GetType("System.Net.Http.DiagnosticsHandler"); ConstructorInfo constructor = type.GetConstructors(BindingFlags.Instance | BindingFlags.Public)[0]; HttpMessageHandler diagnosticsHandler = (HttpMessageHandler)constructor.Invoke(new object[] { _httpHandler, propagator, false /* autoRedirect */ }); #endif _httpClient = new HttpClient(diagnosticsHandler); } public void Dispose() { _diagnosticsManager.Dispose(); } [Fact] public async Task Creates_span() { await _httpClient.SendAsync(new HttpRequestMessage(HttpMethod.Get, new Uri("http://www.example.com/api/values"))); Assert.Single(_tracer.FinishedSpans()); } [Fact] public async Task Span_is_child_of_parent() { // Create parent span using (var scope = _tracer.BuildSpan("parent").StartActive()) { await _httpClient.SendAsync(new HttpRequestMessage(HttpMethod.Get, new Uri("http://www.example.com/api/values"))); } var finishedSpans = _tracer.FinishedSpans(); Assert.Equal(2, finishedSpans.Count); // Inner span is finished first var childSpan = finishedSpans[0]; var parentSpan = finishedSpans[1]; Assert.NotSame(parentSpan, childSpan); Assert.Single(childSpan.References); Assert.Equal(References.ChildOf, childSpan.References[0].ReferenceType); Assert.Same(parentSpan.Context, childSpan.References[0].Context); } [Fact] public async Task Span_has_correct_properties() { await _httpClient.SendAsync(new HttpRequestMessage(HttpMethod.Get, new Uri("http://www.example.com/api/values"))); var finishedSpans = _tracer.FinishedSpans(); Assert.Single(finishedSpans); var span = finishedSpans[0]; Assert.Empty(span.GeneratedErrors); Assert.Empty(span.LogEntries); Assert.Equal("HTTP GET", span.OperationName); Assert.Null(span.ParentId); Assert.Empty(span.References); Assert.Equal(7, span.Tags.Count); Assert.Equal(Tags.SpanKindClient, span.Tags[Tags.SpanKind.Key]); Assert.Equal("HttpOut", span.Tags[Tags.Component.Key]); Assert.Equal("GET", span.Tags[Tags.HttpMethod.Key]); Assert.Equal("http://www.example.com/api/values", span.Tags[Tags.HttpUrl.Key]); Assert.Equal("www.example.com", span.Tags[Tags.PeerHostname.Key]); Assert.Equal(80, span.Tags[Tags.PeerPort.Key]); Assert.Equal(200, span.Tags[Tags.HttpStatus.Key]); } [Fact] public async Task Injects_trace_headers() { var request = new HttpRequestMessage(HttpMethod.Get, new Uri("http://www.example.com/api/values")); await _httpClient.SendAsync(request); Assert.True(request.Headers.Contains("traceid")); } [Fact] public async Task Does_not_inject_trace_headers_if_disabled_in_options() { #if NETCOREAPP3_1 _options.InjectEnabled = req => !req.Properties.ContainsKey("ignore"); #else _options.InjectEnabled = req => !((IDictionary)req.Options).ContainsKey("ignore"); #endif var request = new HttpRequestMessage(HttpMethod.Get, new Uri("http://www.example.com/api/values")); SetRequestOption(request, "ignore", true); await _httpClient.SendAsync(request); Assert.False(request.Headers.Contains("traceid")); } [Fact] public async Task Ignores_requests_with_Ignore_property() { var request = new HttpRequestMessage(HttpMethod.Get, new Uri("http://www.example.com/api/values")); SetRequestOption(request, HttpHandlerDiagnosticOptions.PropertyIgnore, true); await _httpClient.SendAsync(request); Assert.Empty(_tracer.FinishedSpans()); } [Fact] public async Task Ignores_requests_with_custom_rule() { #if NETCOREAPP3_1 _options.IgnorePatterns.Add(req => req.Properties.ContainsKey("foo")); #else _options.IgnorePatterns.Add(req => ((IDictionary) req.Options).ContainsKey("foo")); #endif var request = new HttpRequestMessage(HttpMethod.Get, new Uri("http://www.example.com/api/values")); SetRequestOption(request, "foo", 1); await _httpClient.SendAsync(request); Assert.Empty(_tracer.FinishedSpans()); } [Fact] public async Task Calls_Options_OperationNameResolver() { _options.OperationNameResolver = _ => "foo"; await _httpClient.SendAsync(new HttpRequestMessage(HttpMethod.Get, new Uri("http://www.example.com/api/values"))); var finishedSpans = _tracer.FinishedSpans(); Assert.Single(finishedSpans); var span = finishedSpans[0]; Assert.Equal("foo", span.OperationName); } [Fact] public async Task Calls_Options_OnRequest() { bool onRequestCalled = false; _options.OnRequest = (_, __) => onRequestCalled = true; await _httpClient.SendAsync(new HttpRequestMessage(HttpMethod.Get, new Uri("http://www.example.com/api/values"))); Assert.True(onRequestCalled); } [Fact] public async Task Calls_Options_OnError() { bool onErrorCalled = false; _options.OnError = (_, __, ___) => onErrorCalled = true; var request = new HttpRequestMessage(HttpMethod.Get, new Uri("http://www.example.com/api/values")); _httpHandler.OnSend = _ => throw new InvalidOperationException(); await Assert.ThrowsAsync(() => _httpClient.SendAsync(request)); Assert.True(onErrorCalled); } [Fact] public async Task Creates_error_span_if_request_times_out() { var request = new HttpRequestMessage(HttpMethod.Get, new Uri("http://www.example.com/api/values")); _httpHandler.OnSend = _ => throw new TaskCanceledException(); await Assert.ThrowsAsync(() => _httpClient.SendAsync(request)); var finishedSpans = _tracer.FinishedSpans(); Assert.Single(finishedSpans); var span = finishedSpans[0]; Assert.True(span.Tags[Tags.Error.Key] as bool?); } [Fact] public async Task Creates_error_span_if_request_fails() { var request = new HttpRequestMessage(HttpMethod.Get, new Uri("http://www.example.com/api/values")); _httpHandler.OnSend = _ => throw new InvalidOperationException(); await Assert.ThrowsAsync(() => _httpClient.SendAsync(request)); var finishedSpans = _tracer.FinishedSpans(); Assert.Single(finishedSpans); var span = finishedSpans[0]; Assert.True(span.Tags[Tags.Error.Key] as bool?); } private void SetRequestOption(HttpRequestMessage request, string key, TValue value) { #if NETCOREAPP3_1 request.Properties[key] = value; #else request.Options.Set(new HttpRequestOptionsKey(key), value); #endif } } } ================================================ FILE: test/OpenTracing.Contrib.NetCore.Tests/Internal/DiagnosticManagerTest.cs ================================================ using System.Collections.Generic; using Microsoft.Extensions.Logging.Abstractions; using Microsoft.Extensions.Options; using OpenTracing.Contrib.NetCore.Internal; using OpenTracing.Mock; using OpenTracing.Noop; using OpenTracing.Util; using Xunit; namespace OpenTracing.Contrib.NetCore.Tests.Internal { public class DiagnosticManagerTest { [Fact] public void Does_not_Start_if_Tracer_is_NoopTracer() { var loggerFactory = new NullLoggerFactory(); var tracer = NoopTracerFactory.Create(); var diagnosticSubscribers = new List(); var options = Options.Create(new DiagnosticManagerOptions()); using (DiagnosticManager diagnosticManager = new DiagnosticManager(loggerFactory, tracer, diagnosticSubscribers, options)) { Assert.False(diagnosticManager.IsRunning); diagnosticManager.Start(); Assert.False(diagnosticManager.IsRunning); } } [Fact] public void Does_not_Start_if_Tracer_is_GlobalTracer_with_NoopTracer() { var loggerFactory = new NullLoggerFactory(); var tracer = GlobalTracer.Instance; var diagnosticSubscribers = new List(); var options = Options.Create(new DiagnosticManagerOptions()); using (DiagnosticManager diagnosticManager = new DiagnosticManager(loggerFactory, tracer, diagnosticSubscribers, options)) { Assert.False(diagnosticManager.IsRunning); diagnosticManager.Start(); Assert.False(diagnosticManager.IsRunning); } } [Fact] public void Start_if_valid_Tracer() { var loggerFactory = new NullLoggerFactory(); var tracer = new MockTracer(); var diagnosticSubscribers = new List(); var options = Options.Create(new DiagnosticManagerOptions()); using (DiagnosticManager diagnosticManager = new DiagnosticManager(loggerFactory, tracer, diagnosticSubscribers, options)) { Assert.False(diagnosticManager.IsRunning); diagnosticManager.Start(); Assert.True(diagnosticManager.IsRunning); } } } } ================================================ FILE: test/OpenTracing.Contrib.NetCore.Tests/Internal/PropertyFetcherTest.cs ================================================ using OpenTracing.Contrib.NetCore.Internal; using Xunit; namespace OpenTracing.Contrib.NetCore.Tests.Internal { public class PropertyFetcherTest { public class TestClass { public string TestProperty { get; set; } } [Fact] public void Fetch_NameNotFound_NullReturned() { var obj = new TestClass { TestProperty = "TestValue" }; var sut = new PropertyFetcher("DifferentProperty"); var result = sut.Fetch(obj); Assert.Null(result); } [Fact] public void Fetch_NameFound_ValueReturned() { var obj = new TestClass { TestProperty = "TestValue" }; var sut = new PropertyFetcher("TestProperty"); var result = sut.Fetch(obj); Assert.Equal("TestValue", result); } [Fact] public void Fetch_NameFoundDifferentCasing_ValueReturned() { var obj = new TestClass { TestProperty = "TestValue" }; var sut = new PropertyFetcher("testproperty"); var result = sut.Fetch(obj); Assert.Equal("TestValue", result); } } } ================================================ FILE: test/OpenTracing.Contrib.NetCore.Tests/Logging/LoggingDependencyInjectionTest.cs ================================================ using System; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using OpenTracing.Propagation; using Xunit; namespace OpenTracing.Contrib.Netcore.Tests.Logging { public class LoggingDependencyInjectionTest { [Fact] public void Resolving_tracer_that_needs_ILoggerFactory_succeeds() { // https://github.com/opentracing-contrib/csharp-netcore/issues/14 var serviceProvider = new ServiceCollection() .AddLogging() .AddOpenTracingCoreServices(ot => { ot.AddLoggerProvider(); ot.Services.AddSingleton(); }) .BuildServiceProvider(); var tracer = serviceProvider.GetRequiredService(); Assert.IsType(tracer); } private class TracerWithLoggerFactory : ITracer { public TracerWithLoggerFactory(ILoggerFactory loggerFactory) { } public IScopeManager ScopeManager => throw new NotSupportedException(); public ISpan ActiveSpan => throw new NotSupportedException(); public ISpanBuilder BuildSpan(string operationName) { throw new NotSupportedException(); } public ISpanContext Extract(IFormat format, TCarrier carrier) { throw new NotSupportedException(); } public void Inject(ISpanContext spanContext, IFormat format, TCarrier carrier) { throw new NotSupportedException(); } } } } ================================================ FILE: test/OpenTracing.Contrib.NetCore.Tests/Logging/LoggingTest.cs ================================================ #pragma warning disable CA2017 using System; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using NSubstitute; using OpenTracing.Contrib.NetCore.Internal; using OpenTracing.Mock; using Xunit; namespace OpenTracing.Contrib.NetCore.Tests.Logging { public class LoggingTest { private readonly MockTracer _tracer; private readonly ILoggerFactory _loggerFactory; private readonly ILogger _logger; public LoggingTest() { var serviceProvider = new ServiceCollection() .AddLogging() .AddOpenTracingCoreServices(ot => { ot.AddLoggerProvider(); ot.Services.AddSingleton(); ot.Services.AddSingleton(sp => { var globalTracerAccessor = Substitute.For(); globalTracerAccessor.GetGlobalTracer().Returns(sp.GetRequiredService()); return globalTracerAccessor; }); }) .BuildServiceProvider(); _loggerFactory = serviceProvider.GetRequiredService(); _logger = _loggerFactory.CreateLogger("FooLogger"); _tracer = (MockTracer)serviceProvider.GetRequiredService(); } private IScope StartScope(string operationName = "FooOperation") { return _tracer.BuildSpan(operationName) .StartActive(); } private MockSpan.LogEntry Log(Action actionUnderScope) { using (StartScope()) { actionUnderScope.Invoke(); } var finishedSpans = _tracer.FinishedSpans(); Assert.Single(finishedSpans); var span = finishedSpans[0]; var logEntries = span.LogEntries; Assert.Single(logEntries); return logEntries[0]; } [Fact] public void Logger_does_not_create_span_if_no_ActiveSpan() { _logger.LogInformation("Hello World"); Assert.Empty(_tracer.FinishedSpans()); } [Fact] public void Logger_adds_Log_to_ActiveSpan() { using (StartScope()) { _logger.LogInformation("Hello World"); } var finishedSpans = _tracer.FinishedSpans(); Assert.Single(finishedSpans); var span = finishedSpans[0]; var logEntries = span.LogEntries; Assert.Single(logEntries); } [Fact] public void Logger_adds_multiple_Log_to_ActiveSpan() { using (StartScope()) { _logger.LogInformation("Hello World"); _logger.LogWarning("Some warning"); } var finishedSpans = _tracer.FinishedSpans(); Assert.Single(finishedSpans); var span = finishedSpans[0]; var logEntries = span.LogEntries; Assert.Equal(2, logEntries.Count); } [Fact] public void Correct_fields_for_LogInformation_with_null_message() { // TODO Is it useful to create log entries with a "[null]" message? var logEntry = Log(() => _logger.LogInformation(null)); Assert.Equal(4, logEntry.Fields.Count); Assert.Equal("FooLogger", logEntry.Fields["component"]); Assert.Equal("Information", logEntry.Fields["level"]); Assert.Equal("[null]", logEntry.Fields[LogFields.Message]); Assert.Equal("[null]", logEntry.Fields[LogFields.Event]); } [Fact] public void Correct_fields_for_LogInformation_with_message() { // TODO is it ok to emit "Hello World" twice? var logEntry = Log(() => _logger.LogInformation("Hello World")); Assert.Equal(4, logEntry.Fields.Count); Assert.Equal("FooLogger", logEntry.Fields["component"]); Assert.Equal("Information", logEntry.Fields["level"]); Assert.Equal("Hello World", logEntry.Fields[LogFields.Message]); Assert.Equal("Hello World", logEntry.Fields[LogFields.Event]); } [Fact] public void Args_are_NOT_propagated_if_they_are_not_used_in_messageTemplate() { // This currently is by design: https://github.com/aspnet/Logging/issues/533 int arg1 = 4; string arg2 = "bar"; var logEntry = Log(() => _logger.LogInformation("Hello World", arg1, arg2)); Assert.Equal(4, logEntry.Fields.Count); Assert.Equal("FooLogger", logEntry.Fields["component"]); Assert.Equal("Information", logEntry.Fields["level"]); Assert.Equal("Hello World", logEntry.Fields[LogFields.Message]); Assert.Equal("Hello World", logEntry.Fields[LogFields.Event]); } [Fact] public void Correct_fields_for_LogInformation_with_messageTemplate_without_args() { var logEntry = Log(() => _logger.LogInformation("Hello {Name}")); Assert.Equal(4, logEntry.Fields.Count); Assert.Equal("FooLogger", logEntry.Fields["component"]); Assert.Equal("Information", logEntry.Fields["level"]); Assert.Equal("Hello {Name}", logEntry.Fields[LogFields.Message]); Assert.Equal("Hello {Name}", logEntry.Fields[LogFields.Event]); } [Fact] public void Correct_fields_for_LogInformation_with_messageTemplate_and_not_enough_args() { // TODO This throws in Microsoft.Extensions.Logging when generating the "Message" and we currently just ignore it. string arg1 = "Max"; var logEntry = Log(() => _logger.LogInformation("Hello {Arg1} {Arg2}", arg1)); Assert.Equal(4, logEntry.Fields.Count); Assert.Equal("FooLogger", logEntry.Fields["component"]); Assert.Equal("Information", logEntry.Fields["level"]); Assert.Equal("log", logEntry.Fields[LogFields.Event]); Assert.Equal("Max", logEntry.Fields["Arg1"]); } [Fact] public void Correct_fields_for_LogInformation_with_messageTemplate_with_one_arg() { string name = "Max"; var logEntry = Log(() => _logger.LogInformation("Hello {Name}", name)); Assert.Equal(5, logEntry.Fields.Count); Assert.Equal("FooLogger", logEntry.Fields["component"]); Assert.Equal("Information", logEntry.Fields["level"]); Assert.Equal("Hello Max", logEntry.Fields[LogFields.Message]); Assert.Equal("Hello {Name}", logEntry.Fields[LogFields.Event]); Assert.Equal("Max", logEntry.Fields["Name"]); } [Fact] public void Correct_fields_for_LogInformation_with_messageTemplate_with_two_arg() { string arg1 = "Max"; int arg2 = 3; var logEntry = Log(() => _logger.LogInformation("Hello {Arg1}, {Arg2}", arg1, arg2)); Assert.Equal(6, logEntry.Fields.Count); Assert.Equal("FooLogger", logEntry.Fields["component"]); Assert.Equal("Information", logEntry.Fields["level"]); Assert.Equal("Hello Max, 3", logEntry.Fields[LogFields.Message]); Assert.Equal("Hello {Arg1}, {Arg2}", logEntry.Fields[LogFields.Event]); Assert.Equal("Max", logEntry.Fields["Arg1"]); Assert.Equal(3, logEntry.Fields["Arg2"]); } [Fact] public void Arg_overwrites_builtin_fields() { // TODO Is this behavior ok? string level = "Test"; var logEntry = Log(() => _logger.LogInformation("Hello {level}", level)); Assert.Equal(4, logEntry.Fields.Count); Assert.Equal("FooLogger", logEntry.Fields["component"]); Assert.Equal("Test", logEntry.Fields["level"]); Assert.Equal("Hello Test", logEntry.Fields[LogFields.Message]); Assert.Equal("Hello {level}", logEntry.Fields[LogFields.Event]); } [Fact] public void Correct_fields_for_LogInformation_with_eventId() { var logEntry = Log(() => _logger.LogInformation(new EventId(1), "Hello World")); Assert.Equal(5, logEntry.Fields.Count); Assert.Equal("FooLogger", logEntry.Fields["component"]); Assert.Equal("Information", logEntry.Fields["level"]); Assert.Equal("Hello World", logEntry.Fields[LogFields.Message]); Assert.Equal("Hello World", logEntry.Fields[LogFields.Event]); Assert.Equal(1, logEntry.Fields["eventId"]); } [Fact] public void Correct_fields_for_LogInformation_with_exception() { var exception = new InvalidOperationException("Something went wrong"); var logEntry = Log(() => _logger.LogInformation(exception, "Hello World")); Assert.Equal(6, logEntry.Fields.Count); Assert.Equal("FooLogger", logEntry.Fields["component"]); Assert.Equal("Information", logEntry.Fields["level"]); Assert.Equal("Hello World", logEntry.Fields[LogFields.Message]); Assert.Equal("Hello World", logEntry.Fields[LogFields.Event]); Assert.Equal("System.InvalidOperationException", logEntry.Fields[LogFields.ErrorKind]); // TODO use FullName or Name? Assert.Same(exception, logEntry.Fields[LogFields.ErrorObject]); } [Fact] public void Correct_fields_for_LogInformation_with_exception_and_args() { var arg1 = "Max"; var arg2 = 3; var exception = new InvalidOperationException("Something went wrong"); var logEntry = Log(() => _logger.LogInformation(exception, "Hello World {Arg1} {Arg2}", arg1, arg2)); Assert.Equal(8, logEntry.Fields.Count); Assert.Equal("FooLogger", logEntry.Fields["component"]); Assert.Equal("Information", logEntry.Fields["level"]); Assert.Equal("Hello World Max 3", logEntry.Fields[LogFields.Message]); Assert.Equal("Hello World {Arg1} {Arg2}", logEntry.Fields[LogFields.Event]); Assert.Equal("Max", logEntry.Fields["Arg1"]); Assert.Equal(3, logEntry.Fields["Arg2"]); Assert.Equal("System.InvalidOperationException", logEntry.Fields[LogFields.ErrorKind]); // TODO use FullName or Name? Assert.Same(exception, logEntry.Fields[LogFields.ErrorObject]); } } } ================================================ FILE: test/OpenTracing.Contrib.NetCore.Tests/OpenTracing.Contrib.NetCore.Tests.csproj ================================================  netcoreapp3.1;net6.0;net7.0 ================================================ FILE: test/OpenTracing.Contrib.NetCore.Tests/XunitLogging/XunitLoggerFactoryExtensions.cs ================================================ // From https://github.com/aspnet/Logging/blob/dev/src/Microsoft.Extensions.Logging.Testing/XunitLoggerFactoryExtensions.cs using Microsoft.Extensions.DependencyInjection; using OpenTracing.Contrib.NetCore.Tests.XunitLogging; using Xunit.Abstractions; namespace Microsoft.Extensions.Logging { public static class XunitLoggerFactoryExtensions { public static ILoggingBuilder AddXunit(this ILoggingBuilder builder, ITestOutputHelper output) { builder.Services.AddSingleton(new XunitLoggerProvider(output)); return builder; } public static ILoggingBuilder AddXunit(this ILoggingBuilder builder, ITestOutputHelper output, LogLevel minLevel) { builder.Services.AddSingleton(new XunitLoggerProvider(output, minLevel)); return builder; } public static ILoggerFactory AddXunit(this ILoggerFactory loggerFactory, ITestOutputHelper output) { loggerFactory.AddProvider(new XunitLoggerProvider(output)); return loggerFactory; } public static ILoggerFactory AddXunit(this ILoggerFactory loggerFactory, ITestOutputHelper output, LogLevel minLevel) { loggerFactory.AddProvider(new XunitLoggerProvider(output, minLevel)); return loggerFactory; } } } ================================================ FILE: test/OpenTracing.Contrib.NetCore.Tests/XunitLogging/XunitLoggerProvider.cs ================================================ // From https://github.com/aspnet/Logging/blob/dev/src/Microsoft.Extensions.Logging.Testing/XunitLoggerProvider.cs using System; using System.Linq; using System.Text; using Microsoft.Extensions.Logging; using Xunit.Abstractions; namespace OpenTracing.Contrib.NetCore.Tests.XunitLogging { public class XunitLoggerProvider : ILoggerProvider { private readonly ITestOutputHelper _output; private readonly LogLevel _minLevel; public XunitLoggerProvider(ITestOutputHelper output) : this(output, LogLevel.Trace) { } public XunitLoggerProvider(ITestOutputHelper output, LogLevel minLevel) { _output = output; _minLevel = minLevel; } public ILogger CreateLogger(string categoryName) { return new XunitLogger(_output, categoryName, _minLevel); } public void Dispose() { } } public class XunitLogger : ILogger { private static readonly string[] NewLineChars = new[] { Environment.NewLine }; private readonly string _category; private readonly LogLevel _minLogLevel; private readonly ITestOutputHelper _output; public XunitLogger(ITestOutputHelper output, string category, LogLevel minLogLevel) { _minLogLevel = minLogLevel; _category = category; _output = output; } public void Log( LogLevel logLevel, EventId eventId, TState state, Exception exception, Func formatter) { if (!IsEnabled(logLevel)) { return; } // Buffer the message into a single string in order to avoid shearing the message when running across multiple threads. var messageBuilder = new StringBuilder(); var firstLinePrefix = $"| {_category} {logLevel}: "; var lines = formatter(state, exception).Split(NewLineChars, StringSplitOptions.RemoveEmptyEntries); messageBuilder.AppendLine(firstLinePrefix + lines.First()); var additionalLinePrefix = "|" + new string(' ', firstLinePrefix.Length - 1); foreach (var line in lines.Skip(1)) { messageBuilder.AppendLine(additionalLinePrefix + line); } if (exception != null) { lines = exception.ToString().Split(NewLineChars, StringSplitOptions.RemoveEmptyEntries); additionalLinePrefix = "| "; foreach (var line in lines) { messageBuilder.AppendLine(additionalLinePrefix + line); } } // Remove the last line-break, because ITestOutputHelper only has WriteLine. var message = messageBuilder.ToString(); if (message.EndsWith(Environment.NewLine)) { message = message.Substring(0, message.Length - Environment.NewLine.Length); } try { _output.WriteLine(message); } catch (Exception) { // We could fail because we're on a background thread and our captured ITestOutputHelper is // busted (if the test "completed" before the background thread fired). // So, ignore this. There isn't really anything we can do but hope the // caller has additional loggers registered } } public bool IsEnabled(LogLevel logLevel) => logLevel >= _minLogLevel; public IDisposable BeginScope(TState state) => new NullScope(); private class NullScope : IDisposable { public void Dispose() { } } } } ================================================ FILE: version.props ================================================ 99.99.99 loc$([System.DateTime]::UtcNow.ToString('yyyyMMddHHmm')) ci$([System.Int32]::Parse($(APPVEYOR_BUILD_NUMBER)).ToString('D4')) $(APPVEYOR_REPO_TAG_NAME.TrimStart('v'))