├── .gitattributes ├── .github ├── ISSUE_TEMPLATE │ └── feature_request.md └── workflows │ └── dotnet.yml ├── .gitignore ├── LICENSE ├── LoggingDecoratorGenerator.IntegrationTests ├── IDurationAsMetricTests.cs ├── IInformationLevelInterface.cs ├── ISomeService.cs ├── InformationLevelInterfaceTests.cs ├── LoggingDecoratorGenerator.IntegrationTests.csproj ├── PolymorphicInterfaces.cs ├── PolymorphicInterfacesTests.cs ├── SomeServiceTests.cs └── Usings.cs ├── LoggingDecoratorGenerator.Tests ├── GeneratorSnapshotTests.GeneratesCorrectly#DecorateWithLoggerAttribute.g.verified.cs ├── GeneratorSnapshotTests.GeneratesCorrectly#LogMethodAttribute.g.verified.cs ├── GeneratorSnapshotTests.GeneratesCorrectly#NotLoggedAttribute.g.verified.cs ├── GeneratorSnapshotTests.GeneratesCorrectly#SomeServiceLoggingDecorator.g.verified.cs ├── GeneratorSnapshotTests.cs ├── LoggingDecoratorGenerator.Tests.csproj ├── ModuleInitializer.cs ├── TestHelper.cs └── Usings.cs ├── LoggingDecoratorGenerator.sln ├── LoggingDecoratorGenerator ├── Attributes.cs ├── CompilerErrorException.cs ├── DecoratorClass.cs ├── DecoratorGenerator.cs ├── DiagnosticDescriptors.cs ├── Fineboym.Logging.Generator.csproj ├── LogLevelConverter.cs ├── MethodToGenerate.cs ├── Parameter.cs ├── Parser.cs ├── RoslynExtensions.cs └── SourceGenerationHelper.cs ├── NuGetReadme.md ├── README.md └── icon.png /.gitattributes: -------------------------------------------------------------------------------- 1 | ############################################################################### 2 | # Set default behavior to automatically normalize line endings. 3 | ############################################################################### 4 | * text=auto 5 | 6 | ############################################################################### 7 | # Set default behavior for command prompt diff. 8 | # 9 | # This is need for earlier builds of msysgit that does not have it on by 10 | # default for csharp files. 11 | # Note: This is only used by command line 12 | ############################################################################### 13 | #*.cs diff=csharp 14 | 15 | ############################################################################### 16 | # Set the merge driver for project and solution files 17 | # 18 | # Merging from the command prompt will add diff markers to the files if there 19 | # are conflicts (Merging from VS is not affected by the settings below, in VS 20 | # the diff markers are never inserted). Diff markers may cause the following 21 | # file extensions to fail to load in VS. An alternative would be to treat 22 | # these files as binary and thus will always conflict and require user 23 | # intervention with every merge. To do so, just uncomment the entries below 24 | ############################################################################### 25 | #*.sln merge=binary 26 | #*.csproj merge=binary 27 | #*.vbproj merge=binary 28 | #*.vcxproj merge=binary 29 | #*.vcproj merge=binary 30 | #*.dbproj merge=binary 31 | #*.fsproj merge=binary 32 | #*.lsproj merge=binary 33 | #*.wixproj merge=binary 34 | #*.modelproj merge=binary 35 | #*.sqlproj merge=binary 36 | #*.wwaproj merge=binary 37 | 38 | ############################################################################### 39 | # behavior for image files 40 | # 41 | # image files are treated as binary by default. 42 | ############################################################################### 43 | #*.jpg binary 44 | #*.png binary 45 | #*.gif binary 46 | 47 | ############################################################################### 48 | # diff behavior for common document formats 49 | # 50 | # Convert binary document formats to text before diffing them. This feature 51 | # is only available from the command line. Turn it on by uncommenting the 52 | # entries below. 53 | ############################################################################### 54 | #*.doc diff=astextplain 55 | #*.DOC diff=astextplain 56 | #*.docx diff=astextplain 57 | #*.DOCX diff=astextplain 58 | #*.dot diff=astextplain 59 | #*.DOT diff=astextplain 60 | #*.pdf diff=astextplain 61 | #*.PDF diff=astextplain 62 | #*.rtf diff=astextplain 63 | #*.RTF diff=astextplain 64 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/feature_request.md: -------------------------------------------------------------------------------- 1 | --- 2 | name: Feature request 3 | about: Suggest an idea for this project 4 | title: '' 5 | labels: '' 6 | assignees: '' 7 | 8 | --- 9 | 10 | **Is your feature request related to a problem? Please describe.** 11 | A clear and concise description of what the problem is. Ex. I'm always frustrated when [...] 12 | 13 | **Describe the solution you'd like** 14 | A clear and concise description of what you want to happen. 15 | 16 | **Describe alternatives you've considered** 17 | A clear and concise description of any alternative solutions or features you've considered. 18 | 19 | **Additional context** 20 | Add any other context or screenshots about the feature request here. 21 | -------------------------------------------------------------------------------- /.github/workflows/dotnet.yml: -------------------------------------------------------------------------------- 1 | # This workflow will build a .NET project 2 | # For more information see: https://docs.github.com/en/actions/automating-builds-and-tests/building-and-testing-net 3 | 4 | name: .NET 5 | 6 | on: 7 | push: 8 | branches: [ "master" ] 9 | pull_request: 10 | branches: [ "master" ] 11 | 12 | jobs: 13 | build: 14 | 15 | runs-on: ubuntu-latest 16 | 17 | steps: 18 | - uses: actions/checkout@v3 19 | - name: Setup .NET 20 | uses: actions/setup-dotnet@v3 21 | with: 22 | dotnet-version: 7.0.x 23 | - name: Restore dependencies 24 | run: dotnet restore 25 | - name: Build 26 | run: dotnet build --no-restore 27 | - name: Test 28 | run: dotnet test --no-build --verbosity normal 29 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | ## Ignore Visual Studio temporary files, build results, and 2 | ## files generated by popular Visual Studio add-ons. 3 | ## 4 | ## Get latest from https://github.com/github/gitignore/blob/master/VisualStudio.gitignore 5 | 6 | # User-specific files 7 | *.rsuser 8 | *.suo 9 | *.user 10 | *.userosscache 11 | *.sln.docstates 12 | 13 | # User-specific files (MonoDevelop/Xamarin Studio) 14 | *.userprefs 15 | 16 | # Mono auto generated files 17 | mono_crash.* 18 | 19 | # Build results 20 | [Dd]ebug/ 21 | [Dd]ebugPublic/ 22 | [Rr]elease/ 23 | [Rr]eleases/ 24 | x64/ 25 | x86/ 26 | [Ww][Ii][Nn]32/ 27 | [Aa][Rr][Mm]/ 28 | [Aa][Rr][Mm]64/ 29 | bld/ 30 | [Bb]in/ 31 | [Oo]bj/ 32 | [Oo]ut/ 33 | [Ll]og/ 34 | [Ll]ogs/ 35 | 36 | # Visual Studio 2015/2017 cache/options directory 37 | .vs/ 38 | # Uncomment if you have tasks that create the project's static files in wwwroot 39 | #wwwroot/ 40 | 41 | # Visual Studio 2017 auto generated files 42 | Generated\ Files/ 43 | 44 | # MSTest test Results 45 | [Tt]est[Rr]esult*/ 46 | [Bb]uild[Ll]og.* 47 | 48 | # NUnit 49 | *.VisualState.xml 50 | TestResult.xml 51 | nunit-*.xml 52 | 53 | # Build Results of an ATL Project 54 | [Dd]ebugPS/ 55 | [Rr]eleasePS/ 56 | dlldata.c 57 | 58 | # Benchmark Results 59 | BenchmarkDotNet.Artifacts/ 60 | 61 | # .NET Core 62 | project.lock.json 63 | project.fragment.lock.json 64 | artifacts/ 65 | 66 | # ASP.NET Scaffolding 67 | ScaffoldingReadMe.txt 68 | 69 | # StyleCop 70 | StyleCopReport.xml 71 | 72 | # Files built by Visual Studio 73 | *_i.c 74 | *_p.c 75 | *_h.h 76 | *.ilk 77 | *.meta 78 | *.obj 79 | *.iobj 80 | *.pch 81 | *.pdb 82 | *.ipdb 83 | *.pgc 84 | *.pgd 85 | *.rsp 86 | *.sbr 87 | *.tlb 88 | *.tli 89 | *.tlh 90 | *.tmp 91 | *.tmp_proj 92 | *_wpftmp.csproj 93 | *.log 94 | *.vspscc 95 | *.vssscc 96 | .builds 97 | *.pidb 98 | *.svclog 99 | *.scc 100 | 101 | # Chutzpah Test files 102 | _Chutzpah* 103 | 104 | # Visual C++ cache files 105 | ipch/ 106 | *.aps 107 | *.ncb 108 | *.opendb 109 | *.opensdf 110 | *.sdf 111 | *.cachefile 112 | *.VC.db 113 | *.VC.VC.opendb 114 | 115 | # Visual Studio profiler 116 | *.psess 117 | *.vsp 118 | *.vspx 119 | *.sap 120 | 121 | # Visual Studio Trace Files 122 | *.e2e 123 | 124 | # TFS 2012 Local Workspace 125 | $tf/ 126 | 127 | # Guidance Automation Toolkit 128 | *.gpState 129 | 130 | # ReSharper is a .NET coding add-in 131 | _ReSharper*/ 132 | *.[Rr]e[Ss]harper 133 | *.DotSettings.user 134 | 135 | # TeamCity is a build add-in 136 | _TeamCity* 137 | 138 | # DotCover is a Code Coverage Tool 139 | *.dotCover 140 | 141 | # AxoCover is a Code Coverage Tool 142 | .axoCover/* 143 | !.axoCover/settings.json 144 | 145 | # Coverlet is a free, cross platform Code Coverage Tool 146 | coverage*.json 147 | coverage*.xml 148 | coverage*.info 149 | 150 | # Visual Studio code coverage results 151 | *.coverage 152 | *.coveragexml 153 | 154 | # NCrunch 155 | _NCrunch_* 156 | .*crunch*.local.xml 157 | nCrunchTemp_* 158 | 159 | # MightyMoose 160 | *.mm.* 161 | AutoTest.Net/ 162 | 163 | # Web workbench (sass) 164 | .sass-cache/ 165 | 166 | # Installshield output folder 167 | [Ee]xpress/ 168 | 169 | # DocProject is a documentation generator add-in 170 | DocProject/buildhelp/ 171 | DocProject/Help/*.HxT 172 | DocProject/Help/*.HxC 173 | DocProject/Help/*.hhc 174 | DocProject/Help/*.hhk 175 | DocProject/Help/*.hhp 176 | DocProject/Help/Html2 177 | DocProject/Help/html 178 | 179 | # Click-Once directory 180 | publish/ 181 | 182 | # Publish Web Output 183 | *.[Pp]ublish.xml 184 | *.azurePubxml 185 | # Note: Comment the next line if you want to checkin your web deploy settings, 186 | # but database connection strings (with potential passwords) will be unencrypted 187 | *.pubxml 188 | *.publishproj 189 | 190 | # Microsoft Azure Web App publish settings. Comment the next line if you want to 191 | # checkin your Azure Web App publish settings, but sensitive information contained 192 | # in these scripts will be unencrypted 193 | PublishScripts/ 194 | 195 | # NuGet Packages 196 | *.nupkg 197 | # NuGet Symbol Packages 198 | *.snupkg 199 | # The packages folder can be ignored because of Package Restore 200 | **/[Pp]ackages/* 201 | # except build/, which is used as an MSBuild target. 202 | !**/[Pp]ackages/build/ 203 | # Uncomment if necessary however generally it will be regenerated when needed 204 | #!**/[Pp]ackages/repositories.config 205 | # NuGet v3's project.json files produces more ignorable files 206 | *.nuget.props 207 | *.nuget.targets 208 | 209 | # Microsoft Azure Build Output 210 | csx/ 211 | *.build.csdef 212 | 213 | # Microsoft Azure Emulator 214 | ecf/ 215 | rcf/ 216 | 217 | # Windows Store app package directories and files 218 | AppPackages/ 219 | BundleArtifacts/ 220 | Package.StoreAssociation.xml 221 | _pkginfo.txt 222 | *.appx 223 | *.appxbundle 224 | *.appxupload 225 | 226 | # Visual Studio cache files 227 | # files ending in .cache can be ignored 228 | *.[Cc]ache 229 | # but keep track of directories ending in .cache 230 | !?*.[Cc]ache/ 231 | 232 | # Others 233 | ClientBin/ 234 | ~$* 235 | *~ 236 | *.dbmdl 237 | *.dbproj.schemaview 238 | *.jfm 239 | *.pfx 240 | *.publishsettings 241 | orleans.codegen.cs 242 | 243 | # Including strong name files can present a security risk 244 | # (https://github.com/github/gitignore/pull/2483#issue-259490424) 245 | #*.snk 246 | 247 | # Since there are multiple workflows, uncomment next line to ignore bower_components 248 | # (https://github.com/github/gitignore/pull/1529#issuecomment-104372622) 249 | #bower_components/ 250 | 251 | # RIA/Silverlight projects 252 | Generated_Code/ 253 | 254 | # Backup & report files from converting an old project file 255 | # to a newer Visual Studio version. Backup files are not needed, 256 | # because we have git ;-) 257 | _UpgradeReport_Files/ 258 | Backup*/ 259 | UpgradeLog*.XML 260 | UpgradeLog*.htm 261 | ServiceFabricBackup/ 262 | *.rptproj.bak 263 | 264 | # SQL Server files 265 | *.mdf 266 | *.ldf 267 | *.ndf 268 | 269 | # Business Intelligence projects 270 | *.rdl.data 271 | *.bim.layout 272 | *.bim_*.settings 273 | *.rptproj.rsuser 274 | *- [Bb]ackup.rdl 275 | *- [Bb]ackup ([0-9]).rdl 276 | *- [Bb]ackup ([0-9][0-9]).rdl 277 | 278 | # Microsoft Fakes 279 | FakesAssemblies/ 280 | 281 | # GhostDoc plugin setting file 282 | *.GhostDoc.xml 283 | 284 | # Node.js Tools for Visual Studio 285 | .ntvs_analysis.dat 286 | node_modules/ 287 | 288 | # Visual Studio 6 build log 289 | *.plg 290 | 291 | # Visual Studio 6 workspace options file 292 | *.opt 293 | 294 | # Visual Studio 6 auto-generated workspace file (contains which files were open etc.) 295 | *.vbw 296 | 297 | # Visual Studio LightSwitch build output 298 | **/*.HTMLClient/GeneratedArtifacts 299 | **/*.DesktopClient/GeneratedArtifacts 300 | **/*.DesktopClient/ModelManifest.xml 301 | **/*.Server/GeneratedArtifacts 302 | **/*.Server/ModelManifest.xml 303 | _Pvt_Extensions 304 | 305 | # Paket dependency manager 306 | .paket/paket.exe 307 | paket-files/ 308 | 309 | # FAKE - F# Make 310 | .fake/ 311 | 312 | # CodeRush personal settings 313 | .cr/personal 314 | 315 | # Python Tools for Visual Studio (PTVS) 316 | __pycache__/ 317 | *.pyc 318 | 319 | # Cake - Uncomment if you are using it 320 | # tools/** 321 | # !tools/packages.config 322 | 323 | # Tabs Studio 324 | *.tss 325 | 326 | # Telerik's JustMock configuration file 327 | *.jmconfig 328 | 329 | # BizTalk build output 330 | *.btp.cs 331 | *.btm.cs 332 | *.odx.cs 333 | *.xsd.cs 334 | 335 | # OpenCover UI analysis results 336 | OpenCover/ 337 | 338 | # Azure Stream Analytics local run output 339 | ASALocalRun/ 340 | 341 | # MSBuild Binary and Structured Log 342 | *.binlog 343 | 344 | # NVidia Nsight GPU debugger configuration file 345 | *.nvuser 346 | 347 | # MFractors (Xamarin productivity tool) working folder 348 | .mfractor/ 349 | 350 | # Local History for Visual Studio 351 | .localhistory/ 352 | 353 | # BeatPulse healthcheck temp database 354 | healthchecksdb 355 | 356 | # Backup folder for Package Reference Convert tool in Visual Studio 2017 357 | MigrationBackup/ 358 | 359 | # Ionide (cross platform F# VS Code tools) working folder 360 | .ionide/ 361 | 362 | # Fody - auto-generated XML schema 363 | FodyWeavers.xsd -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2023 David 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /LoggingDecoratorGenerator.IntegrationTests/IDurationAsMetricTests.cs: -------------------------------------------------------------------------------- 1 | using FakeItEasy; 2 | using Fineboym.Logging.Attributes; 3 | using Microsoft.Extensions.DependencyInjection; 4 | using Microsoft.Extensions.Diagnostics.Metrics.Testing; 5 | using Microsoft.Extensions.Logging; 6 | using Microsoft.Extensions.Logging.Testing; 7 | using System.Diagnostics.Metrics; 8 | using System.Globalization; 9 | 10 | namespace LoggingDecoratorGenerator.IntegrationTests; 11 | 12 | [DecorateWithLogger(MeasureDuration = true, ReportDurationAsMetric = true)] 13 | public interface IDurationAsMetric 14 | { 15 | [LogMethod(Level = LogLevel.Information, EventId = 10, EventName = "MyName")] 16 | Task MethodMeasuresDurationAsync(DateTime myDateTimeParam); 17 | 18 | [LogMethod(MeasureDuration = false)] 19 | int MethodWithoutDuration(DateTime input); 20 | } 21 | 22 | public sealed class DurationAsMetricTests : IDisposable 23 | { 24 | private readonly ServiceProvider _serviceProvider; 25 | private readonly IMeterFactory _meterFactory; 26 | private readonly MetricCollector _metricCollector; 27 | 28 | private readonly FakeLogger _logger; 29 | private readonly FakeLogCollector _logCollector; 30 | private readonly IDurationAsMetric _fakeService; 31 | private readonly DurationAsMetricLoggingDecorator _decorator; 32 | 33 | public DurationAsMetricTests() 34 | { 35 | var serviceCollection = new ServiceCollection(); 36 | serviceCollection.AddMetrics(); 37 | _serviceProvider = serviceCollection.BuildServiceProvider(); 38 | _meterFactory = _serviceProvider.GetRequiredService(); 39 | 40 | _logCollector = new(); 41 | _logger = new(_logCollector); 42 | _fakeService = A.Fake(); 43 | _decorator = new DurationAsMetricLoggingDecorator(_logger, _fakeService, _meterFactory); 44 | 45 | _metricCollector = new MetricCollector( 46 | meterScope: _meterFactory, 47 | meterName: _fakeService.GetType().ToString(), 48 | instrumentName: "logging_decorator.method.duration"); 49 | } 50 | 51 | public void Dispose() => _serviceProvider.Dispose(); 52 | 53 | [Fact] 54 | public async Task WhenMethodMeasuresDuration_ReportsAsMetric() 55 | { 56 | // Arrange 57 | DateTime input = DateTime.UtcNow; 58 | int expectedReturnValue = Random.Shared.Next(); 59 | A.CallTo(() => _fakeService.MethodMeasuresDurationAsync(input)).Returns(expectedReturnValue); 60 | 61 | // Act 62 | int actualReturnValue = await _decorator.MethodMeasuresDurationAsync(input); 63 | 64 | // Assert 65 | Assert.Equal(expectedReturnValue, actualReturnValue); 66 | A.CallTo(() => _fakeService.MethodMeasuresDurationAsync(input)).MustHaveHappenedOnceExactly(); 67 | 68 | Assert.Equal(2, _logCollector.Count); 69 | 70 | IReadOnlyList writes = _logCollector.GetSnapshot(); 71 | 72 | FakeLogRecord firstWrite = writes[0]; 73 | Assert.Equal(10, firstWrite.Id.Id); 74 | Assert.Equal("MyName", firstWrite.Id.Name); 75 | Assert.Equal(LogLevel.Information, firstWrite.Level); 76 | Assert.Equal("LoggingDecoratorGenerator.IntegrationTests.IDurationAsMetric", firstWrite.Category); 77 | Assert.Equal($"Entering MethodMeasuresDurationAsync with parameters: myDateTimeParam = {input.ToString(DateTimeFormatInfo.InvariantInfo)}", firstWrite.Message); 78 | Assert.Null(firstWrite.Exception); 79 | Assert.Empty(firstWrite.Scopes); 80 | KeyValuePair[] expectedBeforeWriteState = new[] 81 | { 82 | new KeyValuePair("myDateTimeParam", input.ToString(DateTimeFormatInfo.InvariantInfo)), 83 | new KeyValuePair("{OriginalFormat}", "Entering MethodMeasuresDurationAsync with parameters: myDateTimeParam = {myDateTimeParam}"), 84 | }; 85 | Assert.Equivalent(expectedBeforeWriteState, firstWrite.StructuredState, strict: true); 86 | 87 | FakeLogRecord lastWrite = writes[1]; 88 | Assert.Equal(10, lastWrite.Id.Id); 89 | Assert.Equal("MyName", lastWrite.Id.Name); 90 | Assert.Equal(LogLevel.Information, lastWrite.Level); 91 | Assert.Equal("LoggingDecoratorGenerator.IntegrationTests.IDurationAsMetric", lastWrite.Category); 92 | Assert.Equal($"Method MethodMeasuresDurationAsync returned. Result = {expectedReturnValue}", lastWrite.Message); 93 | Assert.Null(lastWrite.Exception); 94 | Assert.Empty(lastWrite.Scopes); 95 | KeyValuePair[] expectedAfterWriteState = new[] 96 | { 97 | new KeyValuePair("result", expectedReturnValue), 98 | new KeyValuePair("{OriginalFormat}", "Method MethodMeasuresDurationAsync returned. Result = {result}"), 99 | }; 100 | Assert.Equivalent(expectedAfterWriteState, lastWrite.StructuredState, strict: true); 101 | 102 | Histogram histogram = Assert.IsType>(_metricCollector.Instrument); 103 | Assert.Equal("s", histogram.Unit); 104 | Assert.Equal("The duration of method invocations.", histogram.Description); 105 | Assert.Null(histogram.Tags); 106 | Assert.Null(histogram.Meter.Tags); 107 | Assert.Null(histogram.Meter.Version); 108 | 109 | IReadOnlyList> collectedMeasurements = _metricCollector.GetMeasurementSnapshot(); 110 | CollectedMeasurement singleMeasurement = Assert.Single(collectedMeasurements); 111 | Assert.InRange(singleMeasurement.Value, double.Epsilon, (lastWrite.Timestamp - firstWrite.Timestamp).TotalSeconds); 112 | bool tagsMatch = singleMeasurement.MatchesTags( 113 | new KeyValuePair("logging_decorator.method", nameof(IDurationAsMetric.MethodMeasuresDurationAsync))); 114 | Assert.True(tagsMatch); 115 | Assert.True(singleMeasurement.Timestamp > firstWrite.Timestamp && singleMeasurement.Timestamp < lastWrite.Timestamp); 116 | } 117 | 118 | [Fact] 119 | public void WhenMetricCollectionEnabled_MethodWithoutDuration_NoMetricIsReported() 120 | { 121 | // Arrange 122 | DateTime input = DateTime.UtcNow; 123 | int expectedReturnValue = Random.Shared.Next(); 124 | A.CallTo(() => _fakeService.MethodWithoutDuration(input)).Returns(expectedReturnValue); 125 | 126 | // Act 127 | int actualReturnValue = _decorator.MethodWithoutDuration(input); 128 | 129 | // Assert 130 | Assert.Equal(expectedReturnValue, actualReturnValue); 131 | A.CallTo(() => _fakeService.MethodWithoutDuration(input)).MustHaveHappenedOnceExactly(); 132 | 133 | Assert.Equal(2, _logCollector.Count); 134 | Histogram histogram = Assert.IsType>(_metricCollector.Instrument); 135 | Assert.Equal(_fakeService.GetType().ToString(), histogram.Meter.Name); 136 | Assert.Equal("logging_decorator.method.duration", histogram.Name); 137 | Assert.True(histogram.Enabled); 138 | Assert.Empty(_metricCollector.GetMeasurementSnapshot()); 139 | } 140 | 141 | [Fact] 142 | public async Task WhenTwoImplementationsOfSameInterface_ReportToDifferentMeters_DifferentInstruments() 143 | { 144 | // Arrange 145 | MetricCollector? firstCollector = null, secondCollector = null; 146 | using MeterListener meterListener = new(); 147 | meterListener.InstrumentPublished = (instrument, listener) => 148 | { 149 | Assert.Null(instrument.Meter.Tags); 150 | Assert.Null(instrument.Meter.Version); 151 | 152 | Histogram histogram = Assert.IsType>(instrument); 153 | Assert.Equal("s", histogram.Unit); 154 | Assert.Equal("The duration of method invocations.", histogram.Description); 155 | Assert.Null(histogram.Tags); 156 | 157 | if (instrument.Meter.Name == typeof(FirstImplementation).ToString()) 158 | { 159 | firstCollector = new MetricCollector(histogram); 160 | } 161 | else if (instrument.Meter.Name == typeof(SecondImplementation).ToString()) 162 | { 163 | secondCollector = new MetricCollector(histogram); 164 | } 165 | }; 166 | 167 | meterListener.Start(); 168 | 169 | var decorator1 = new DurationAsMetricLoggingDecorator(_logger, new FirstImplementation(), _meterFactory); 170 | var decorator2 = new DurationAsMetricLoggingDecorator(_logger, new SecondImplementation(), _meterFactory); 171 | 172 | // Act 173 | await decorator1.MethodMeasuresDurationAsync(DateTime.UtcNow); 174 | await decorator2.MethodMeasuresDurationAsync(DateTime.UtcNow); 175 | 176 | // Assert 177 | Assert.NotNull(firstCollector?.Instrument); 178 | Assert.NotNull(secondCollector?.Instrument); 179 | 180 | Assert.NotSame(firstCollector.Instrument.Meter, secondCollector.Instrument.Meter); 181 | Assert.NotSame(firstCollector.Instrument, secondCollector.Instrument); 182 | 183 | CollectedMeasurement firstImplementationMeasurement = Assert.Single(firstCollector.GetMeasurementSnapshot()); 184 | CollectedMeasurement secondImplementationMeasurement = Assert.Single(secondCollector.GetMeasurementSnapshot()); 185 | 186 | KeyValuePair firstImplementationTag = Assert.Single(firstImplementationMeasurement.Tags); 187 | KeyValuePair secondImplementationTag = Assert.Single(secondImplementationMeasurement.Tags); 188 | 189 | Assert.Equal(new KeyValuePair("logging_decorator.method", nameof(IDurationAsMetric.MethodMeasuresDurationAsync)), firstImplementationTag); 190 | Assert.Equal(firstImplementationTag, secondImplementationTag); 191 | } 192 | 193 | private class FirstImplementation : IDurationAsMetric 194 | { 195 | public Task MethodMeasuresDurationAsync(DateTime myDateTimeParam) 196 | { 197 | return Task.FromResult(1); 198 | } 199 | 200 | public int MethodWithoutDuration(DateTime input) 201 | { 202 | throw new NotImplementedException(); 203 | } 204 | } 205 | 206 | private class SecondImplementation : IDurationAsMetric 207 | { 208 | public Task MethodMeasuresDurationAsync(DateTime myDateTimeParam) 209 | { 210 | return Task.FromResult(2); 211 | } 212 | 213 | public int MethodWithoutDuration(DateTime input) 214 | { 215 | throw new NotImplementedException(); 216 | } 217 | } 218 | } -------------------------------------------------------------------------------- /LoggingDecoratorGenerator.IntegrationTests/IInformationLevelInterface.cs: -------------------------------------------------------------------------------- 1 | using Fineboym.Logging.Attributes; 2 | using Microsoft.Extensions.Logging; 3 | using OtherFolder.OtherSubFolder; 4 | 5 | namespace LoggingDecoratorGenerator.IntegrationTests 6 | { 7 | [DecorateWithLogger(LogLevel.Information)] 8 | public interface IInformationLevelInterface 9 | { 10 | ValueTask MethodWithoutAttribute(int x, int y); 11 | 12 | [LogMethod(Level = LogLevel.Debug, EventName = "SomePersonEventName", EventId = 100)] 13 | Person MethodWithAttribute(Person person, int someNumber); 14 | 15 | void MethodShouldNotBeLoggedBecauseOfLogLevel(); 16 | 17 | [LogMethod(MeasureDuration = true, ExceptionToLog = typeof(Exception), ExceptionLogLevel = LogLevel.Critical)] 18 | Task MethodWithMeasuredDurationAsync(DateOnly someDate); 19 | 20 | [LogMethod(ExceptionToLog = typeof(Exception), EventId = 777, MeasureDuration = true)] 21 | Task MethodThrowsAndLogsExceptionAsync(); 22 | } 23 | } 24 | 25 | namespace OtherFolder.OtherSubFolder 26 | { 27 | public record Person(string Name, int Age); 28 | } 29 | -------------------------------------------------------------------------------- /LoggingDecoratorGenerator.IntegrationTests/ISomeService.cs: -------------------------------------------------------------------------------- 1 | using Fineboym.Logging.Attributes; 2 | using Microsoft.Extensions.Logging; 3 | 4 | namespace LoggingDecoratorGenerator.IntegrationTests; 5 | 6 | [DecorateWithLogger] 7 | public interface ISomeService : IDisposable 8 | { 9 | DateTime DateTimeReturningMethod(DateTime someDateTime); 10 | 11 | [LogMethod(Level = LogLevel.Information, EventId = 0)] 12 | Task StringReturningAsyncMethod(string? s); 13 | 14 | [LogMethod(EventId = 222, EventName = "Parameterless")] 15 | void TwoMethodsWithSameName(); 16 | 17 | [LogMethod(EventId = 333, EventName = "WithIntegerParam")] 18 | void TwoMethodsWithSameName(int i); 19 | 20 | [return: NotLogged] 21 | string GetMySecretString(string username, [NotLogged] string password, int x); 22 | } -------------------------------------------------------------------------------- /LoggingDecoratorGenerator.IntegrationTests/InformationLevelInterfaceTests.cs: -------------------------------------------------------------------------------- 1 | using FakeItEasy; 2 | using Microsoft.Extensions.Logging; 3 | using Microsoft.Extensions.Logging.Testing; 4 | using OtherFolder.OtherSubFolder; 5 | using System.Globalization; 6 | 7 | namespace LoggingDecoratorGenerator.IntegrationTests; 8 | 9 | public class InformationLevelInterfaceTests 10 | { 11 | private readonly FakeLogCollector _collector; 12 | private readonly IInformationLevelInterface _fakeService; 13 | private readonly InformationLevelInterfaceLoggingDecorator _decorator; 14 | 15 | public InformationLevelInterfaceTests() 16 | { 17 | _collector = new(); 18 | FakeLogger logger = new(_collector); 19 | _fakeService = A.Fake(); 20 | _decorator = new InformationLevelInterfaceLoggingDecorator(logger, _fakeService); 21 | } 22 | 23 | [Fact] 24 | public async Task MethodWithoutAttribute() 25 | { 26 | // Arrange 27 | int x = 42; 28 | int y = 43; 29 | float expectedReturnValue = 42.43f; 30 | A.CallTo(() => _fakeService.MethodWithoutAttribute(x, y)).Returns(expectedReturnValue); 31 | 32 | // Act 33 | float actualReturn = await _decorator.MethodWithoutAttribute(x, y); 34 | 35 | // Assert 36 | Assert.Equal(expected: expectedReturnValue, actual: actualReturn); 37 | A.CallTo(() => _fakeService.MethodWithoutAttribute(x, y)).MustHaveHappenedOnceExactly(); 38 | 39 | Assert.Equal(2, _collector.Count); 40 | 41 | IReadOnlyList writes = _collector.GetSnapshot(); 42 | 43 | FakeLogRecord firstWrite = writes[0]; 44 | Assert.Equal(1514124652, firstWrite.Id.Id); 45 | Assert.Equal("MethodWithoutAttribute", firstWrite.Id.Name); 46 | Assert.Equal(LogLevel.Information, firstWrite.Level); 47 | Assert.Equal("LoggingDecoratorGenerator.IntegrationTests.IInformationLevelInterface", firstWrite.Category); 48 | Assert.Equal("Entering MethodWithoutAttribute with parameters: x = 42, y = 43", firstWrite.Message); 49 | Assert.Null(firstWrite.Exception); 50 | Assert.Empty(firstWrite.Scopes); 51 | KeyValuePair[] expectedBeforeWriteState = new[] 52 | { 53 | new KeyValuePair("x", x), 54 | new KeyValuePair("y", y), 55 | new KeyValuePair("{OriginalFormat}", "Entering MethodWithoutAttribute with parameters: x = {x}, y = {y}"), 56 | }; 57 | Assert.Equivalent(expectedBeforeWriteState, firstWrite.StructuredState, strict: true); 58 | 59 | FakeLogRecord lastWrite = writes[1]; 60 | Assert.Equal(1514124652, lastWrite.Id.Id); 61 | Assert.Equal("MethodWithoutAttribute", lastWrite.Id.Name); 62 | Assert.Equal(LogLevel.Information, lastWrite.Level); 63 | Assert.Equal("LoggingDecoratorGenerator.IntegrationTests.IInformationLevelInterface", lastWrite.Category); 64 | Assert.Equal("Method MethodWithoutAttribute returned. Result = 42.43", lastWrite.Message); 65 | Assert.Null(lastWrite.Exception); 66 | Assert.Empty(lastWrite.Scopes); 67 | KeyValuePair[] expectedAfterWriteState = new[] 68 | { 69 | new KeyValuePair("result", expectedReturnValue), 70 | new KeyValuePair("{OriginalFormat}", "Method MethodWithoutAttribute returned. Result = {result}"), 71 | }; 72 | Assert.Equivalent(expectedAfterWriteState, lastWrite.StructuredState, strict: true); 73 | } 74 | 75 | [Fact] 76 | public void MethodWithAttribute() 77 | { 78 | // Arrange 79 | Person firstInput = new("foo", 30); 80 | int secondInput = 33; 81 | Person expectedReturnValue = new("bar", 42); 82 | A.CallTo(() => _fakeService.MethodWithAttribute(firstInput, secondInput)).Returns(expectedReturnValue); 83 | 84 | // Act 85 | Person actualReturn = _decorator.MethodWithAttribute(firstInput, secondInput); 86 | 87 | // Assert 88 | Assert.Equal(expected: expectedReturnValue, actual: actualReturn); 89 | A.CallTo(() => _fakeService.MethodWithAttribute(firstInput, secondInput)).MustHaveHappenedOnceExactly(); 90 | 91 | Assert.Equal(2, _collector.Count); 92 | 93 | IReadOnlyList writes = _collector.GetSnapshot(); 94 | 95 | var firstWrite = writes[0]; 96 | Assert.Equal(100, firstWrite.Id.Id); 97 | Assert.Equal("SomePersonEventName", firstWrite.Id.Name); 98 | Assert.Equal(LogLevel.Debug, firstWrite.Level); 99 | Assert.Equal("LoggingDecoratorGenerator.IntegrationTests.IInformationLevelInterface", firstWrite.Category); 100 | Assert.Equal("Entering MethodWithAttribute with parameters: person = Person { Name = foo, Age = 30 }, someNumber = 33", firstWrite.Message); 101 | Assert.Null(firstWrite.Exception); 102 | Assert.Empty(firstWrite.Scopes); 103 | KeyValuePair[] expectedBeforeWriteState = new[] 104 | { 105 | new KeyValuePair("person", firstInput.ToString()), 106 | new KeyValuePair("someNumber", secondInput.ToString()), 107 | new KeyValuePair("{OriginalFormat}", "Entering MethodWithAttribute with parameters: person = {person}, someNumber = {someNumber}"), 108 | }; 109 | Assert.Equivalent(expectedBeforeWriteState, firstWrite.StructuredState, strict: true); 110 | 111 | var lastWrite = writes[1]; 112 | Assert.Equal(100, lastWrite.Id.Id); 113 | Assert.Equal("SomePersonEventName", lastWrite.Id.Name); 114 | Assert.Equal(LogLevel.Debug, lastWrite.Level); 115 | Assert.Equal("LoggingDecoratorGenerator.IntegrationTests.IInformationLevelInterface", lastWrite.Category); 116 | Assert.Equal("Method MethodWithAttribute returned. Result = Person { Name = bar, Age = 42 }", lastWrite.Message); 117 | Assert.Null(lastWrite.Exception); 118 | Assert.Empty(lastWrite.Scopes); 119 | KeyValuePair[] expectedAfterWriteState = new[] 120 | { 121 | new KeyValuePair("result", expectedReturnValue.ToString()), 122 | new KeyValuePair("{OriginalFormat}", "Method MethodWithAttribute returned. Result = {result}"), 123 | }; 124 | Assert.Equivalent(expectedAfterWriteState, lastWrite.StructuredState, strict: true); 125 | } 126 | 127 | [Fact] 128 | public void MethodShouldNotBeLoggedBecauseOfLogLevel() 129 | { 130 | // Arrange 131 | ILogger fakeLogger = A.Fake>(); 132 | var decorator = new InformationLevelInterfaceLoggingDecorator(fakeLogger, _fakeService); 133 | A.CallTo(() => fakeLogger.IsEnabled(LogLevel.Information)).Returns(false); 134 | A.CallTo(() => _fakeService.MethodShouldNotBeLoggedBecauseOfLogLevel()).DoesNothing(); 135 | 136 | // Act 137 | decorator.MethodShouldNotBeLoggedBecauseOfLogLevel(); 138 | 139 | // Assert 140 | A.CallTo(() => _fakeService.MethodShouldNotBeLoggedBecauseOfLogLevel()).MustHaveHappenedOnceExactly(); 141 | A.CallTo(() => fakeLogger.IsEnabled(LogLevel.Information)).MustHaveHappenedOnceExactly(); 142 | A.CallTo(fakeLogger).Where(call => call.Method.Name == nameof(ILogger.Log)).MustNotHaveHappened(); 143 | } 144 | 145 | [Fact] 146 | public async Task MethodWithMeasuredDurationAsync() 147 | { 148 | // Arrange 149 | DateOnly inputParam = DateOnly.FromDayNumber(1_000); 150 | Person expectedReturnValue = new("bar", 42); 151 | A.CallTo(() => _fakeService.MethodWithMeasuredDurationAsync(inputParam)).Returns(expectedReturnValue); 152 | 153 | // Act 154 | Person actualReturn = await _decorator.MethodWithMeasuredDurationAsync(inputParam); 155 | 156 | // Assert 157 | Assert.Equal(expected: expectedReturnValue, actual: actualReturn); 158 | A.CallTo(() => _fakeService.MethodWithMeasuredDurationAsync(inputParam)).MustHaveHappenedOnceExactly(); 159 | 160 | Assert.Equal(2, _collector.Count); 161 | 162 | IReadOnlyList writes = _collector.GetSnapshot(); 163 | 164 | var firstWrite = writes[0]; 165 | Assert.Equal(1711224704, firstWrite.Id.Id); 166 | Assert.Equal("MethodWithMeasuredDurationAsync", firstWrite.Id.Name); 167 | Assert.Equal(LogLevel.Information, firstWrite.Level); 168 | Assert.Equal("LoggingDecoratorGenerator.IntegrationTests.IInformationLevelInterface", firstWrite.Category); 169 | Assert.Equal("Entering MethodWithMeasuredDurationAsync with parameters: someDate = 09/28/0003", firstWrite.Message); 170 | Assert.Null(firstWrite.Exception); 171 | Assert.Empty(firstWrite.Scopes); 172 | KeyValuePair[] expectedBeforeWriteState = new[] 173 | { 174 | new KeyValuePair("someDate", inputParam.ToString(DateTimeFormatInfo.InvariantInfo)), 175 | new KeyValuePair("{OriginalFormat}", "Entering MethodWithMeasuredDurationAsync with parameters: someDate = {someDate}"), 176 | }; 177 | Assert.Equivalent(expectedBeforeWriteState, firstWrite.StructuredState, strict: true); 178 | 179 | var lastWrite = writes[1]; 180 | Assert.Equal(1711224704, lastWrite.Id.Id); 181 | Assert.Equal("MethodWithMeasuredDurationAsync", lastWrite.Id.Name); 182 | Assert.Equal(LogLevel.Information, lastWrite.Level); 183 | Assert.Equal("LoggingDecoratorGenerator.IntegrationTests.IInformationLevelInterface", lastWrite.Category); 184 | Assert.Null(lastWrite.Exception); 185 | Assert.Empty(lastWrite.Scopes); 186 | var afterWriteState = lastWrite.StructuredState; 187 | KeyValuePair[] expectedAfterWriteState = new[] 188 | { 189 | new KeyValuePair("result", expectedReturnValue.ToString()), 190 | new KeyValuePair("{OriginalFormat}", "Method MethodWithMeasuredDurationAsync returned. Result = {result}. DurationInMilliseconds = {durationInMilliseconds}"), 191 | }; 192 | Assert.Equivalent(expectedAfterWriteState, afterWriteState); 193 | string? durationString = afterWriteState!.SingleOrDefault(kvp => kvp.Key == "durationInMilliseconds").Value; 194 | Assert.True(double.TryParse(durationString, out double duration)); 195 | Assert.Equal($"Method MethodWithMeasuredDurationAsync returned. Result = Person {{ Name = bar, Age = 42 }}. DurationInMilliseconds = {duration}", lastWrite.Message); 196 | Assert.InRange(duration, double.Epsilon, lastWrite.Timestamp.Subtract(firstWrite.Timestamp).TotalMilliseconds); 197 | } 198 | 199 | [Fact] 200 | public async Task MethodThrowsAndLogsExceptionAsync() 201 | { 202 | // Arrange 203 | InvalidOperationException expectedException = new("someMessage"); 204 | A.CallTo(() => _fakeService.MethodThrowsAndLogsExceptionAsync()).ThrowsAsync(expectedException); 205 | 206 | // Act and Assert 207 | InvalidOperationException actualException = await Assert.ThrowsAsync(() => _decorator.MethodThrowsAndLogsExceptionAsync()); 208 | Assert.Equal(expectedException, actualException); 209 | A.CallTo(() => _fakeService.MethodThrowsAndLogsExceptionAsync()).MustHaveHappenedOnceExactly(); 210 | 211 | Assert.Equal(2, _collector.Count); 212 | 213 | IReadOnlyList writes = _collector.GetSnapshot(); 214 | 215 | var firstWrite = writes[0]; 216 | Assert.Equal(777, firstWrite.Id.Id); 217 | Assert.Equal("MethodThrowsAndLogsExceptionAsync", firstWrite.Id.Name); 218 | Assert.Equal(LogLevel.Information, firstWrite.Level); 219 | Assert.Equal("LoggingDecoratorGenerator.IntegrationTests.IInformationLevelInterface", firstWrite.Category); 220 | Assert.Equal("Entering MethodThrowsAndLogsExceptionAsync", firstWrite.Message); 221 | Assert.Null(firstWrite.Exception); 222 | Assert.Empty(firstWrite.Scopes); 223 | KeyValuePair[] expectedBeforeWriteState = new[] 224 | { 225 | new KeyValuePair("{OriginalFormat}", "Entering MethodThrowsAndLogsExceptionAsync"), 226 | }; 227 | Assert.Equivalent(expectedBeforeWriteState, firstWrite.StructuredState, strict: true); 228 | 229 | var lastWrite = writes[1]; 230 | Assert.Equal(777, lastWrite.Id.Id); 231 | Assert.Equal("MethodThrowsAndLogsExceptionAsync", lastWrite.Id.Name); 232 | Assert.Equal(LogLevel.Error, lastWrite.Level); 233 | Assert.Equal("LoggingDecoratorGenerator.IntegrationTests.IInformationLevelInterface", lastWrite.Category); 234 | Assert.Equal("MethodThrowsAndLogsExceptionAsync failed", lastWrite.Message); 235 | Assert.Equal(expectedException, lastWrite.Exception); 236 | Assert.Empty(lastWrite.Scopes); 237 | KeyValuePair[] expectedAfterWriteState = new[] 238 | { 239 | new KeyValuePair("{OriginalFormat}", "MethodThrowsAndLogsExceptionAsync failed"), 240 | }; 241 | Assert.Equivalent(expectedAfterWriteState, lastWrite.StructuredState, strict: true); 242 | } 243 | } -------------------------------------------------------------------------------- /LoggingDecoratorGenerator.IntegrationTests/LoggingDecoratorGenerator.IntegrationTests.csproj: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | net6.0;net7.0;net8.0 5 | enable 6 | enable 7 | false 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | runtime; build; native; contentfiles; analyzers; buildtransitive 18 | all 19 | 20 | 21 | runtime; build; native; contentfiles; analyzers; buildtransitive 22 | all 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | -------------------------------------------------------------------------------- /LoggingDecoratorGenerator.IntegrationTests/PolymorphicInterfaces.cs: -------------------------------------------------------------------------------- 1 | using Fineboym.Logging.Attributes; 2 | 3 | namespace LoggingDecoratorGenerator.IntegrationTests 4 | { 5 | public interface IBaseInterfaceWithoutAttribute 6 | { 7 | Task PassThroughMethodAsync(int x, int y); 8 | 9 | [LogMethod(Level = Microsoft.Extensions.Logging.LogLevel.Trace, EventId = 7, ExceptionToLog = typeof(InvalidOperationException))] 10 | Task MethodWithAttributeAsync(float num, [NotLogged] string secret); 11 | } 12 | 13 | [DecorateWithLogger()] 14 | public interface IBaseInterfaceWithAttribute : IBaseInterfaceWithoutAttribute 15 | { 16 | TimeOnly MethodWithoutAttribute(DateOnly someDate); 17 | } 18 | 19 | [DecorateWithLogger(level: Microsoft.Extensions.Logging.LogLevel.Information)] 20 | public interface IDerivedInterface : IBaseInterfaceWithAttribute 21 | { 22 | ValueTask DerivedMethodAsync(int x); 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /LoggingDecoratorGenerator.IntegrationTests/PolymorphicInterfacesTests.cs: -------------------------------------------------------------------------------- 1 | using FakeItEasy; 2 | using Microsoft.Extensions.Logging; 3 | using Microsoft.Extensions.Logging.Testing; 4 | 5 | namespace LoggingDecoratorGenerator.IntegrationTests; 6 | 7 | public class PolymorphicInterfacesTests 8 | { 9 | private readonly FakeLogCollector _collector; 10 | private readonly IDerivedInterface _fakeService; 11 | private readonly DerivedInterfaceLoggingDecorator _decorator; 12 | 13 | public PolymorphicInterfacesTests() 14 | { 15 | _collector = new(); 16 | FakeLogger logger = new(_collector); 17 | _fakeService = A.Fake(); 18 | _decorator = new DerivedInterfaceLoggingDecorator(logger, _fakeService); 19 | } 20 | 21 | [Fact] 22 | public async Task PassThroughMethodAsync() 23 | { 24 | // Arrange 25 | const int x = 1; 26 | const int y = 2; 27 | const int expectedResult = 3; 28 | ILogger fakeLogger = A.Fake>(); 29 | var decorator = new DerivedInterfaceLoggingDecorator(fakeLogger, _fakeService); 30 | A.CallTo(() => _fakeService.PassThroughMethodAsync(x, y)).Returns(expectedResult); 31 | 32 | // Act 33 | int result = await decorator.PassThroughMethodAsync(x, y); 34 | 35 | // Assert 36 | Assert.Equal(expectedResult, result); 37 | A.CallTo(() => _fakeService.PassThroughMethodAsync(x, y)).MustHaveHappenedOnceExactly(); 38 | A.CallTo(fakeLogger).MustNotHaveHappened(); 39 | } 40 | 41 | [Fact] 42 | public async Task MethodWithAttributeAsync() 43 | { 44 | // Arrange 45 | const float num = 42.3f; 46 | const string secret = "bar"; 47 | const string expectedReturnValue = "returnValue"; 48 | A.CallTo(() => _fakeService.MethodWithAttributeAsync(num, secret)).Returns(expectedReturnValue); 49 | 50 | // Act 51 | string actualReturn = await _decorator.MethodWithAttributeAsync(num, secret); 52 | 53 | // Assert 54 | Assert.Equal(expected: expectedReturnValue, actual: actualReturn); 55 | A.CallTo(() => _fakeService.MethodWithAttributeAsync(num, secret)).MustHaveHappenedOnceExactly(); 56 | 57 | Assert.Equal(2, _collector.Count); 58 | 59 | IReadOnlyList writes = _collector.GetSnapshot(); 60 | 61 | FakeLogRecord firstWrite = writes[0]; 62 | Assert.Equal(7, firstWrite.Id.Id); 63 | Assert.Equal("MethodWithAttributeAsync", firstWrite.Id.Name); 64 | Assert.Equal(LogLevel.Trace, firstWrite.Level); 65 | Assert.Equal("LoggingDecoratorGenerator.IntegrationTests.IDerivedInterface", firstWrite.Category); 66 | Assert.Equal("Entering MethodWithAttributeAsync with parameters: num = 42.3, secret = [REDACTED]", firstWrite.Message); 67 | Assert.Null(firstWrite.Exception); 68 | Assert.Empty(firstWrite.Scopes); 69 | KeyValuePair[] expectedBeforeWriteState = new[] 70 | { 71 | new KeyValuePair("num", num), 72 | new KeyValuePair("{OriginalFormat}", "Entering MethodWithAttributeAsync with parameters: num = {num}, secret = [REDACTED]"), 73 | }; 74 | Assert.Equivalent(expectedBeforeWriteState, firstWrite.StructuredState, strict: true); 75 | 76 | FakeLogRecord lastWrite = writes[1]; 77 | Assert.Equal(7, lastWrite.Id.Id); 78 | Assert.Equal("MethodWithAttributeAsync", lastWrite.Id.Name); 79 | Assert.Equal(LogLevel.Trace, lastWrite.Level); 80 | Assert.Equal("LoggingDecoratorGenerator.IntegrationTests.IDerivedInterface", lastWrite.Category); 81 | Assert.Equal("Method MethodWithAttributeAsync returned. Result = returnValue", lastWrite.Message); 82 | Assert.Null(lastWrite.Exception); 83 | Assert.Empty(firstWrite.Scopes); 84 | KeyValuePair[] expectedAfterWriteState = new[] 85 | { 86 | new KeyValuePair("result", expectedReturnValue), 87 | new KeyValuePair("{OriginalFormat}", "Method MethodWithAttributeAsync returned. Result = {result}") 88 | }; 89 | Assert.Equivalent(expectedAfterWriteState, lastWrite.StructuredState, strict: true); 90 | } 91 | } 92 | -------------------------------------------------------------------------------- /LoggingDecoratorGenerator.IntegrationTests/SomeServiceTests.cs: -------------------------------------------------------------------------------- 1 | using FakeItEasy; 2 | using Microsoft.Extensions.Logging; 3 | using Microsoft.Extensions.Logging.Testing; 4 | using System.Globalization; 5 | 6 | namespace LoggingDecoratorGenerator.IntegrationTests; 7 | 8 | public class SomeServiceTests 9 | { 10 | private readonly FakeLogCollector _collector; 11 | private readonly ISomeService _fakeService; 12 | private readonly SomeServiceLoggingDecorator _decorator; 13 | 14 | public SomeServiceTests() 15 | { 16 | _collector = new(); 17 | FakeLogger logger = new(_collector); 18 | _fakeService = A.Fake(); 19 | _decorator = new SomeServiceLoggingDecorator(logger, _fakeService); 20 | } 21 | 22 | [Fact] 23 | public void PassThroughMethodDoesNotCallLogger() 24 | { 25 | // Arrange 26 | ILogger fakeLogger = A.Fake>(); 27 | var decorator = new SomeServiceLoggingDecorator(fakeLogger, _fakeService); 28 | A.CallTo(() => _fakeService.Dispose()).DoesNothing(); 29 | 30 | // Act 31 | decorator.Dispose(); 32 | 33 | // Assert 34 | A.CallTo(() => _fakeService.Dispose()).MustHaveHappenedOnceExactly(); 35 | A.CallTo(fakeLogger).MustNotHaveHappened(); 36 | } 37 | 38 | [Fact] 39 | public void SynchronousMethod_DecoratorLogsAndCallsDecoratedInstance() 40 | { 41 | // Arrange 42 | DateTime dateTimeParameter = new(year: 2022, month: 12, day: 12, hour: 22, minute: 57, second: 45, DateTimeKind.Utc); 43 | DateTime expectedReturnValue = new(year: 2020, month: 09, day: 06, hour: 00, minute: 00, second: 00, DateTimeKind.Utc); 44 | A.CallTo(() => _fakeService.DateTimeReturningMethod(dateTimeParameter)).Returns(expectedReturnValue); 45 | 46 | // Act 47 | DateTime actualReturn = _decorator.DateTimeReturningMethod(dateTimeParameter); 48 | 49 | // Assert 50 | Assert.Equal(expectedReturnValue, actualReturn); 51 | A.CallTo(() => _fakeService.DateTimeReturningMethod(dateTimeParameter)).MustHaveHappenedOnceExactly(); 52 | 53 | Assert.Equal(2, _collector.Count); 54 | 55 | IReadOnlyList writes = _collector.GetSnapshot(); 56 | 57 | FakeLogRecord firstWrite = writes[0]; 58 | Assert.Equal(963397959, firstWrite.Id.Id); 59 | Assert.Equal("DateTimeReturningMethod", firstWrite.Id.Name); 60 | Assert.Equal(LogLevel.Debug, firstWrite.Level); 61 | Assert.Equal("LoggingDecoratorGenerator.IntegrationTests.ISomeService", firstWrite.Category); 62 | Assert.Equal("Entering DateTimeReturningMethod with parameters: someDateTime = 12/12/2022 22:57:45", firstWrite.Message); 63 | Assert.Null(firstWrite.Exception); 64 | Assert.Empty(firstWrite.Scopes); 65 | KeyValuePair[] expectedBeforeWriteState = new[] 66 | { 67 | new KeyValuePair("someDateTime", dateTimeParameter.ToString(DateTimeFormatInfo.InvariantInfo)), 68 | new KeyValuePair("{OriginalFormat}", "Entering DateTimeReturningMethod with parameters: someDateTime = {someDateTime}"), 69 | }; 70 | Assert.Equivalent(expectedBeforeWriteState, firstWrite.StructuredState, strict: true); 71 | 72 | FakeLogRecord lastWrite = writes[1]; 73 | Assert.Equal(963397959, lastWrite.Id.Id); 74 | Assert.Equal("DateTimeReturningMethod", lastWrite.Id.Name); 75 | Assert.Equal(LogLevel.Debug, lastWrite.Level); 76 | Assert.Equal("LoggingDecoratorGenerator.IntegrationTests.ISomeService", lastWrite.Category); 77 | Assert.Equal("Method DateTimeReturningMethod returned. Result = 09/06/2020 00:00:00", lastWrite.Message); 78 | Assert.Null(lastWrite.Exception); 79 | Assert.Empty(firstWrite.Scopes); 80 | KeyValuePair[] expectedAfterWriteState = new[] 81 | { 82 | new KeyValuePair("result", expectedReturnValue.ToString(DateTimeFormatInfo.InvariantInfo)), 83 | new KeyValuePair("{OriginalFormat}", "Method DateTimeReturningMethod returned. Result = {result}"), 84 | }; 85 | Assert.Equivalent(expectedAfterWriteState, lastWrite.StructuredState, strict: true); 86 | } 87 | 88 | [Fact] 89 | public void ParameterAndReturnValuesNotLogged() 90 | { 91 | // Arrange 92 | string username = "foo"; 93 | string password = "bar"; 94 | string expectedReturnValue = "returnValue"; 95 | int x = 42; 96 | A.CallTo(() => _fakeService.GetMySecretString(username, password, x)).Returns(expectedReturnValue); 97 | 98 | // Act 99 | string actualReturn = _decorator.GetMySecretString(username, password, x); 100 | 101 | // Assert 102 | Assert.Equal(expected: expectedReturnValue, actual: actualReturn); 103 | A.CallTo(() => _fakeService.GetMySecretString(username, password, x)).MustHaveHappenedOnceExactly(); 104 | 105 | Assert.Equal(2, _collector.Count); 106 | 107 | IReadOnlyList writes = _collector.GetSnapshot(); 108 | 109 | FakeLogRecord firstWrite = writes[0]; 110 | Assert.Equal(1921103492, firstWrite.Id.Id); 111 | Assert.Equal("GetMySecretString", firstWrite.Id.Name); 112 | Assert.Equal(LogLevel.Debug, firstWrite.Level); 113 | Assert.Equal("LoggingDecoratorGenerator.IntegrationTests.ISomeService", firstWrite.Category); 114 | Assert.Equal("Entering GetMySecretString with parameters: username = foo, password = [REDACTED], x = 42", firstWrite.Message); 115 | Assert.Null(firstWrite.Exception); 116 | Assert.Empty(firstWrite.Scopes); 117 | KeyValuePair[] expectedBeforeWriteState = new[] 118 | { 119 | new KeyValuePair("username", username), 120 | new KeyValuePair("x", x), 121 | new KeyValuePair("{OriginalFormat}", "Entering GetMySecretString with parameters: username = {username}, password = [REDACTED], x = {x}"), 122 | }; 123 | Assert.Equivalent(expectedBeforeWriteState, firstWrite.StructuredState, strict: true); 124 | 125 | FakeLogRecord lastWrite = writes[1]; 126 | Assert.Equal(1921103492, lastWrite.Id.Id); 127 | Assert.Equal("GetMySecretString", lastWrite.Id.Name); 128 | Assert.Equal(LogLevel.Debug, lastWrite.Level); 129 | Assert.Equal("LoggingDecoratorGenerator.IntegrationTests.ISomeService", lastWrite.Category); 130 | Assert.Equal("Method GetMySecretString returned. Result = [REDACTED]", lastWrite.Message); 131 | Assert.Null(lastWrite.Exception); 132 | Assert.Empty(firstWrite.Scopes); 133 | KeyValuePair[] expectedAfterWriteState = new[] 134 | { 135 | new KeyValuePair("{OriginalFormat}", "Method GetMySecretString returned. Result = [REDACTED]") 136 | }; 137 | Assert.Equivalent(expectedAfterWriteState, lastWrite.StructuredState, strict: true); 138 | } 139 | 140 | [Fact] 141 | public async Task AsynchronousMethod_DecoratorLogsAndCallsDecoratedInstance() 142 | { 143 | // Arrange 144 | string inputParameter = "SomeInputParameter"; 145 | string expectedReturnValue = "SomeReturnValue"; 146 | A.CallTo(() => _fakeService.StringReturningAsyncMethod(inputParameter)).Returns(expectedReturnValue); 147 | 148 | // Act 149 | string? actualReturn = await _decorator.StringReturningAsyncMethod(inputParameter); 150 | 151 | // Assert 152 | Assert.Equal(expected: expectedReturnValue, actual: actualReturn); 153 | A.CallTo(() => _fakeService.StringReturningAsyncMethod(inputParameter)).MustHaveHappenedOnceExactly(); 154 | 155 | Assert.Equal(2, _collector.Count); 156 | 157 | IReadOnlyList writes = _collector.GetSnapshot(); 158 | 159 | FakeLogRecord firstWrite = writes[0]; 160 | Assert.Equal(0, firstWrite.Id.Id); 161 | Assert.Equal("StringReturningAsyncMethod", firstWrite.Id.Name); 162 | Assert.Equal(LogLevel.Information, firstWrite.Level); 163 | Assert.Equal("LoggingDecoratorGenerator.IntegrationTests.ISomeService", firstWrite.Category); 164 | Assert.Equal("Entering StringReturningAsyncMethod with parameters: s = SomeInputParameter", firstWrite.Message); 165 | Assert.Null(firstWrite.Exception); 166 | Assert.Empty(firstWrite.Scopes); 167 | KeyValuePair[] expectedBeforeWriteState = new[] 168 | { 169 | new KeyValuePair("s", inputParameter), 170 | new KeyValuePair("{OriginalFormat}", "Entering StringReturningAsyncMethod with parameters: s = {s}"), 171 | }; 172 | Assert.Equivalent(expectedBeforeWriteState, firstWrite.StructuredState, strict: true); 173 | 174 | FakeLogRecord lastWrite = writes[1]; 175 | Assert.Equal(0, lastWrite.Id.Id); 176 | Assert.Equal("StringReturningAsyncMethod", lastWrite.Id.Name); 177 | Assert.Equal(LogLevel.Information, lastWrite.Level); 178 | Assert.Equal("LoggingDecoratorGenerator.IntegrationTests.ISomeService", lastWrite.Category); 179 | Assert.Equal("Method StringReturningAsyncMethod returned. Result = SomeReturnValue", lastWrite.Message); 180 | Assert.Null(lastWrite.Exception); 181 | Assert.Empty(firstWrite.Scopes); 182 | KeyValuePair[] expectedAfterWriteState = new[] 183 | { 184 | new KeyValuePair("result", expectedReturnValue), 185 | new KeyValuePair("{OriginalFormat}", "Method StringReturningAsyncMethod returned. Result = {result}"), 186 | }; 187 | Assert.Equivalent(expectedAfterWriteState, lastWrite.StructuredState, strict: true); 188 | } 189 | 190 | [Fact] 191 | public void TwoMethodsWithSameName_WithIntegerParameter() 192 | { 193 | // Arrange 194 | int inputParameter = 42; 195 | A.CallTo(() => _fakeService.TwoMethodsWithSameName(inputParameter)).DoesNothing(); 196 | 197 | // Act 198 | _decorator.TwoMethodsWithSameName(inputParameter); 199 | 200 | // Assert 201 | A.CallTo(() => _fakeService.TwoMethodsWithSameName(inputParameter)).MustHaveHappenedOnceExactly(); 202 | 203 | Assert.Equal(2, _collector.Count); 204 | 205 | IReadOnlyList writes = _collector.GetSnapshot(); 206 | 207 | FakeLogRecord firstWrite = writes[0]; 208 | Assert.Equal(333, firstWrite.Id.Id); 209 | Assert.Equal("WithIntegerParam", firstWrite.Id.Name); 210 | Assert.Equal(LogLevel.Debug, firstWrite.Level); 211 | Assert.Equal("LoggingDecoratorGenerator.IntegrationTests.ISomeService", firstWrite.Category); 212 | Assert.Equal("Entering TwoMethodsWithSameName with parameters: i = 42", firstWrite.Message); 213 | Assert.Null(firstWrite.Exception); 214 | Assert.Empty(firstWrite.Scopes); 215 | KeyValuePair[] expectedBeforeWriteState = new[] 216 | { 217 | new KeyValuePair("i", inputParameter), 218 | new KeyValuePair("{OriginalFormat}", "Entering TwoMethodsWithSameName with parameters: i = {i}"), 219 | }; 220 | Assert.Equivalent(expectedBeforeWriteState, firstWrite.StructuredState, strict: true); 221 | 222 | FakeLogRecord lastWrite = writes[1]; 223 | Assert.Equal(333, lastWrite.Id.Id); 224 | Assert.Equal("WithIntegerParam", lastWrite.Id.Name); 225 | Assert.Equal(LogLevel.Debug, lastWrite.Level); 226 | Assert.Equal("LoggingDecoratorGenerator.IntegrationTests.ISomeService", lastWrite.Category); 227 | Assert.Equal("Method TwoMethodsWithSameName returned", lastWrite.Message); 228 | Assert.Null(lastWrite.Exception); 229 | Assert.Empty(firstWrite.Scopes); 230 | KeyValuePair[] expectedAfterWriteState = new[] 231 | { 232 | new KeyValuePair("{OriginalFormat}", "Method TwoMethodsWithSameName returned"), 233 | }; 234 | Assert.Equivalent(expectedAfterWriteState, lastWrite.StructuredState, strict: true); 235 | } 236 | } 237 | -------------------------------------------------------------------------------- /LoggingDecoratorGenerator.IntegrationTests/Usings.cs: -------------------------------------------------------------------------------- 1 | global using Xunit; -------------------------------------------------------------------------------- /LoggingDecoratorGenerator.Tests/GeneratorSnapshotTests.GeneratesCorrectly#DecorateWithLoggerAttribute.g.verified.cs: -------------------------------------------------------------------------------- 1 | //HintName: DecorateWithLoggerAttribute.g.cs 2 | #nullable enable 3 | namespace Fineboym.Logging.Attributes 4 | { 5 | [System.AttributeUsage(System.AttributeTargets.Interface, AllowMultiple = false, Inherited = false)] 6 | internal sealed class DecorateWithLoggerAttribute : System.Attribute 7 | { 8 | public Microsoft.Extensions.Logging.LogLevel Level { get; } 9 | 10 | /// 11 | /// Surrounds all method calls by , default is . 12 | /// Can be overridden for each method by . 13 | /// If is , then duration in milliseconds is included in the log message about method's return, otherwise separately as a metric in seconds. 14 | /// 15 | public bool MeasureDuration { get; set; } 16 | 17 | /// 18 | /// If a method measures duration and this is set to , then the decorator will report the durations of method invocations as a metric using the System.Diagnostics.Metrics APIs. 19 | /// If , the durations won't be reported in log messages and decorator class will require in its constructor. 20 | /// It's available by targeting .NET 6+, or in older .NET Core and .NET Framework apps by adding a reference to the .NET System.Diagnostics.DiagnosticsSource 6.0+ NuGet package. 21 | /// For more info, see ASP.NET Core metrics, 22 | /// .NET observability with OpenTelemetry, 23 | /// Collect metrics. 24 | /// 25 | public bool ReportDurationAsMetric { get; set; } 26 | 27 | public DecorateWithLoggerAttribute(Microsoft.Extensions.Logging.LogLevel level = Microsoft.Extensions.Logging.LogLevel.Debug) 28 | { 29 | Level = level; 30 | } 31 | } 32 | } -------------------------------------------------------------------------------- /LoggingDecoratorGenerator.Tests/GeneratorSnapshotTests.GeneratesCorrectly#LogMethodAttribute.g.verified.cs: -------------------------------------------------------------------------------- 1 | //HintName: LogMethodAttribute.g.cs 2 | #nullable enable 3 | namespace Fineboym.Logging.Attributes 4 | { 5 | [System.AttributeUsage(System.AttributeTargets.Method, AllowMultiple = false, Inherited = true)] 6 | internal sealed class LogMethodAttribute : System.Attribute 7 | { 8 | public Microsoft.Extensions.Logging.LogLevel Level { get; set; } = Microsoft.Extensions.Logging.LogLevel.None; 9 | 10 | /// 11 | /// Gets the logging event id for the logging method. 12 | /// 13 | public int EventId { get; set; } = -1; 14 | 15 | /// 16 | /// Gets or sets the logging event name for the logging method. 17 | /// 18 | /// 19 | /// This will equal the method name if not specified. 20 | /// 21 | public string? EventName { get; set; } 22 | 23 | /// 24 | /// Surrounds the method call by , default is . 25 | /// If is , then duration in milliseconds is included in the log message about method's return, otherwise separately as a metric in seconds. 26 | /// 27 | public bool MeasureDuration { get; set; } 28 | 29 | /// 30 | /// By default, exceptions are not logged and there is no try-catch block around the method call. 31 | /// Set this property to some exception type to log exceptions of that type. 32 | /// 33 | public System.Type? ExceptionToLog { get; set; } 34 | 35 | /// 36 | /// If is not null, then this controls log level for exceptions. Default is . 37 | /// 38 | public Microsoft.Extensions.Logging.LogLevel ExceptionLogLevel { get; set; } = Microsoft.Extensions.Logging.LogLevel.Error; 39 | } 40 | } -------------------------------------------------------------------------------- /LoggingDecoratorGenerator.Tests/GeneratorSnapshotTests.GeneratesCorrectly#NotLoggedAttribute.g.verified.cs: -------------------------------------------------------------------------------- 1 | //HintName: NotLoggedAttribute.g.cs 2 | #nullable enable 3 | namespace Fineboym.Logging.Attributes 4 | { 5 | [System.AttributeUsage(System.AttributeTargets.Parameter | System.AttributeTargets.ReturnValue, AllowMultiple = false, Inherited = true)] 6 | internal sealed class NotLoggedAttribute : System.Attribute 7 | { 8 | } 9 | } -------------------------------------------------------------------------------- /LoggingDecoratorGenerator.Tests/GeneratorSnapshotTests.GeneratesCorrectly#SomeServiceLoggingDecorator.g.verified.cs: -------------------------------------------------------------------------------- 1 | //HintName: SomeServiceLoggingDecorator.g.cs 2 | #nullable enable 3 | 4 | namespace SomeFolder.SomeSubFolder 5 | { 6 | [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Fineboym.Logging.Generator", "1.10.0.0")] 7 | public sealed class SomeServiceLoggingDecorator : ISomeService 8 | { 9 | private readonly global::Microsoft.Extensions.Logging.ILogger _logger; 10 | private readonly ISomeService _decorated; 11 | 12 | public SomeServiceLoggingDecorator( 13 | global::Microsoft.Extensions.Logging.ILogger logger, 14 | ISomeService decorated) 15 | { 16 | _logger = logger; 17 | _decorated = decorated; 18 | } 19 | 20 | private static readonly global::System.Action s_beforeVoidParameterlessMethod 21 | = global::Microsoft.Extensions.Logging.LoggerMessage.Define( 22 | global::Microsoft.Extensions.Logging.LogLevel.Trace, 23 | new global::Microsoft.Extensions.Logging.EventId(101, "foo"), 24 | "Entering VoidParameterlessMethod", 25 | new global::Microsoft.Extensions.Logging.LogDefineOptions() { SkipEnabledCheck = true }); 26 | 27 | private static readonly global::System.Action s_afterVoidParameterlessMethod 28 | = global::Microsoft.Extensions.Logging.LoggerMessage.Define( 29 | global::Microsoft.Extensions.Logging.LogLevel.Trace, 30 | new global::Microsoft.Extensions.Logging.EventId(101, "foo"), 31 | "Method VoidParameterlessMethod returned. DurationInMilliseconds = {durationInMilliseconds}", 32 | new global::Microsoft.Extensions.Logging.LogDefineOptions() { SkipEnabledCheck = true }); 33 | 34 | public void VoidParameterlessMethod() 35 | { 36 | var __logEnabled = _logger.IsEnabled(global::Microsoft.Extensions.Logging.LogLevel.Trace); 37 | long __startTimestamp = 0; 38 | 39 | if (__logEnabled) 40 | { 41 | s_beforeVoidParameterlessMethod(_logger, null); 42 | __startTimestamp = global::System.Diagnostics.Stopwatch.GetTimestamp(); 43 | } 44 | 45 | _decorated.VoidParameterlessMethod(); 46 | 47 | if (__logEnabled) 48 | { 49 | var __elapsedTime = global::System.Diagnostics.Stopwatch.GetElapsedTime(__startTimestamp); 50 | s_afterVoidParameterlessMethod(_logger, __elapsedTime.TotalMilliseconds, null); 51 | } 52 | } 53 | 54 | private static readonly global::System.Action s_beforeIntReturningMethod 55 | = global::Microsoft.Extensions.Logging.LoggerMessage.Define( 56 | global::Microsoft.Extensions.Logging.LogLevel.Debug, 57 | new global::Microsoft.Extensions.Logging.EventId(390793361, nameof(IntReturningMethod)), 58 | "Entering IntReturningMethod with parameters: x = {x}, person = {person}", 59 | new global::Microsoft.Extensions.Logging.LogDefineOptions() { SkipEnabledCheck = true }); 60 | 61 | private static readonly global::System.Action s_afterIntReturningMethod 62 | = global::Microsoft.Extensions.Logging.LoggerMessage.Define( 63 | global::Microsoft.Extensions.Logging.LogLevel.Debug, 64 | new global::Microsoft.Extensions.Logging.EventId(390793361, nameof(IntReturningMethod)), 65 | "Method IntReturningMethod returned. Result = {result}", 66 | new global::Microsoft.Extensions.Logging.LogDefineOptions() { SkipEnabledCheck = true }); 67 | 68 | public int IntReturningMethod(int x, global::OtherFolder.OtherSubFolder.Person person) 69 | { 70 | var __logEnabled = _logger.IsEnabled(global::Microsoft.Extensions.Logging.LogLevel.Debug); 71 | 72 | if (__logEnabled) 73 | { 74 | s_beforeIntReturningMethod(_logger, x, person, null); 75 | } 76 | 77 | var __result = _decorated.IntReturningMethod(x, person); 78 | 79 | if (__logEnabled) 80 | { 81 | s_afterIntReturningMethod(_logger, __result, null); 82 | } 83 | 84 | return __result; 85 | } 86 | 87 | private static readonly global::System.Action s_beforeTaskReturningAsyncMethod 88 | = global::Microsoft.Extensions.Logging.LoggerMessage.Define( 89 | global::Microsoft.Extensions.Logging.LogLevel.Debug, 90 | new global::Microsoft.Extensions.Logging.EventId(658828815, nameof(TaskReturningAsyncMethod)), 91 | "Entering TaskReturningAsyncMethod with parameters: x = {x}, y = {y}", 92 | new global::Microsoft.Extensions.Logging.LogDefineOptions() { SkipEnabledCheck = true }); 93 | 94 | private static readonly global::System.Action s_afterTaskReturningAsyncMethod 95 | = global::Microsoft.Extensions.Logging.LoggerMessage.Define( 96 | global::Microsoft.Extensions.Logging.LogLevel.Debug, 97 | new global::Microsoft.Extensions.Logging.EventId(658828815, nameof(TaskReturningAsyncMethod)), 98 | "Method TaskReturningAsyncMethod returned", 99 | new global::Microsoft.Extensions.Logging.LogDefineOptions() { SkipEnabledCheck = true }); 100 | 101 | public async global::System.Threading.Tasks.Task TaskReturningAsyncMethod(int x, int y) 102 | { 103 | var __logEnabled = _logger.IsEnabled(global::Microsoft.Extensions.Logging.LogLevel.Debug); 104 | 105 | if (__logEnabled) 106 | { 107 | s_beforeTaskReturningAsyncMethod(_logger, x, y, null); 108 | } 109 | 110 | await _decorated.TaskReturningAsyncMethod(x, y).ConfigureAwait(false); 111 | 112 | if (__logEnabled) 113 | { 114 | s_afterTaskReturningAsyncMethod(_logger, null); 115 | } 116 | } 117 | 118 | private static readonly global::System.Action s_beforeTaskIntReturningAsyncMethod 119 | = global::Microsoft.Extensions.Logging.LoggerMessage.Define( 120 | global::Microsoft.Extensions.Logging.LogLevel.Debug, 121 | new global::Microsoft.Extensions.Logging.EventId(450889442, nameof(TaskIntReturningAsyncMethod)), 122 | "Entering TaskIntReturningAsyncMethod with parameters: x = {x}, y = {y}", 123 | new global::Microsoft.Extensions.Logging.LogDefineOptions() { SkipEnabledCheck = true }); 124 | 125 | private static readonly global::System.Action s_afterTaskIntReturningAsyncMethod 126 | = global::Microsoft.Extensions.Logging.LoggerMessage.Define( 127 | global::Microsoft.Extensions.Logging.LogLevel.Debug, 128 | new global::Microsoft.Extensions.Logging.EventId(450889442, nameof(TaskIntReturningAsyncMethod)), 129 | "Method TaskIntReturningAsyncMethod returned. Result = {result}", 130 | new global::Microsoft.Extensions.Logging.LogDefineOptions() { SkipEnabledCheck = true }); 131 | 132 | public async global::System.Threading.Tasks.Task TaskIntReturningAsyncMethod(int x, int y) 133 | { 134 | var __logEnabled = _logger.IsEnabled(global::Microsoft.Extensions.Logging.LogLevel.Debug); 135 | 136 | if (__logEnabled) 137 | { 138 | s_beforeTaskIntReturningAsyncMethod(_logger, x, y, null); 139 | } 140 | 141 | var __result = await _decorated.TaskIntReturningAsyncMethod(x, y).ConfigureAwait(false); 142 | 143 | if (__logEnabled) 144 | { 145 | s_afterTaskIntReturningAsyncMethod(_logger, __result, null); 146 | } 147 | 148 | return __result; 149 | } 150 | 151 | private static readonly global::System.Action s_beforeValueTaskReturningAsyncMethod 152 | = global::Microsoft.Extensions.Logging.LoggerMessage.Define( 153 | global::Microsoft.Extensions.Logging.LogLevel.Debug, 154 | new global::Microsoft.Extensions.Logging.EventId(1988761032, nameof(ValueTaskReturningAsyncMethod)), 155 | "Entering ValueTaskReturningAsyncMethod with parameters: x = {x}, y = {y}", 156 | new global::Microsoft.Extensions.Logging.LogDefineOptions() { SkipEnabledCheck = true }); 157 | 158 | private static readonly global::System.Action s_afterValueTaskReturningAsyncMethod 159 | = global::Microsoft.Extensions.Logging.LoggerMessage.Define( 160 | global::Microsoft.Extensions.Logging.LogLevel.Debug, 161 | new global::Microsoft.Extensions.Logging.EventId(1988761032, nameof(ValueTaskReturningAsyncMethod)), 162 | "Method ValueTaskReturningAsyncMethod returned", 163 | new global::Microsoft.Extensions.Logging.LogDefineOptions() { SkipEnabledCheck = true }); 164 | 165 | public async global::System.Threading.Tasks.ValueTask ValueTaskReturningAsyncMethod(int x, int y) 166 | { 167 | var __logEnabled = _logger.IsEnabled(global::Microsoft.Extensions.Logging.LogLevel.Debug); 168 | 169 | if (__logEnabled) 170 | { 171 | s_beforeValueTaskReturningAsyncMethod(_logger, x, y, null); 172 | } 173 | 174 | await _decorated.ValueTaskReturningAsyncMethod(x, y).ConfigureAwait(false); 175 | 176 | if (__logEnabled) 177 | { 178 | s_afterValueTaskReturningAsyncMethod(_logger, null); 179 | } 180 | } 181 | 182 | private static readonly global::System.Action s_beforeValueTaskFloatReturningAsyncMethod 183 | = global::Microsoft.Extensions.Logging.LoggerMessage.Define( 184 | global::Microsoft.Extensions.Logging.LogLevel.Debug, 185 | new global::Microsoft.Extensions.Logging.EventId(632205484, nameof(ValueTaskFloatReturningAsyncMethod)), 186 | "Entering ValueTaskFloatReturningAsyncMethod with parameters: x = {x}, y = {y}", 187 | new global::Microsoft.Extensions.Logging.LogDefineOptions() { SkipEnabledCheck = true }); 188 | 189 | private static readonly global::System.Action s_afterValueTaskFloatReturningAsyncMethod 190 | = global::Microsoft.Extensions.Logging.LoggerMessage.Define( 191 | global::Microsoft.Extensions.Logging.LogLevel.Debug, 192 | new global::Microsoft.Extensions.Logging.EventId(632205484, nameof(ValueTaskFloatReturningAsyncMethod)), 193 | "Method ValueTaskFloatReturningAsyncMethod returned. Result = {result}", 194 | new global::Microsoft.Extensions.Logging.LogDefineOptions() { SkipEnabledCheck = true }); 195 | 196 | public async global::System.Threading.Tasks.ValueTask ValueTaskFloatReturningAsyncMethod(int x, int y) 197 | { 198 | var __logEnabled = _logger.IsEnabled(global::Microsoft.Extensions.Logging.LogLevel.Debug); 199 | 200 | if (__logEnabled) 201 | { 202 | s_beforeValueTaskFloatReturningAsyncMethod(_logger, x, y, null); 203 | } 204 | 205 | var __result = await _decorated.ValueTaskFloatReturningAsyncMethod(x, y).ConfigureAwait(false); 206 | 207 | if (__logEnabled) 208 | { 209 | s_afterValueTaskFloatReturningAsyncMethod(_logger, __result, null); 210 | } 211 | 212 | return __result; 213 | } 214 | } 215 | } 216 | -------------------------------------------------------------------------------- /LoggingDecoratorGenerator.Tests/GeneratorSnapshotTests.cs: -------------------------------------------------------------------------------- 1 | namespace LoggingDecoratorGenerator.Tests; 2 | 3 | [UsesVerify] 4 | public class GeneratorSnapshotTests 5 | { 6 | [Fact] 7 | public Task GeneratesCorrectly() 8 | { 9 | // The source code to test 10 | var source = @" 11 | using System; 12 | using System.Threading.Tasks; 13 | using Fineboym.Logging.Attributes; 14 | using Microsoft.Extensions.Logging; 15 | 16 | namespace SomeFolder.SomeSubFolder 17 | { 18 | using OtherFolder.OtherSubFolder; 19 | 20 | [DecorateWithLogger] 21 | public interface ISomeService 22 | { 23 | [LogMethod(Level = LogLevel.Trace, EventId = 101, EventName = ""foo"", MeasureDuration = true)] 24 | void VoidParameterlessMethod(); 25 | 26 | int IntReturningMethod(int x, Person person); 27 | 28 | Task TaskReturningAsyncMethod(int x, int y); 29 | 30 | Task TaskIntReturningAsyncMethod(int x, int y); 31 | 32 | ValueTask ValueTaskReturningAsyncMethod(int x, int y); 33 | 34 | ValueTask ValueTaskFloatReturningAsyncMethod(int x, int y); 35 | } 36 | } 37 | 38 | namespace OtherFolder.OtherSubFolder 39 | { 40 | public record Person(string Name, int Age); 41 | }"; 42 | 43 | // Pass the source code to our helper and snapshot test the output 44 | return TestHelper.Verify(source); 45 | } 46 | } -------------------------------------------------------------------------------- /LoggingDecoratorGenerator.Tests/LoggingDecoratorGenerator.Tests.csproj: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | net7.0 5 | enable 6 | enable 7 | 8 | false 9 | 10 | 11 | 12 | 13 | all 14 | runtime; build; native; contentfiles; analyzers; buildtransitive 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | runtime; build; native; contentfiles; analyzers; buildtransitive 24 | all 25 | 26 | 27 | runtime; build; native; contentfiles; analyzers; buildtransitive 28 | all 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | -------------------------------------------------------------------------------- /LoggingDecoratorGenerator.Tests/ModuleInitializer.cs: -------------------------------------------------------------------------------- 1 | using System.Runtime.CompilerServices; 2 | 3 | namespace LoggingDecoratorGenerator.Tests; 4 | 5 | public static class ModuleInitializer 6 | { 7 | [ModuleInitializer] 8 | public static void Init() 9 | { 10 | VerifySourceGenerators.Initialize(); 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /LoggingDecoratorGenerator.Tests/TestHelper.cs: -------------------------------------------------------------------------------- 1 | using Fineboym.Logging.Generator; 2 | using Microsoft.CodeAnalysis; 3 | using Microsoft.CodeAnalysis.CSharp; 4 | 5 | namespace LoggingDecoratorGenerator.Tests; 6 | 7 | public static class TestHelper 8 | { 9 | public static Task Verify(string source) 10 | { 11 | // Parse the provided string into a C# syntax tree 12 | SyntaxTree syntaxTree = CSharpSyntaxTree.ParseText(source); 13 | 14 | IEnumerable references = AppDomain.CurrentDomain.GetAssemblies() 15 | .Where(static assembly => !assembly.IsDynamic && !string.IsNullOrWhiteSpace(assembly.Location)) 16 | .Select(static assembly => MetadataReference.CreateFromFile(assembly.Location)) 17 | .Concat(new[] { MetadataReference.CreateFromFile(typeof(DecoratorGenerator).Assembly.Location) }); 18 | 19 | // Create a Roslyn compilation for the syntax tree. 20 | CSharpCompilation compilation = CSharpCompilation.Create( 21 | assemblyName: "Tests", 22 | syntaxTrees: new[] { syntaxTree }, 23 | references: references); 24 | 25 | // Create an instance of our EnumGenerator incremental source generator 26 | var generator = new DecoratorGenerator(); 27 | 28 | // The GeneratorDriver is used to run our generator against a compilation 29 | GeneratorDriver driver = CSharpGeneratorDriver.Create(generator); 30 | 31 | // Run the source generator! 32 | driver = driver.RunGenerators(compilation); 33 | 34 | // Use verify to snapshot test the source generator output! 35 | return Verifier.Verify(driver); 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /LoggingDecoratorGenerator.Tests/Usings.cs: -------------------------------------------------------------------------------- 1 | global using Xunit; -------------------------------------------------------------------------------- /LoggingDecoratorGenerator.sln: -------------------------------------------------------------------------------- 1 |  2 | Microsoft Visual Studio Solution File, Format Version 12.00 3 | # Visual Studio Version 17 4 | VisualStudioVersion = 17.5.33209.295 5 | MinimumVisualStudioVersion = 10.0.40219.1 6 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Fineboym.Logging.Generator", "LoggingDecoratorGenerator\Fineboym.Logging.Generator.csproj", "{AA0CEEFA-7EA0-43A4-B04C-FD299A9EB00C}" 7 | EndProject 8 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "LoggingDecoratorGenerator.Tests", "LoggingDecoratorGenerator.Tests\LoggingDecoratorGenerator.Tests.csproj", "{CA980B33-06CB-4471-8100-6958024B5185}" 9 | EndProject 10 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "LoggingDecoratorGenerator.IntegrationTests", "LoggingDecoratorGenerator.IntegrationTests\LoggingDecoratorGenerator.IntegrationTests.csproj", "{2DE18598-A5D9-4A34-818A-9680890571C8}" 11 | EndProject 12 | Global 13 | GlobalSection(SolutionConfigurationPlatforms) = preSolution 14 | Debug|Any CPU = Debug|Any CPU 15 | Release|Any CPU = Release|Any CPU 16 | EndGlobalSection 17 | GlobalSection(ProjectConfigurationPlatforms) = postSolution 18 | {AA0CEEFA-7EA0-43A4-B04C-FD299A9EB00C}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 19 | {AA0CEEFA-7EA0-43A4-B04C-FD299A9EB00C}.Debug|Any CPU.Build.0 = Debug|Any CPU 20 | {AA0CEEFA-7EA0-43A4-B04C-FD299A9EB00C}.Release|Any CPU.ActiveCfg = Release|Any CPU 21 | {AA0CEEFA-7EA0-43A4-B04C-FD299A9EB00C}.Release|Any CPU.Build.0 = Release|Any CPU 22 | {CA980B33-06CB-4471-8100-6958024B5185}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 23 | {CA980B33-06CB-4471-8100-6958024B5185}.Debug|Any CPU.Build.0 = Debug|Any CPU 24 | {CA980B33-06CB-4471-8100-6958024B5185}.Release|Any CPU.ActiveCfg = Release|Any CPU 25 | {CA980B33-06CB-4471-8100-6958024B5185}.Release|Any CPU.Build.0 = Release|Any CPU 26 | {2DE18598-A5D9-4A34-818A-9680890571C8}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 27 | {2DE18598-A5D9-4A34-818A-9680890571C8}.Debug|Any CPU.Build.0 = Debug|Any CPU 28 | {2DE18598-A5D9-4A34-818A-9680890571C8}.Release|Any CPU.ActiveCfg = Release|Any CPU 29 | {2DE18598-A5D9-4A34-818A-9680890571C8}.Release|Any CPU.Build.0 = Release|Any CPU 30 | EndGlobalSection 31 | GlobalSection(SolutionProperties) = preSolution 32 | HideSolutionNode = FALSE 33 | EndGlobalSection 34 | GlobalSection(ExtensibilityGlobals) = postSolution 35 | SolutionGuid = {AFB03611-1FC1-4BE2-9C4F-A46A2E289A05} 36 | EndGlobalSection 37 | EndGlobal 38 | -------------------------------------------------------------------------------- /LoggingDecoratorGenerator/Attributes.cs: -------------------------------------------------------------------------------- 1 | namespace Fineboym.Logging.Generator; 2 | 3 | internal static class Attributes 4 | { 5 | private const string Namespace = "Fineboym.Logging.Attributes"; 6 | 7 | public const string DecorateWithLoggerName = "DecorateWithLoggerAttribute"; 8 | public const string DecorateWithLoggerFullName = $"{Namespace}.{DecorateWithLoggerName}"; 9 | public const string ReportDurationAsMetricName = "ReportDurationAsMetric"; 10 | public const string DecorateWithLogger = $$""" 11 | #nullable enable 12 | namespace {{Namespace}} 13 | { 14 | [System.AttributeUsage(System.AttributeTargets.Interface, AllowMultiple = false, Inherited = false)] 15 | internal sealed class {{DecorateWithLoggerName}} : System.Attribute 16 | { 17 | public Microsoft.Extensions.Logging.LogLevel Level { get; } 18 | 19 | /// 20 | /// Surrounds all method calls by , default is . 21 | /// Can be overridden for each method by . 22 | /// If is , then duration in milliseconds is included in the log message about method's return, otherwise separately as a metric in seconds. 23 | /// 24 | public bool {{LogMethodMeasureDurationName}} { get; set; } 25 | 26 | /// 27 | /// If a method measures duration and this is set to , then the decorator will report the durations of method invocations as a metric using the System.Diagnostics.Metrics APIs. 28 | /// If , the durations won't be reported in log messages and decorator class will require in its constructor. 29 | /// It's available by targeting .NET 6+, or in older .NET Core and .NET Framework apps by adding a reference to the .NET System.Diagnostics.DiagnosticsSource 6.0+ NuGet package. 30 | /// For more info, see ASP.NET Core metrics, 31 | /// .NET observability with OpenTelemetry, 32 | /// Collect metrics. 33 | /// 34 | public bool {{ReportDurationAsMetricName}} { get; set; } 35 | 36 | public {{DecorateWithLoggerName}}(Microsoft.Extensions.Logging.LogLevel level = Microsoft.Extensions.Logging.LogLevel.Debug) 37 | { 38 | Level = level; 39 | } 40 | } 41 | } 42 | """; 43 | 44 | public const string LogMethodName = "LogMethodAttribute"; 45 | public const string LogMethodFullName = $"{Namespace}.{LogMethodName}"; 46 | public const string LogMethodLevelName = "Level"; 47 | public const string LogMethodEventIdName = "EventId"; 48 | public const string LogMethodEventNameName = "EventName"; 49 | public const string LogMethodMeasureDurationName = "MeasureDuration"; 50 | public const string LogMethodExceptionToLogName = "ExceptionToLog"; 51 | public const string LogMethodExceptionLogLevelName = "ExceptionLogLevel"; 52 | public const string LogMethod = $$""" 53 | #nullable enable 54 | namespace {{Namespace}} 55 | { 56 | [System.AttributeUsage(System.AttributeTargets.Method, AllowMultiple = false, Inherited = true)] 57 | internal sealed class {{LogMethodName}} : System.Attribute 58 | { 59 | public Microsoft.Extensions.Logging.LogLevel {{LogMethodLevelName}} { get; set; } = Microsoft.Extensions.Logging.LogLevel.None; 60 | 61 | /// 62 | /// Gets the logging event id for the logging method. 63 | /// 64 | public int {{LogMethodEventIdName}} { get; set; } = -1; 65 | 66 | /// 67 | /// Gets or sets the logging event name for the logging method. 68 | /// 69 | /// 70 | /// This will equal the method name if not specified. 71 | /// 72 | public string? {{LogMethodEventNameName}} { get; set; } 73 | 74 | /// 75 | /// Surrounds the method call by , default is . 76 | /// If is , then duration in milliseconds is included in the log message about method's return, otherwise separately as a metric in seconds. 77 | /// 78 | public bool {{LogMethodMeasureDurationName}} { get; set; } 79 | 80 | /// 81 | /// By default, exceptions are not logged and there is no try-catch block around the method call. 82 | /// Set this property to some exception type to log exceptions of that type. 83 | /// 84 | public System.Type? {{LogMethodExceptionToLogName}} { get; set; } 85 | 86 | /// 87 | /// If is not null, then this controls log level for exceptions. Default is . 88 | /// 89 | public Microsoft.Extensions.Logging.LogLevel {{LogMethodExceptionLogLevelName}} { get; set; } = Microsoft.Extensions.Logging.LogLevel.Error; 90 | } 91 | } 92 | """; 93 | 94 | public const string NotLoggedName = "NotLoggedAttribute"; 95 | public const string NotLoggedFullName = $"{Namespace}.{NotLoggedName}"; 96 | public const string NotLogged = $$""" 97 | #nullable enable 98 | namespace {{Namespace}} 99 | { 100 | [System.AttributeUsage(System.AttributeTargets.Parameter | System.AttributeTargets.ReturnValue, AllowMultiple = false, Inherited = true)] 101 | internal sealed class {{NotLoggedName}} : System.Attribute 102 | { 103 | } 104 | } 105 | """; 106 | } 107 | -------------------------------------------------------------------------------- /LoggingDecoratorGenerator/CompilerErrorException.cs: -------------------------------------------------------------------------------- 1 | namespace Fineboym.Logging.Generator; 2 | 3 | [Serializable] 4 | internal class CompilerErrorException : Exception 5 | { 6 | public CompilerErrorException() { } 7 | public CompilerErrorException(string message) : base(message) { } 8 | public CompilerErrorException(string message, Exception inner) : base(message, inner) { } 9 | protected CompilerErrorException( 10 | System.Runtime.Serialization.SerializationInfo info, 11 | System.Runtime.Serialization.StreamingContext context) : base(info, context) { } 12 | } 13 | -------------------------------------------------------------------------------- /LoggingDecoratorGenerator/DecoratorClass.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.CodeAnalysis; 2 | using Microsoft.CodeAnalysis.CSharp; 3 | using Microsoft.CodeAnalysis.CSharp.Syntax; 4 | using System.Collections.Immutable; 5 | 6 | namespace Fineboym.Logging.Generator; 7 | 8 | internal class DecoratorClassParser 9 | { 10 | private readonly INamedTypeSymbol _interfaceMarkerAttribute; 11 | private readonly INamedTypeSymbol _methodMarkerAttribute; 12 | private readonly INamedTypeSymbol _notLoggedAttribute; 13 | private readonly Action _reportDiagnostic; 14 | private readonly CancellationToken _cancellationToken; 15 | 16 | public DecoratorClassParser( 17 | INamedTypeSymbol interfaceMarkerAttribute, 18 | INamedTypeSymbol methodMarkerAttribute, 19 | INamedTypeSymbol notLoggedAttribute, 20 | Action reportDiagnostic, 21 | CancellationToken cancellationToken) 22 | { 23 | _interfaceMarkerAttribute = interfaceMarkerAttribute; 24 | _methodMarkerAttribute = methodMarkerAttribute; 25 | _notLoggedAttribute = notLoggedAttribute; 26 | _reportDiagnostic = reportDiagnostic; 27 | _cancellationToken = cancellationToken; 28 | } 29 | 30 | public bool TryParseDecoratorClass(SemanticModel semanticModel, InterfaceDeclarationSyntax interfaceDeclaration, out DecoratorClass? decoratorClass) 31 | { 32 | decoratorClass = null; 33 | 34 | if (interfaceDeclaration.Arity > 0) 35 | { 36 | ReportDiagnostic(DiagnosticDescriptors.GenericInterfaceNotSupported, interfaceDeclaration.Identifier.GetLocation()); 37 | return false; 38 | } 39 | 40 | string? nameSpace = GetNamespace(interfaceDeclaration); 41 | if (nameSpace == null) 42 | { 43 | ReportDiagnostic(DiagnosticDescriptors.InterfaceNoNamespace, interfaceDeclaration.Identifier.GetLocation()); 44 | return false; 45 | } 46 | 47 | if (interfaceDeclaration.Parent is not BaseNamespaceDeclarationSyntax) 48 | { 49 | ReportDiagnostic(DiagnosticDescriptors.NestedInterfaceNotSupported, interfaceDeclaration.Identifier.GetLocation()); 50 | return false; 51 | } 52 | 53 | if (semanticModel.GetDeclaredSymbol(interfaceDeclaration, _cancellationToken) is not INamedTypeSymbol interfaceSymbol) 54 | { 55 | // something went wrong, bail out 56 | return false; 57 | } 58 | 59 | if (interfaceSymbol.IsFileLocal) 60 | { 61 | ReportDiagnostic(DiagnosticDescriptors.FileLocalInterfaceNotSupported, interfaceDeclaration.Identifier.GetLocation()); 62 | return false; 63 | } 64 | 65 | (string? interfaceLogLevel, bool measureDuration, bool durationAsMetric) = (null, false, false); 66 | List methods; 67 | try 68 | { 69 | (interfaceLogLevel, measureDuration, durationAsMetric) = ResolveInterfaceAttribute(interfaceSymbol); 70 | if (interfaceLogLevel == null) 71 | { 72 | return false; 73 | } 74 | 75 | methods = new List(); 76 | 77 | if (!TryParseMembers(interfaceSymbol, interfaceLogLevel, measureDuration, methods)) 78 | { 79 | return false; 80 | } 81 | 82 | foreach (INamedTypeSymbol baseInterface in interfaceSymbol.AllInterfaces) 83 | { 84 | (string? baseInterfaceLogLevel, measureDuration, _) = ResolveInterfaceAttribute(baseInterface); 85 | if (!TryParseMembers(baseInterface, baseInterfaceLogLevel, measureDuration, methods)) 86 | { 87 | return false; 88 | } 89 | } 90 | } 91 | catch (CompilerErrorException) 92 | { 93 | return false; 94 | } 95 | 96 | // Once we've collected all methods for the given interface, check for overloads and provide unique names 97 | var methodsMap = new Dictionary(methods.Count, StringComparer.Ordinal); 98 | foreach (MethodToGenerate m in methods) 99 | { 100 | if (methodsMap.TryGetValue(m.MethodSymbol.Name, out int currentCount)) 101 | { 102 | m.UniqueName = $"{m.MethodSymbol.Name}{currentCount}"; 103 | methodsMap[m.MethodSymbol.Name] = currentCount + 1; 104 | } 105 | else 106 | { 107 | m.UniqueName = m.MethodSymbol.Name; 108 | methodsMap[m.MethodSymbol.Name] = 1; //start from 1 109 | } 110 | } 111 | 112 | decoratorClass = new( 113 | @namespace: nameSpace, 114 | interfaceName: interfaceSymbol.Name, 115 | declaredAccessibility: SyntaxFacts.GetText(interfaceSymbol.DeclaredAccessibility), 116 | logLevel: interfaceLogLevel, 117 | durationAsMetric, 118 | methods: methods); 119 | 120 | return true; 121 | } 122 | 123 | private bool TryParseMembers(INamedTypeSymbol interfaceSymbol, string? logLevel, bool measureDuration, List methods) 124 | { 125 | foreach (ISymbol member in interfaceSymbol.GetMembers()) 126 | { 127 | if (member is INamedTypeSymbol) 128 | { 129 | // Not interested in nested types as they won't affect the generated code 130 | continue; 131 | } 132 | 133 | if (member.IsStatic) 134 | { 135 | // Not interested in static members as they can only be referred from the interface instance type 136 | continue; 137 | } 138 | 139 | if (member.Name[0] == '_') 140 | { 141 | // can't have member names that start with _ since that can lead to conflicting symbol names 142 | // because the generated symbols start with _ 143 | ReportDiagnostic(DiagnosticDescriptors.InvalidMemberName, member.Locations[0]); 144 | return false; 145 | } 146 | 147 | if (member is IMethodSymbol methodSymbol && methodSymbol.MethodKind == MethodKind.Ordinary) 148 | { 149 | if (methodSymbol.Arity > 0) 150 | { 151 | ReportDiagnostic(DiagnosticDescriptors.GenericMethodsNotSupported, methodSymbol.Locations[0]); 152 | return false; 153 | } 154 | 155 | if (methodSymbol.ReturnsByRef || methodSymbol.ReturnsByRefReadonly) 156 | { 157 | ReportDiagnostic(DiagnosticDescriptors.RefReturnNotSupported, methodSymbol.Locations[0]); 158 | return false; 159 | } 160 | 161 | MethodToGenerate decMethod = new(methodSymbol, logLevel, measureDuration, _methodMarkerAttribute, _notLoggedAttribute); 162 | methods.Add(decMethod); 163 | } 164 | else 165 | { 166 | ReportDiagnostic(DiagnosticDescriptors.OnlyOrdinaryMethods, member.Locations[0]); 167 | return false; 168 | } 169 | } 170 | 171 | return true; 172 | } 173 | 174 | // determine the namespace the class/enum/struct is declared in, if any 175 | private static string? GetNamespace(BaseTypeDeclarationSyntax syntax) 176 | { 177 | // If we don't have a namespace at all we'll return an empty string 178 | // This accounts for the "default namespace" case 179 | string? nameSpace = null; 180 | 181 | // Get the containing syntax node for the type declaration 182 | // (could be a nested type, for example) 183 | SyntaxNode? potentialNamespaceParent = syntax.Parent; 184 | 185 | // Keep moving "out" of nested classes etc until we get to a namespace 186 | // or until we run out of parents 187 | while (potentialNamespaceParent != null && 188 | potentialNamespaceParent is not NamespaceDeclarationSyntax 189 | && potentialNamespaceParent is not FileScopedNamespaceDeclarationSyntax) 190 | { 191 | potentialNamespaceParent = potentialNamespaceParent.Parent; 192 | } 193 | 194 | // Build up the final namespace by looping until we no longer have a namespace declaration 195 | if (potentialNamespaceParent is BaseNamespaceDeclarationSyntax namespaceParent) 196 | { 197 | // We have a namespace. Use that as the type 198 | nameSpace = namespaceParent.Name.ToString(); 199 | 200 | // Keep moving "out" of the namespace declarations until we 201 | // run out of nested namespace declarations 202 | while (true) 203 | { 204 | if (namespaceParent.Parent is not NamespaceDeclarationSyntax parent) 205 | { 206 | break; 207 | } 208 | 209 | // Add the outer namespace as a prefix to the final namespace 210 | nameSpace = $"{namespaceParent.Name}.{nameSpace}"; 211 | namespaceParent = parent; 212 | } 213 | } 214 | 215 | // return the final namespace 216 | return nameSpace; 217 | } 218 | 219 | private (string? logLevel, bool measureDuration, bool durationAsMetric) ResolveInterfaceAttribute(INamedTypeSymbol interfaceSymbol) 220 | { 221 | foreach (AttributeData attributeData in interfaceSymbol.GetAttributes()) 222 | { 223 | if (!_interfaceMarkerAttribute.Equals(attributeData.AttributeClass, SymbolEqualityComparer.Default)) 224 | { 225 | continue; 226 | } 227 | 228 | ImmutableArray args = attributeData.ConstructorArguments; 229 | 230 | // make sure we don't have any errors 231 | foreach (TypedConstant arg in args) 232 | { 233 | if (arg.Kind == TypedConstantKind.Error) 234 | { 235 | // have an error, so don't try and do any generation 236 | throw new CompilerErrorException(); 237 | } 238 | } 239 | 240 | if (args[0].Value is not int logLevelValue) 241 | { 242 | throw new CompilerErrorException(); 243 | } 244 | 245 | bool measureDuration = false; 246 | bool reportDurationAsMetric = false; 247 | foreach (KeyValuePair arg in attributeData.NamedArguments) 248 | { 249 | TypedConstant typedConstant = arg.Value; 250 | if (typedConstant.Kind == TypedConstantKind.Error) 251 | { 252 | throw new CompilerErrorException(); 253 | } 254 | 255 | switch (arg.Key) 256 | { 257 | case Attributes.LogMethodMeasureDurationName when typedConstant.Value is bool value: 258 | measureDuration = value; 259 | break; 260 | case Attributes.ReportDurationAsMetricName when typedConstant.Value is bool value: 261 | reportDurationAsMetric = value; 262 | break; 263 | } 264 | } 265 | 266 | return ($"global::Microsoft.Extensions.Logging.LogLevel.{LogLevelConverter.FromInt(logLevelValue)}", measureDuration, reportDurationAsMetric); 267 | } 268 | 269 | return (null, false, false); 270 | } 271 | 272 | private void ReportDiagnostic(DiagnosticDescriptor desc, Location? location, params object?[]? messageArgs) 273 | { 274 | _reportDiagnostic(Diagnostic.Create(desc, location, messageArgs)); 275 | } 276 | } 277 | 278 | internal class DecoratorClass 279 | { 280 | public string Namespace { get; } 281 | 282 | public string InterfaceName { get; } 283 | 284 | public string DeclaredAccessibility { get; } 285 | 286 | public string LogLevel { get; } 287 | 288 | public bool DurationAsMetric { get; } 289 | 290 | public IReadOnlyList Methods { get; } 291 | 292 | public string ClassName { get; } 293 | 294 | public bool SomeMethodMeasuresDuration { get; } 295 | 296 | public bool NeedsDurationAsMetric => SomeMethodMeasuresDuration && DurationAsMetric; 297 | 298 | public DecoratorClass(string @namespace, string interfaceName, string declaredAccessibility, string logLevel, bool durationAsMetric, IReadOnlyList methods) 299 | { 300 | Namespace = @namespace; 301 | InterfaceName = interfaceName; 302 | DeclaredAccessibility = declaredAccessibility; 303 | LogLevel = logLevel; 304 | DurationAsMetric = durationAsMetric; 305 | Methods = methods; 306 | ClassName = $"{(interfaceName[0] == 'I' ? interfaceName.Substring(1) : interfaceName)}LoggingDecorator"; 307 | SomeMethodMeasuresDuration = methods.Any(static m => m.MeasureDuration); 308 | } 309 | } -------------------------------------------------------------------------------- /LoggingDecoratorGenerator/DecoratorGenerator.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.CodeAnalysis; 2 | using Microsoft.CodeAnalysis.CSharp.Syntax; 3 | using Microsoft.CodeAnalysis.Text; 4 | using System.Collections.Immutable; 5 | using System.Text; 6 | 7 | namespace Fineboym.Logging.Generator; 8 | 9 | [Generator] 10 | public class DecoratorGenerator : IIncrementalGenerator 11 | { 12 | public void Initialize(IncrementalGeneratorInitializationContext context) 13 | { 14 | // Add the marker attributes to the compilation 15 | context.RegisterPostInitializationOutput(static ctx => 16 | { 17 | ctx.AddSource($"{Attributes.DecorateWithLoggerName}.g.cs", SourceText.From(Attributes.DecorateWithLogger, Encoding.UTF8)); 18 | ctx.AddSource($"{Attributes.LogMethodName}.g.cs", SourceText.From(Attributes.LogMethod, Encoding.UTF8)); 19 | ctx.AddSource($"{Attributes.NotLoggedName}.g.cs", SourceText.From(Attributes.NotLogged, Encoding.UTF8)); 20 | }); 21 | 22 | // Do a simple filter for interfaces 23 | IncrementalValuesProvider interfaceDeclarations = context.SyntaxProvider 24 | .ForAttributeWithMetadataName( 25 | Attributes.DecorateWithLoggerFullName, 26 | predicate: static (node, _) => node is InterfaceDeclarationSyntax, 27 | transform: static (context, _) => context.TargetNode as InterfaceDeclarationSyntax) 28 | .Where(predicate: static m => m is not null)!; 29 | 30 | // Combine the selected interfaces with the `Compilation` 31 | IncrementalValueProvider<(Compilation, ImmutableArray)> compilationAndInterfaces 32 | = context.CompilationProvider.Combine(provider2: interfaceDeclarations.Collect()); 33 | 34 | // Generate the source using the compilation and interfaces 35 | context.RegisterSourceOutput(source: compilationAndInterfaces, action: static (spc, source) => Execute(source.Item1, source.Item2, spc)); 36 | } 37 | 38 | private static void Execute(Compilation compilation, ImmutableArray interfaces, SourceProductionContext context) 39 | { 40 | if (interfaces.IsDefaultOrEmpty) 41 | { 42 | // nothing to do yet 43 | return; 44 | } 45 | 46 | IEnumerable distinctInterfaces = interfaces.Distinct(); 47 | 48 | var p = new Parser(compilation, context.ReportDiagnostic, context.CancellationToken); 49 | IReadOnlyList decoratorClasses = p.GetDecoratorClasses(distinctInterfaces); 50 | 51 | foreach (var decoratorClass in decoratorClasses) 52 | { 53 | context.CancellationToken.ThrowIfCancellationRequested(); 54 | string source = SourceGenerationHelper.GenerateLoggingDecoratorClass(decoratorClass, p.StopwatchGetElapsedTimeAvailable); 55 | context.AddSource(hintName: $"{decoratorClass.ClassName}.g.cs", sourceText: SourceText.From(text: source, encoding: Encoding.UTF8)); 56 | } 57 | } 58 | } 59 | -------------------------------------------------------------------------------- /LoggingDecoratorGenerator/DiagnosticDescriptors.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.CodeAnalysis; 2 | 3 | namespace Fineboym.Logging.Generator; 4 | 5 | internal static class DiagnosticDescriptors 6 | { 7 | public static DiagnosticDescriptor GenericInterfaceNotSupported { get; } = new DiagnosticDescriptor( 8 | id: "LOGDEC0001", 9 | title: "Generic Interface", 10 | messageFormat: "Generic interfaces are not supported by logging decorator.", 11 | category: "LoggingGenerator", 12 | DiagnosticSeverity.Error, 13 | isEnabledByDefault: true); 14 | 15 | public static DiagnosticDescriptor InterfaceNoNamespace { get; } = new DiagnosticDescriptor( 16 | id: "LOGDEC0002", 17 | title: "Interface Without Namespace", 18 | messageFormat: "Interfaces without namespace are not supported by logging decorator.", 19 | category: "LoggingGenerator", 20 | DiagnosticSeverity.Error, 21 | isEnabledByDefault: true); 22 | 23 | public static DiagnosticDescriptor NestedInterfaceNotSupported { get; } = new DiagnosticDescriptor( 24 | id: "LOGDEC0003", 25 | title: "Nested Interface", 26 | messageFormat: "Nested interfaces are not supported by logging decorator.", 27 | category: "LoggingGenerator", 28 | DiagnosticSeverity.Error, 29 | isEnabledByDefault: true); 30 | 31 | public static DiagnosticDescriptor FileLocalInterfaceNotSupported { get; } = new DiagnosticDescriptor( 32 | id: "LOGDEC0004", 33 | title: "File Local", 34 | messageFormat: "File local interfaces are not supported by logging decorator.", 35 | category: "LoggingGenerator", 36 | DiagnosticSeverity.Error, 37 | isEnabledByDefault: true); 38 | 39 | public static DiagnosticDescriptor InvalidMemberName { get; } = new DiagnosticDescriptor( 40 | id: "LOGDEC0005", 41 | title: "Invalid Name", 42 | messageFormat: "Member names that start with _ are not supported by logging decorator.", 43 | category: "LoggingGenerator", 44 | DiagnosticSeverity.Error, 45 | isEnabledByDefault: true); 46 | 47 | public static DiagnosticDescriptor GenericMethodsNotSupported { get; } = new DiagnosticDescriptor( 48 | id: "LOGDEC0006", 49 | title: "Generic Method", 50 | messageFormat: "Generic methods are not supported by logging decorator.", 51 | category: "LoggingGenerator", 52 | DiagnosticSeverity.Error, 53 | isEnabledByDefault: true); 54 | 55 | public static DiagnosticDescriptor RefReturnNotSupported { get; } = new DiagnosticDescriptor( 56 | id: "LOGDEC0007", 57 | title: "Method Returns by ref", 58 | messageFormat: "Ref returning methods are not supported by logging decorator.", 59 | category: "LoggingGenerator", 60 | DiagnosticSeverity.Error, 61 | isEnabledByDefault: true); 62 | 63 | public static DiagnosticDescriptor OnlyOrdinaryMethods { get; } = new DiagnosticDescriptor( 64 | id: "LOGDEC0008", 65 | title: "Only Ordinary Methods", 66 | messageFormat: "Only ordinary methods are supported by logging decorator.", 67 | category: "LoggingGenerator", 68 | DiagnosticSeverity.Error, 69 | isEnabledByDefault: true); 70 | } 71 | -------------------------------------------------------------------------------- /LoggingDecoratorGenerator/Fineboym.Logging.Generator.csproj: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | netstandard2.0 5 | false 6 | enable 7 | true 8 | Latest 9 | true 10 | False 11 | 1.10.0 12 | dfineboym 13 | 14 | True 15 | preview-all 16 | Logging Decorator Source Generator 17 | https://github.com/DavidFineboym/LoggingDecoratorGenerator 18 | logging decorator;source generator 19 | True 20 | Source generates logger decorator class for an interface. Uses Microsoft.Extensions.Logging.ILogger to log and requires it in decorator class constructor. 21 | 22 | 23 | 24 | MIT 25 | NuGetReadme.md 26 | icon.png 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | True 38 | \ 39 | 40 | 41 | 42 | 43 | 44 | -------------------------------------------------------------------------------- /LoggingDecoratorGenerator/LogLevelConverter.cs: -------------------------------------------------------------------------------- 1 | namespace Fineboym.Logging.Generator; 2 | 3 | internal static class LogLevelConverter 4 | { 5 | public static string FromInt(int value) => value switch 6 | { 7 | 0 => "Trace", 8 | 1 => "Debug", 9 | 2 => "Information", 10 | 3 => "Warning", 11 | 4 => "Error", 12 | 5 => "Critical", 13 | 6 => "None", 14 | _ => value.ToString() 15 | }; 16 | } 17 | -------------------------------------------------------------------------------- /LoggingDecoratorGenerator/MethodToGenerate.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.CodeAnalysis; 2 | 3 | namespace Fineboym.Logging.Generator; 4 | 5 | internal class MethodToGenerate 6 | { 7 | private const string LogLevelEnumFullName = "global::Microsoft.Extensions.Logging.LogLevel"; 8 | 9 | public IMethodSymbol MethodSymbol { get; } 10 | 11 | public IReadOnlyList Parameters { get; } 12 | 13 | public string? LogLevel { get; } 14 | 15 | public int EventId { get; } 16 | 17 | public string EventName { get; } 18 | 19 | public string UniqueName { get; set; } 20 | 21 | public bool Awaitable { get; private set; } 22 | 23 | public bool HasReturnValue { get; private set; } 24 | 25 | public bool ReturnValueLogged { get; } 26 | 27 | public ITypeSymbol? UnwrappedReturnType { get; private set; } 28 | 29 | public bool MeasureDuration { get; private set; } 30 | 31 | public string? ExceptionTypeToLog { get; private set; } 32 | 33 | public string ExceptionLogLevel { get; private set; } 34 | // TODO: Refactor to MethodParser and add diagnostics for unsupported parameters- ref, out... 35 | public MethodToGenerate( 36 | IMethodSymbol methodSymbol, 37 | string? interfaceLogLevel, 38 | bool interfaceMeasureDuration, 39 | INamedTypeSymbol methodMarkerAttribute, 40 | INamedTypeSymbol notLoggedAttribute) 41 | { 42 | MethodSymbol = methodSymbol; 43 | UniqueName = methodSymbol.Name; // assume no overloads at first 44 | CheckReturnType(methodSymbol.ReturnType); 45 | LogLevel = interfaceLogLevel; 46 | MeasureDuration = interfaceMeasureDuration; 47 | bool suppliedEventId = false; 48 | string? suppliedEventName = null; 49 | 50 | foreach (AttributeData attributeData in methodSymbol.GetAttributes()) 51 | { 52 | if (!methodMarkerAttribute.Equals(attributeData.AttributeClass, SymbolEqualityComparer.Default)) 53 | { 54 | continue; 55 | } 56 | 57 | foreach (KeyValuePair arg in attributeData.NamedArguments) 58 | { 59 | TypedConstant typedConstant = arg.Value; 60 | if (typedConstant.Kind == TypedConstantKind.Error) 61 | { 62 | throw new CompilerErrorException(); 63 | } 64 | 65 | switch (arg.Key) 66 | { 67 | case Attributes.LogMethodLevelName when typedConstant.Value is int logLevel: 68 | LogLevel = $"{LogLevelEnumFullName}.{LogLevelConverter.FromInt(logLevel)}"; 69 | break; 70 | case Attributes.LogMethodEventIdName when typedConstant.Value is int eventId: 71 | EventId = eventId; 72 | suppliedEventId = true; 73 | break; 74 | case Attributes.LogMethodEventNameName when typedConstant.Value is string eventName: 75 | suppliedEventName = eventName; 76 | break; 77 | case Attributes.LogMethodMeasureDurationName when typedConstant.Value is bool measureDuration: 78 | MeasureDuration = measureDuration; 79 | break; 80 | case Attributes.LogMethodExceptionToLogName when typedConstant.Value is INamedTypeSymbol exceptionToLog: 81 | ExceptionTypeToLog = exceptionToLog.ToFullyQualifiedDisplayString(); 82 | break; 83 | case Attributes.LogMethodExceptionLogLevelName when typedConstant.Value is int exceptionLogLevel: 84 | ExceptionLogLevel = $"{LogLevelEnumFullName}.{LogLevelConverter.FromInt(exceptionLogLevel)}"; 85 | break; 86 | } 87 | } 88 | 89 | break; 90 | } 91 | 92 | if (!suppliedEventId) 93 | { 94 | EventId = GetNonRandomizedHashCode(string.IsNullOrWhiteSpace(suppliedEventName) ? methodSymbol.Name : suppliedEventName!); 95 | } 96 | 97 | EventName = string.IsNullOrWhiteSpace(suppliedEventName) ? $"nameof({methodSymbol.Name})" : $"\"{suppliedEventName}\""; 98 | 99 | if (ExceptionLogLevel == default) 100 | { 101 | ExceptionLogLevel = $"{LogLevelEnumFullName}.Error"; // default log level 102 | } 103 | 104 | var parameters = new List(capacity: methodSymbol.Parameters.Length); 105 | foreach (IParameterSymbol parameterSymbol in methodSymbol.Parameters) 106 | { 107 | parameters.Add(new(parameterSymbol, notLoggedAttribute)); 108 | } 109 | Parameters = parameters; 110 | 111 | ReturnValueLogged = !methodSymbol.GetReturnTypeAttributes() 112 | .Any(attributeData => notLoggedAttribute.Equals(attributeData.AttributeClass, SymbolEqualityComparer.Default)); 113 | } 114 | 115 | private void CheckReturnType(ITypeSymbol methodReturnType) 116 | { 117 | string returnTypeOriginalDef = methodReturnType.OriginalDefinition.ToString(); 118 | 119 | if (returnTypeOriginalDef is "System.Threading.Tasks.Task" or "System.Threading.Tasks.ValueTask") 120 | { 121 | Awaitable = true; 122 | HasReturnValue = true; 123 | UnwrappedReturnType = ((INamedTypeSymbol)methodReturnType).TypeArguments[0]; 124 | 125 | return; 126 | } 127 | 128 | if (returnTypeOriginalDef is "System.Threading.Tasks.Task" or "System.Threading.Tasks.ValueTask") 129 | { 130 | Awaitable = true; 131 | HasReturnValue = false; 132 | 133 | return; 134 | } 135 | 136 | Awaitable = false; 137 | HasReturnValue = methodReturnType.SpecialType != SpecialType.System_Void; 138 | } 139 | 140 | /// 141 | /// Returns a non-randomized hash code for the given string. 142 | /// We always return a positive value. 143 | /// 144 | private static int GetNonRandomizedHashCode(string s) 145 | { 146 | uint result = 2166136261u; 147 | foreach (char c in s) 148 | { 149 | result = (c ^ result) * 16777619; 150 | } 151 | return Math.Abs((int)result); 152 | } 153 | } 154 | -------------------------------------------------------------------------------- /LoggingDecoratorGenerator/Parameter.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.CodeAnalysis; 2 | 3 | namespace Fineboym.Logging.Generator; 4 | 5 | internal class Parameter 6 | { 7 | public IParameterSymbol Symbol { get; } 8 | 9 | public bool IsLogged { get; } 10 | 11 | public Parameter(IParameterSymbol symbol, INamedTypeSymbol notLoggedAttribute) 12 | { 13 | Symbol = symbol; 14 | IsLogged = true; 15 | 16 | foreach (AttributeData attributeData in symbol.GetAttributes()) 17 | { 18 | if (notLoggedAttribute.Equals(attributeData.AttributeClass, SymbolEqualityComparer.Default)) 19 | { 20 | IsLogged = false; 21 | 22 | break; 23 | } 24 | } 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /LoggingDecoratorGenerator/Parser.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.CodeAnalysis; 2 | using Microsoft.CodeAnalysis.CSharp.Syntax; 3 | 4 | namespace Fineboym.Logging.Generator; 5 | 6 | internal sealed class Parser 7 | { 8 | private readonly CancellationToken _cancellationToken; 9 | private readonly Compilation _compilation; 10 | private readonly Action _reportDiagnostic; 11 | 12 | public bool StopwatchGetElapsedTimeAvailable { get; private set; } 13 | 14 | public Parser(Compilation compilation, Action reportDiagnostic, CancellationToken cancellationToken) 15 | { 16 | _compilation = compilation; 17 | _cancellationToken = cancellationToken; 18 | _reportDiagnostic = reportDiagnostic; 19 | } 20 | 21 | public IReadOnlyList GetDecoratorClasses(IEnumerable interfaces) 22 | { 23 | // Get the semantic representation of our marker attribute 24 | INamedTypeSymbol? interfaceMarkerAttribute = _compilation.GetBestTypeByMetadataName(Attributes.DecorateWithLoggerFullName); 25 | if (interfaceMarkerAttribute == null) 26 | { 27 | // nothing to do if this type isn't available 28 | return Array.Empty(); 29 | } 30 | 31 | INamedTypeSymbol? methodMarkerAttribute = _compilation.GetBestTypeByMetadataName(Attributes.LogMethodFullName); 32 | if (methodMarkerAttribute == null) 33 | { 34 | // nothing to do if this type isn't available 35 | return Array.Empty(); 36 | } 37 | 38 | INamedTypeSymbol? notLoggedAttribute = _compilation.GetBestTypeByMetadataName(Attributes.NotLoggedFullName); 39 | if (notLoggedAttribute == null) 40 | { 41 | // nothing to do if this type isn't available 42 | return Array.Empty(); 43 | } 44 | 45 | INamedTypeSymbol? stopwatchType = _compilation.GetBestTypeByMetadataName("System.Diagnostics.Stopwatch"); 46 | if (stopwatchType == null) 47 | { 48 | return Array.Empty(); 49 | } 50 | 51 | StopwatchGetElapsedTimeAvailable = stopwatchType.GetMembers("GetElapsedTime") 52 | .OfType() 53 | .Where(ms => ms.DeclaredAccessibility == Accessibility.Public && ms.IsStatic) 54 | .Any(); 55 | 56 | var results = new List(); 57 | DecoratorClassParser parser = new(interfaceMarkerAttribute, methodMarkerAttribute, notLoggedAttribute, _reportDiagnostic, _cancellationToken); 58 | 59 | // we enumerate by syntax tree, to minimize the need to instantiate semantic models (since they're expensive) 60 | foreach (IGrouping group in interfaces.GroupBy(static x => x.SyntaxTree)) 61 | { 62 | SyntaxTree syntaxTree = group.Key; 63 | SemanticModel sm = _compilation.GetSemanticModel(syntaxTree); 64 | 65 | foreach (InterfaceDeclarationSyntax interfaceDec in group) 66 | { 67 | // stop if we're asked to 68 | _cancellationToken.ThrowIfCancellationRequested(); 69 | 70 | if (!parser.TryParseDecoratorClass(sm, interfaceDec, out DecoratorClass? decorator)) 71 | { 72 | continue; 73 | } 74 | 75 | results.Add(decorator!); 76 | } 77 | } 78 | 79 | return results; 80 | } 81 | } 82 | -------------------------------------------------------------------------------- /LoggingDecoratorGenerator/RoslynExtensions.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.CodeAnalysis; 2 | 3 | namespace Fineboym.Logging.Generator; 4 | 5 | internal static class RoslynExtensions 6 | { 7 | private static readonly SymbolDisplayFormat s_symbolFormat = SymbolDisplayFormat.FullyQualifiedFormat 8 | .AddMiscellaneousOptions(SymbolDisplayMiscellaneousOptions.IncludeNullableReferenceTypeModifier); 9 | 10 | public static string ToFullyQualifiedDisplayString(this ISymbol symbol) => symbol.ToDisplayString(s_symbolFormat); 11 | 12 | // Copied from: https://github.com/dotnet/roslyn/blob/main/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Extensions/CompilationExtensions.cs 13 | /// 14 | /// Gets a type by its metadata name to use for code analysis within a . This method 15 | /// attempts to find the "best" symbol to use for code analysis, which is the symbol matching the first of the 16 | /// following rules. 17 | /// 18 | /// 19 | /// 20 | /// If only one type with the given name is found within the compilation and its referenced assemblies, that 21 | /// type is returned regardless of accessibility. 22 | /// 23 | /// 24 | /// If the current defines the symbol, that symbol is returned. 25 | /// 26 | /// 27 | /// If exactly one referenced assembly defines the symbol in a manner that makes it visible to the current 28 | /// , that symbol is returned. 29 | /// 30 | /// 31 | /// Otherwise, this method returns . 32 | /// 33 | /// 34 | /// 35 | /// The to consider for analysis. 36 | /// The fully-qualified metadata type name to find. 37 | /// The symbol to use for code analysis; otherwise, . 38 | public static INamedTypeSymbol? GetBestTypeByMetadataName(this Compilation compilation, string fullyQualifiedMetadataName) 39 | { 40 | // Try to get the unique type with this name, ignoring accessibility 41 | var type = compilation.GetTypeByMetadataName(fullyQualifiedMetadataName); 42 | 43 | // Otherwise, try to get the unique type with this name originally defined in 'compilation' 44 | type ??= compilation.Assembly.GetTypeByMetadataName(fullyQualifiedMetadataName); 45 | 46 | // Otherwise, try to get the unique accessible type with this name from a reference 47 | if (type is null) 48 | { 49 | foreach (var module in compilation.Assembly.Modules) 50 | { 51 | foreach (var referencedAssembly in module.ReferencedAssemblySymbols) 52 | { 53 | var currentType = referencedAssembly.GetTypeByMetadataName(fullyQualifiedMetadataName); 54 | if (currentType is null) 55 | continue; 56 | 57 | switch (currentType.GetResultantVisibility()) 58 | { 59 | case SymbolVisibility.Public: 60 | case SymbolVisibility.Internal when referencedAssembly.GivesAccessTo(compilation.Assembly): 61 | break; 62 | 63 | default: 64 | continue; 65 | } 66 | 67 | if (type is object) 68 | { 69 | // Multiple visible types with the same metadata name are present 70 | return null; 71 | } 72 | 73 | type = currentType; 74 | } 75 | } 76 | } 77 | 78 | return type; 79 | } 80 | 81 | // copied from https://github.com/dotnet/roslyn/blob/main/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Extensions/ISymbolExtensions.cs 82 | private static SymbolVisibility GetResultantVisibility(this ISymbol symbol) 83 | { 84 | // Start by assuming it's visible. 85 | SymbolVisibility visibility = SymbolVisibility.Public; 86 | 87 | switch (symbol.Kind) 88 | { 89 | case SymbolKind.Alias: 90 | // Aliases are uber private. They're only visible in the same file that they 91 | // were declared in. 92 | return SymbolVisibility.Private; 93 | 94 | case SymbolKind.Parameter: 95 | // Parameters are only as visible as their containing symbol 96 | return GetResultantVisibility(symbol.ContainingSymbol); 97 | 98 | case SymbolKind.TypeParameter: 99 | // Type Parameters are private. 100 | return SymbolVisibility.Private; 101 | } 102 | 103 | while (symbol != null && symbol.Kind != SymbolKind.Namespace) 104 | { 105 | switch (symbol.DeclaredAccessibility) 106 | { 107 | // If we see anything private, then the symbol is private. 108 | case Accessibility.NotApplicable: 109 | case Accessibility.Private: 110 | return SymbolVisibility.Private; 111 | 112 | // If we see anything internal, then knock it down from public to 113 | // internal. 114 | case Accessibility.Internal: 115 | case Accessibility.ProtectedAndInternal: 116 | visibility = SymbolVisibility.Internal; 117 | break; 118 | 119 | // For anything else (Public, Protected, ProtectedOrInternal), the 120 | // symbol stays at the level we've gotten so far. 121 | } 122 | 123 | symbol = symbol.ContainingSymbol; 124 | } 125 | 126 | return visibility; 127 | } 128 | 129 | // Copied from: https://github.com/dotnet/roslyn/blob/main/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Utilities/SymbolVisibility.cs 130 | #pragma warning disable CA1027 // Mark enums with FlagsAttribute 131 | private enum SymbolVisibility 132 | #pragma warning restore CA1027 // Mark enums with FlagsAttribute 133 | { 134 | Public = 0, 135 | Internal = 1, 136 | Private = 2, 137 | Friend = Internal, 138 | } 139 | } 140 | -------------------------------------------------------------------------------- /LoggingDecoratorGenerator/SourceGenerationHelper.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.CodeAnalysis; 2 | using System.CodeDom.Compiler; 3 | 4 | namespace Fineboym.Logging.Generator; 5 | 6 | internal static class SourceGenerationHelper 7 | { 8 | private const string LogEnabledBoolVar = "__logEnabled"; 9 | private const string DurationMetricEnabledBoolVar = "__metricEnabled"; 10 | private const string ElapsedTimeVar = "__elapsedTime"; 11 | 12 | private static readonly string s_generatedCodeAttribute = 13 | $"[global::System.CodeDom.Compiler.GeneratedCodeAttribute(" + 14 | $"\"{typeof(SourceGenerationHelper).Assembly.GetName().Name}\", " + 15 | $"\"{typeof(SourceGenerationHelper).Assembly.GetName().Version}\")]"; 16 | 17 | public static string GenerateLoggingDecoratorClass(DecoratorClass decoratorClass, bool stopwatchGetElapsedTimeAvailable) 18 | { 19 | using StringWriter stringWriter = new(); 20 | using IndentedTextWriter writer = new(stringWriter, " "); 21 | writer.WriteLine("#nullable enable"); 22 | writer.WriteLine(); 23 | writer.WriteLine($"namespace {decoratorClass.Namespace}"); 24 | writer.StartBlock(); 25 | 26 | string interfaceName = decoratorClass.InterfaceName; 27 | string loggerType = $"global::Microsoft.Extensions.Logging.ILogger<{interfaceName}>"; 28 | 29 | writer.WriteLine(s_generatedCodeAttribute); 30 | writer.WriteLine($"{decoratorClass.DeclaredAccessibility} sealed class {decoratorClass.ClassName} : {interfaceName}"); 31 | writer.StartBlock(); 32 | writer.WriteLine($"private readonly {loggerType} _logger;"); 33 | writer.WriteLine($"private readonly {interfaceName} _decorated;"); 34 | if (decoratorClass.NeedsDurationAsMetric) 35 | { 36 | writer.WriteLine("private readonly global::System.Diagnostics.Metrics.Histogram _methodDuration;"); 37 | } 38 | writer.WriteLineNoTabs(null); 39 | 40 | AppendConstructor(writer, decoratorClass, loggerType); 41 | 42 | foreach (MethodToGenerate methodToGenerate in decoratorClass.Methods) 43 | { 44 | writer.WriteLineNoTabs(null); 45 | 46 | if (methodToGenerate.LogLevel == null) 47 | { 48 | AppendPassThroughMethod(writer, methodToGenerate); 49 | } 50 | else 51 | { 52 | string loggerDelegateBeforeVariable = AppendLoggerMessageDefineForBeforeCall(writer, methodToGenerate); 53 | string loggerDelegateAfterVariable = AppendLoggerMessageDefineForAfterCall(writer, methodToGenerate, decoratorClass.DurationAsMetric); 54 | AppendMethod(writer, methodToGenerate, loggerDelegateBeforeVariable, loggerDelegateAfterVariable, stopwatchGetElapsedTimeAvailable, decoratorClass.DurationAsMetric); 55 | } 56 | } 57 | 58 | if (!stopwatchGetElapsedTimeAvailable && decoratorClass.SomeMethodMeasuresDuration) 59 | { 60 | writer.WriteLineNoTabs(null); 61 | AppendGetElapsedTimeSection(writer); 62 | } 63 | 64 | writer.EndBlock(); 65 | writer.EndBlock(); 66 | 67 | writer.Flush(); 68 | 69 | return stringWriter.ToString(); 70 | } 71 | 72 | private static void AppendGetElapsedTimeSection(IndentedTextWriter writer) 73 | { 74 | writer.WriteLine("private static readonly double s_timestampToTicks = global::System.TimeSpan.TicksPerSecond / (double)global::System.Diagnostics.Stopwatch.Frequency;"); 75 | writer.WriteLineNoTabs(null); 76 | writer.WriteLine("private static global::System.TimeSpan __GetElapsedTime__(long startTimestamp)"); 77 | writer.StartBlock(); 78 | writer.WriteLine("var end = global::System.Diagnostics.Stopwatch.GetTimestamp();"); 79 | writer.WriteLine("var timestampDelta = end - startTimestamp;"); 80 | writer.WriteLine("var ticks = (long)(s_timestampToTicks * timestampDelta);"); 81 | writer.WriteLine("return new global::System.TimeSpan(ticks);"); 82 | writer.EndBlock(); 83 | } 84 | 85 | private static void AppendConstructor(IndentedTextWriter writer, DecoratorClass decClass, string loggerType) 86 | { 87 | writer.WriteLine($"public {decClass.ClassName}("); 88 | writer.Indent++; 89 | writer.WriteLine($"{loggerType} logger,"); 90 | writer.Write($"{decClass.InterfaceName} decorated"); 91 | if (decClass.NeedsDurationAsMetric) 92 | { 93 | writer.WriteLine(","); 94 | writer.Write("global::System.Diagnostics.Metrics.IMeterFactory meterFactory"); 95 | } 96 | writer.WriteLine(")"); 97 | writer.Indent--; 98 | writer.StartBlock(); 99 | writer.WriteLine("_logger = logger;"); 100 | writer.WriteLine("_decorated = decorated;"); 101 | if (decClass.NeedsDurationAsMetric) 102 | { 103 | writer.WriteLine("var meterOptions = new global::System.Diagnostics.Metrics.MeterOptions(name: decorated.GetType().ToString());"); 104 | writer.WriteLine("var meter = meterFactory.Create(meterOptions);"); 105 | writer.WriteLine("_methodDuration = meter.CreateHistogram(name: \"logging_decorator.method.duration\", unit: \"s\", description: \"The duration of method invocations.\");"); 106 | } 107 | writer.EndBlock(); 108 | } 109 | 110 | private static void AppendPassThroughMethod(IndentedTextWriter writer, MethodToGenerate methodToGenerate) 111 | { 112 | var method = methodToGenerate.MethodSymbol; 113 | AppendMethodSignature(writer, methodToGenerate); 114 | writer.Indent++; 115 | writer.Write("=> "); 116 | AppendCallToDecoratedInstance(writer, method); 117 | writer.WriteLine(';'); 118 | writer.Indent--; 119 | } 120 | 121 | private static void AppendMethod( 122 | IndentedTextWriter writer, 123 | MethodToGenerate methodToGenerate, 124 | string loggerDelegateBeforeVariable, 125 | string loggerDelegateAfterVariable, 126 | bool stopwatchGetElapsedTimeAvailable, 127 | bool durationAsMetric) 128 | { 129 | IMethodSymbol method = methodToGenerate.MethodSymbol; 130 | bool awaitable = methodToGenerate.Awaitable; 131 | bool hasReturnValue = methodToGenerate.HasReturnValue; 132 | AppendMethodSignature(writer, methodToGenerate); 133 | writer.StartBlock(); 134 | 135 | AppendBeforeMethodSection(writer, loggerDelegateBeforeVariable, methodToGenerate, durationAsMetric); 136 | 137 | if (methodToGenerate.ExceptionTypeToLog != null) 138 | { 139 | if (hasReturnValue) 140 | { 141 | writer.WriteLine($"{(awaitable ? methodToGenerate.UnwrappedReturnType! : method.ReturnType).ToFullyQualifiedDisplayString()} __result;"); 142 | } 143 | 144 | writer.WriteLine("try"); 145 | writer.StartBlock(); 146 | } 147 | else if (hasReturnValue) 148 | { 149 | writer.Write("var "); 150 | } 151 | 152 | if (hasReturnValue) 153 | { 154 | writer.Write("__result = "); 155 | } 156 | 157 | if (awaitable) 158 | { 159 | writer.Write("await "); 160 | } 161 | 162 | AppendCallToDecoratedInstance(writer, method); 163 | 164 | if (awaitable) 165 | { 166 | writer.Write(".ConfigureAwait(false)"); 167 | } 168 | writer.WriteLine(';'); 169 | 170 | if (methodToGenerate.ExceptionTypeToLog != null) 171 | { 172 | writer.EndBlock(); 173 | writer.WriteLine($"catch ({methodToGenerate.ExceptionTypeToLog} __e)"); 174 | writer.StartBlock(); 175 | writer.WriteLine("global::Microsoft.Extensions.Logging.LoggerExtensions.Log("); 176 | writer.Indent++; 177 | writer.WriteLine("_logger,"); 178 | writer.WriteLine($"{methodToGenerate.ExceptionLogLevel},"); 179 | writer.WriteLine($"new global::Microsoft.Extensions.Logging.EventId({methodToGenerate.EventId}, {methodToGenerate.EventName}),"); 180 | writer.WriteLine("__e,"); 181 | writer.WriteLine($"\"{method.Name} failed\");"); 182 | writer.Indent--; 183 | writer.WriteLineNoTabs(null); 184 | writer.WriteLine("throw;"); 185 | writer.EndBlock(); 186 | } 187 | 188 | writer.WriteLineNoTabs(null); 189 | 190 | AppendAfterMethodSection(writer, loggerDelegateAfterVariable, methodToGenerate, stopwatchGetElapsedTimeAvailable, durationAsMetric); 191 | 192 | writer.EndBlock(); 193 | } 194 | 195 | private static void AppendCallToDecoratedInstance(IndentedTextWriter writer, IMethodSymbol method) 196 | { 197 | writer.Write($"_decorated.{method.Name}("); 198 | for (int i = 0; i < method.Parameters.Length; i++) 199 | { 200 | IParameterSymbol parameter = method.Parameters[i]; 201 | writer.Write($"{parameter.Name}"); 202 | if (i < method.Parameters.Length - 1) 203 | { 204 | writer.Write(", "); 205 | } 206 | } 207 | writer.Write(')'); 208 | } 209 | 210 | private static void AppendMethodSignature(IndentedTextWriter writer, MethodToGenerate methodToGenerate) 211 | { 212 | IMethodSymbol method = methodToGenerate.MethodSymbol; 213 | bool awaitable = methodToGenerate.Awaitable; 214 | bool passThrough = methodToGenerate.LogLevel == null; 215 | 216 | writer.Write($"public {(awaitable && !passThrough ? "async " : string.Empty)}{method.ReturnType.ToFullyQualifiedDisplayString()} {method.Name}("); 217 | for (int i = 0; i < method.Parameters.Length; i++) 218 | { 219 | IParameterSymbol parameter = method.Parameters[i]; 220 | writer.Write($"{parameter.Type.ToFullyQualifiedDisplayString()} {parameter.Name}"); 221 | if (i < method.Parameters.Length - 1) 222 | { 223 | writer.Write(", "); 224 | } 225 | } 226 | writer.WriteLine(")"); 227 | } 228 | 229 | private static void AppendBeforeMethodSection(IndentedTextWriter writer, string loggerDelegateBeforeVariable, MethodToGenerate method, bool durationAsMetric) 230 | { 231 | writer.WriteLine($"var {LogEnabledBoolVar} = _logger.IsEnabled({method.LogLevel});"); 232 | 233 | if (method.MeasureDuration) 234 | { 235 | if (durationAsMetric) 236 | { 237 | writer.WriteLine($"var {DurationMetricEnabledBoolVar} = _methodDuration.Enabled;"); 238 | } 239 | writer.WriteLine("long __startTimestamp = 0;"); 240 | } 241 | 242 | writer.WriteLineNoTabs(null); 243 | 244 | writer.WriteLine($"if ({LogEnabledBoolVar})"); 245 | writer.StartBlock(); 246 | 247 | writer.Write($"{loggerDelegateBeforeVariable}(_logger, "); 248 | foreach (Parameter loggedParameter in method.Parameters.Where(static p => p.IsLogged)) 249 | { 250 | writer.Write($"{loggedParameter.Symbol.Name}, "); 251 | } 252 | writer.WriteLine("null);"); 253 | 254 | const string startTimestampInit = "__startTimestamp = global::System.Diagnostics.Stopwatch.GetTimestamp();"; 255 | if (method.MeasureDuration && !durationAsMetric) 256 | { 257 | writer.WriteLine(startTimestampInit); 258 | } 259 | 260 | writer.EndBlock(); 261 | 262 | writer.WriteLineNoTabs(null); 263 | 264 | if (method.MeasureDuration && durationAsMetric) 265 | { 266 | writer.WriteLine($"if ({DurationMetricEnabledBoolVar})"); 267 | writer.StartBlock(); 268 | writer.WriteLine(startTimestampInit); 269 | writer.EndBlock(); 270 | 271 | writer.WriteLineNoTabs(null); 272 | } 273 | } 274 | 275 | private static void AppendAfterMethodSection( 276 | IndentedTextWriter writer, 277 | string loggerDelegateAfterVariable, 278 | MethodToGenerate methodToGenerate, 279 | bool stopwatchGetElapsedTimeAvailable, 280 | bool durationAsMetric) 281 | { 282 | if (methodToGenerate.MeasureDuration && durationAsMetric) 283 | { 284 | writer.WriteLine($"if ({DurationMetricEnabledBoolVar})"); 285 | writer.StartBlock(); 286 | AppendGetElapsedTime(writer, stopwatchGetElapsedTimeAvailable); 287 | writer.WriteLine($"_methodDuration.Record({ElapsedTimeVar}.TotalSeconds,"); 288 | writer.Indent++; 289 | writer.WriteLine($"new global::System.Collections.Generic.KeyValuePair(\"logging_decorator.method\", nameof({methodToGenerate.MethodSymbol.Name})));"); 290 | writer.Indent--; 291 | writer.EndBlock(); 292 | 293 | writer.WriteLineNoTabs(null); 294 | } 295 | 296 | writer.WriteLine($"if ({LogEnabledBoolVar})"); 297 | writer.StartBlock(); 298 | bool loggingDuration = methodToGenerate.MeasureDuration && !durationAsMetric; 299 | if (loggingDuration) 300 | { 301 | AppendGetElapsedTime(writer, stopwatchGetElapsedTimeAvailable); 302 | } 303 | 304 | writer.Write($"{loggerDelegateAfterVariable}(_logger, "); 305 | if (methodToGenerate.HasReturnValue && methodToGenerate.ReturnValueLogged) 306 | { 307 | writer.Write("__result, "); 308 | } 309 | 310 | if (loggingDuration) 311 | { 312 | writer.Write($"{ElapsedTimeVar}.TotalMilliseconds, "); 313 | } 314 | 315 | writer.WriteLine("null);"); 316 | 317 | writer.EndBlock(); 318 | 319 | if (methodToGenerate.HasReturnValue) 320 | { 321 | writer.WriteLineNoTabs(null); 322 | writer.WriteLine("return __result;"); 323 | } 324 | } 325 | 326 | private static void AppendGetElapsedTime(IndentedTextWriter writer, bool stopwatchGetElapsedTimeAvailable) 327 | { 328 | if (!stopwatchGetElapsedTimeAvailable) 329 | { 330 | writer.WriteLine($"var {ElapsedTimeVar} = __GetElapsedTime__(__startTimestamp);"); 331 | } 332 | else 333 | { 334 | writer.WriteLine($"var {ElapsedTimeVar} = global::System.Diagnostics.Stopwatch.GetElapsedTime(__startTimestamp);"); 335 | } 336 | } 337 | 338 | private static void StartBlock(this IndentedTextWriter writer) 339 | { 340 | writer.WriteLine('{'); 341 | writer.Indent++; 342 | } 343 | 344 | private static void EndBlock(this IndentedTextWriter writer) 345 | { 346 | writer.Indent--; 347 | writer.WriteLine('}'); 348 | } 349 | 350 | /// 351 | /// 352 | /// 353 | /// 354 | /// 355 | /// Variable name of logger delegate. 356 | private static string AppendLoggerMessageDefineForBeforeCall(IndentedTextWriter writer, MethodToGenerate method) 357 | { 358 | IMethodSymbol methodSymbol = method.MethodSymbol; 359 | string loggerVariable = $"s_before{method.UniqueName}"; 360 | AppendLoggerMessageDefineUpToFormatString( 361 | writer, 362 | method.Parameters.Where(static p => p.IsLogged).Select(static p => p.Symbol.Type.ToFullyQualifiedDisplayString()).ToArray(), 363 | loggerVariable, 364 | method); 365 | writer.Write($"\"Entering {methodSymbol.Name}"); 366 | for (int i = 0; i < method.Parameters.Count; i++) 367 | { 368 | if (i == 0) 369 | { 370 | writer.Write(" with parameters: "); 371 | } 372 | 373 | Parameter parameter = method.Parameters[i]; 374 | IParameterSymbol parameterSymbol = parameter.Symbol; 375 | if (parameter.IsLogged) 376 | { 377 | writer.Write($"{parameterSymbol.Name} = {{{parameterSymbol.Name}}}"); 378 | } 379 | else 380 | { 381 | writer.Write($"{parameterSymbol.Name} = [REDACTED]"); 382 | } 383 | 384 | if (i < method.Parameters.Count - 1) 385 | { 386 | writer.Write(", "); 387 | } 388 | } 389 | writer.WriteLine("\","); 390 | FinishByLogDefineOptions(writer); 391 | 392 | return loggerVariable; 393 | } 394 | 395 | private static string AppendLoggerMessageDefineForAfterCall(IndentedTextWriter writer, MethodToGenerate methodToGenerate, bool durationAsMetric) 396 | { 397 | IMethodSymbol method = methodToGenerate.MethodSymbol; 398 | bool hasReturnValue = methodToGenerate.HasReturnValue; 399 | bool awaitable = methodToGenerate.Awaitable; 400 | 401 | string loggerVariable = $"s_after{methodToGenerate.UniqueName}"; 402 | 403 | List types = new(); 404 | 405 | if (hasReturnValue && methodToGenerate.ReturnValueLogged) 406 | { 407 | ITypeSymbol returnType = awaitable ? methodToGenerate.UnwrappedReturnType! : method.ReturnType; 408 | types.Add(returnType.ToFullyQualifiedDisplayString()); 409 | } 410 | 411 | bool loggingDuration = methodToGenerate.MeasureDuration && !durationAsMetric; 412 | if (loggingDuration) 413 | { 414 | types.Add("double?"); 415 | } 416 | 417 | AppendLoggerMessageDefineUpToFormatString( 418 | writer, 419 | types, 420 | loggerVariable, 421 | methodToGenerate); 422 | 423 | writer.Write($"\"Method {method.Name} returned"); 424 | if (hasReturnValue) 425 | { 426 | if (methodToGenerate.ReturnValueLogged) 427 | { 428 | writer.Write(". Result = {result}"); 429 | } 430 | else 431 | { 432 | writer.Write(". Result = [REDACTED]"); 433 | } 434 | } 435 | 436 | if (loggingDuration) 437 | { 438 | writer.Write(". DurationInMilliseconds = {durationInMilliseconds}"); 439 | } 440 | 441 | writer.WriteLine("\","); 442 | FinishByLogDefineOptions(writer); 443 | 444 | return loggerVariable; 445 | } 446 | 447 | private static void AppendLoggerMessageDefineUpToFormatString( 448 | IndentedTextWriter writer, 449 | IReadOnlyList types, 450 | string loggerVariable, 451 | MethodToGenerate methodToGenerate) 452 | { 453 | writer.Write("private static readonly global::System.Action {loggerVariable}"); 460 | writer.Indent++; 461 | writer.Write("= global::Microsoft.Extensions.Logging.LoggerMessage.Define"); 462 | 463 | for (int i = 0; i < types.Count; i++) 464 | { 465 | if (i == 0) 466 | { 467 | writer.Write("<"); 468 | } 469 | 470 | writer.Write(types[i]); 471 | if (i < types.Count - 1) 472 | { 473 | writer.Write(", "); 474 | } 475 | else if (i == types.Count - 1) 476 | { 477 | writer.Write(">"); 478 | } 479 | } 480 | 481 | writer.WriteLine("("); 482 | writer.Indent++; 483 | writer.WriteLine($"{methodToGenerate.LogLevel},"); 484 | writer.WriteLine($"new global::Microsoft.Extensions.Logging.EventId({methodToGenerate.EventId}, {methodToGenerate.EventName}),"); 485 | } 486 | 487 | private static void FinishByLogDefineOptions(IndentedTextWriter writer) 488 | { 489 | writer.WriteLine("new global::Microsoft.Extensions.Logging.LogDefineOptions() { SkipEnabledCheck = true });"); 490 | writer.Indent -= 2; 491 | writer.WriteLineNoTabs(null); 492 | } 493 | } -------------------------------------------------------------------------------- /NuGetReadme.md: -------------------------------------------------------------------------------- 1 | ![image](https://github.com/DavidFineboym/LoggingDecoratorGenerator/actions/workflows/dotnet.yml/badge.svg?event=push) 2 | # Logging Decorator Source Generator 3 | 4 | Generates logger decorator class for an interface at compile time(*no runtime reflection*). Uses `Microsoft.Extensions.Logging.ILogger` to log and requires it in decorator class constructor. 5 | - Logs method parameters and return value(can omit secrets from log using `[NotLoggedAttribute]`) 6 | - Supports async methods 7 | - Supports log level, event id, and event name override through attribute 8 | - Can catch and log specific exceptions 9 | - Can measure method duration for performance reporting either as metric or log message 10 | - Follows [High-performance logging in .NET](https://learn.microsoft.com/en-us/dotnet/core/extensions/high-performance-logging) guidance 11 | 12 | ## Getting started 13 | 14 | Use `[DecorateWithLogger]` attribute in `Fineboym.Logging.Attributes` namespace on an interface. In Visual Studio you can see the generated code in Solution Explorer if you expand Dependencies->Analyzers->Fineboym.Logging.Generator. 15 | 16 | ### Prerequisites 17 | 18 | Latest version of Visual Studio 2022. 19 | 20 | ## Usage 21 | 22 | ```C# 23 | using Fineboym.Logging.Attributes; 24 | using Microsoft.Extensions.Logging; 25 | 26 | namespace SomeFolder.SomeSubFolder; 27 | 28 | // Default log level is Debug, applied to all methods. Can be changed through attribute's constructor. 29 | [DecorateWithLogger(ReportDurationAsMetric = false)] 30 | public interface ISomeService 31 | { 32 | int SomeMethod(DateTime someDateTime); 33 | 34 | // Override log level and event id. EventName is also supported. 35 | [LogMethod(Level = LogLevel.Information, EventId = 100, MeasureDuration = true)] 36 | Task SomeAsyncMethod(string? s); 37 | 38 | // By default, exceptions are not logged and there is no try-catch block around the method call. 39 | // If you want to log exceptions, use ExceptionToLog property. 40 | // Default log level for exceptions is Error and it can be changed through ExceptionLogLevel property. 41 | [LogMethod(ExceptionToLog = typeof(InvalidOperationException))] 42 | Task AnotherAsyncMethod(int x); 43 | 44 | // You can omit secrets or PII from logs using [NotLogged] attribute. 45 | [return: NotLogged] 46 | string GetMySecretString(string username, [NotLogged] string password); 47 | } 48 | ``` 49 | This will create a generated class named `SomeServiceLoggingDecorator` in the same namespace as the interface. 50 | You can see the generated code example for above interface on [GitHub README](https://github.com/DavidFineboym/LoggingDecoratorGenerator). 51 | 52 | #### Duration as metric 53 | Reporting duration of methods as a metric has an advantage of being separated from logs, so you can enable one without the other. 54 | For example, metrics can be collected ad-hoc by [dotnet-counters](https://learn.microsoft.com/en-us/dotnet/core/diagnostics/metrics-collection#view-metrics-with-dotnet-counters) tool or Prometheus. 55 | Only if `ReportDurationAsMetric` is `true`, then [IMeterFactory](https://learn.microsoft.com/en-us/dotnet/api/system.diagnostics.metrics.imeterfactory) is required in the decorator class constructor. 56 | For the example above, name of the meter will be `decorated.GetType().ToString()` where `ISomeService decorated` is constructor parameter to `SomeServiceLoggingDecorator`. 57 | Name of the instrument is always `"logging_decorator.method.duration"` and type is [Histogram\](https://learn.microsoft.com/en-us/dotnet/api/system.diagnostics.metrics.histogram-1). 58 | For more info, see [ASP.NET Core metrics](https://learn.microsoft.com/en-us/aspnet/core/log-mon/metrics/metrics), [.NET observability with OpenTelemetry](https://learn.microsoft.com/en-us/dotnet/core/diagnostics/observability-with-otel). 59 | 60 | ## Additional documentation 61 | 62 | If you use .NET dependency injection, then you can decorate your service interface. You can do it yourself or use [Scrutor](https://github.com/khellang/Scrutor). 63 | Here is an explanation [Adding decorated classes to the ASP.NET Core DI container using Scrutor](https://andrewlock.net/adding-decorated-classes-to-the-asp.net-core-di-container-using-scrutor). 64 | If you're not familiar with Source Generators, read [Source Generators](https://learn.microsoft.com/en-us/dotnet/csharp/roslyn-sdk/source-generators-overview). 65 | 66 | ## Limitations 67 | 68 | Currently it supports non-generic interfaces, only with methods as its members and up to 6 parameters in a method which is what 69 | [LoggerMessage.Define Method](https://learn.microsoft.com/en-us/dotnet/api/microsoft.extensions.logging.loggermessage.define?view=dotnet-plat-ext-7.0) 70 | supports. To work around 6 parameters limitation, you can encapsulate some 71 | parameters in a class or a struct or omit them from logging using `[NotLogged]` attribute. 72 | 73 | ## Feedback 74 | 75 | Please go to [GitHub repository](https://github.com/DavidFineboym/LoggingDecoratorGenerator) for feedback. Feel free to open issues for questions, bugs, and improvements and I'll try to address them as soon as I can. Thank you. -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | ![image](https://github.com/DavidFineboym/LoggingDecoratorGenerator/actions/workflows/dotnet.yml/badge.svg?event=push) 2 | # Logging Decorator Source Generator 3 | 4 | Generates logger decorator class for an interface at compile time(*no runtime reflection*). Uses `Microsoft.Extensions.Logging.ILogger` to log and requires it in decorator class constructor. 5 | - Logs method parameters and return value(can omit secrets from log using `[NotLoggedAttribute]`) 6 | - Supports async methods 7 | - Supports log level, event id, and event name override through attribute 8 | - Can catch and log specific exceptions 9 | - Can measure method duration for performance reporting either as metric or log message 10 | - Follows [High-performance logging in .NET](https://learn.microsoft.com/en-us/dotnet/core/extensions/high-performance-logging) guidance 11 | 12 | ## Getting started 13 | 14 | Install the package from [NuGet](https://www.nuget.org/packages/Fineboym.Logging.Generator) 15 | 16 | Use `[DecorateWithLogger]` attribute in `Fineboym.Logging.Attributes` namespace on an interface. In Visual Studio you can see the generated code in Solution Explorer if you expand Dependencies->Analyzers->Fineboym.Logging.Generator. 17 | 18 | ### Prerequisites 19 | 20 | Latest version of Visual Studio 2022. 21 | 22 | ## Usage 23 | 24 | ```C# 25 | using Fineboym.Logging.Attributes; 26 | using Microsoft.Extensions.Logging; 27 | 28 | namespace SomeFolder.SomeSubFolder; 29 | 30 | // Default log level is Debug, applied to all methods. Can be changed through attribute's constructor. 31 | [DecorateWithLogger(ReportDurationAsMetric = false)] 32 | public interface ISomeService 33 | { 34 | int SomeMethod(DateTime someDateTime); 35 | 36 | // Override log level and event id. EventName is also supported. 37 | [LogMethod(Level = LogLevel.Information, EventId = 100, MeasureDuration = true)] 38 | Task SomeAsyncMethod(string? s); 39 | 40 | // By default, exceptions are not logged and there is no try-catch block around the method call. 41 | // If you want to log exceptions, use ExceptionToLog property. 42 | // Default log level for exceptions is Error and it can be changed through ExceptionLogLevel property. 43 | [LogMethod(ExceptionToLog = typeof(InvalidOperationException))] 44 | Task AnotherAsyncMethod(int x); 45 | 46 | // You can omit secrets or PII from logs using [NotLogged] attribute. 47 | [return: NotLogged] 48 | string GetMySecretString(string username, [NotLogged] string password); 49 | } 50 | ``` 51 | This will create a generated class named `SomeServiceLoggingDecorator` in the same namespace as the interface. 52 |
Click to see the generated code 53 | 54 | ```C# 55 | #nullable enable 56 | 57 | namespace SomeFolder.SomeSubFolder 58 | { 59 | [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Fineboym.Logging.Generator", "1.10.0.0")] 60 | public sealed class SomeServiceLoggingDecorator : ISomeService 61 | { 62 | private readonly global::Microsoft.Extensions.Logging.ILogger _logger; 63 | private readonly ISomeService _decorated; 64 | 65 | public SomeServiceLoggingDecorator( 66 | global::Microsoft.Extensions.Logging.ILogger logger, 67 | ISomeService decorated) 68 | { 69 | _logger = logger; 70 | _decorated = decorated; 71 | } 72 | 73 | private static readonly global::System.Action s_beforeSomeMethod 74 | = global::Microsoft.Extensions.Logging.LoggerMessage.Define( 75 | global::Microsoft.Extensions.Logging.LogLevel.Debug, 76 | new global::Microsoft.Extensions.Logging.EventId(15022964, nameof(SomeMethod)), 77 | "Entering SomeMethod with parameters: someDateTime = {someDateTime}", 78 | new global::Microsoft.Extensions.Logging.LogDefineOptions() { SkipEnabledCheck = true }); 79 | 80 | private static readonly global::System.Action s_afterSomeMethod 81 | = global::Microsoft.Extensions.Logging.LoggerMessage.Define( 82 | global::Microsoft.Extensions.Logging.LogLevel.Debug, 83 | new global::Microsoft.Extensions.Logging.EventId(15022964, nameof(SomeMethod)), 84 | "Method SomeMethod returned. Result = {result}", 85 | new global::Microsoft.Extensions.Logging.LogDefineOptions() { SkipEnabledCheck = true }); 86 | 87 | public int SomeMethod(global::System.DateTime someDateTime) 88 | { 89 | var __logEnabled = _logger.IsEnabled(global::Microsoft.Extensions.Logging.LogLevel.Debug); 90 | 91 | if (__logEnabled) 92 | { 93 | s_beforeSomeMethod(_logger, someDateTime, null); 94 | } 95 | 96 | var __result = _decorated.SomeMethod(someDateTime); 97 | 98 | if (__logEnabled) 99 | { 100 | s_afterSomeMethod(_logger, __result, null); 101 | } 102 | 103 | return __result; 104 | } 105 | 106 | private static readonly global::System.Action s_beforeSomeAsyncMethod 107 | = global::Microsoft.Extensions.Logging.LoggerMessage.Define( 108 | global::Microsoft.Extensions.Logging.LogLevel.Information, 109 | new global::Microsoft.Extensions.Logging.EventId(100, nameof(SomeAsyncMethod)), 110 | "Entering SomeAsyncMethod with parameters: s = {s}", 111 | new global::Microsoft.Extensions.Logging.LogDefineOptions() { SkipEnabledCheck = true }); 112 | 113 | private static readonly global::System.Action s_afterSomeAsyncMethod 114 | = global::Microsoft.Extensions.Logging.LoggerMessage.Define( 115 | global::Microsoft.Extensions.Logging.LogLevel.Information, 116 | new global::Microsoft.Extensions.Logging.EventId(100, nameof(SomeAsyncMethod)), 117 | "Method SomeAsyncMethod returned. Result = {result}. DurationInMilliseconds = {durationInMilliseconds}", 118 | new global::Microsoft.Extensions.Logging.LogDefineOptions() { SkipEnabledCheck = true }); 119 | 120 | public async global::System.Threading.Tasks.Task SomeAsyncMethod(string? s) 121 | { 122 | var __logEnabled = _logger.IsEnabled(global::Microsoft.Extensions.Logging.LogLevel.Information); 123 | long __startTimestamp = 0; 124 | 125 | if (__logEnabled) 126 | { 127 | s_beforeSomeAsyncMethod(_logger, s, null); 128 | __startTimestamp = global::System.Diagnostics.Stopwatch.GetTimestamp(); 129 | } 130 | 131 | var __result = await _decorated.SomeAsyncMethod(s).ConfigureAwait(false); 132 | 133 | if (__logEnabled) 134 | { 135 | var __elapsedTime = global::System.Diagnostics.Stopwatch.GetElapsedTime(__startTimestamp); 136 | s_afterSomeAsyncMethod(_logger, __result, __elapsedTime.TotalMilliseconds, null); 137 | } 138 | 139 | return __result; 140 | } 141 | 142 | private static readonly global::System.Action s_beforeAnotherAsyncMethod 143 | = global::Microsoft.Extensions.Logging.LoggerMessage.Define( 144 | global::Microsoft.Extensions.Logging.LogLevel.Debug, 145 | new global::Microsoft.Extensions.Logging.EventId(2017861863, nameof(AnotherAsyncMethod)), 146 | "Entering AnotherAsyncMethod with parameters: x = {x}", 147 | new global::Microsoft.Extensions.Logging.LogDefineOptions() { SkipEnabledCheck = true }); 148 | 149 | private static readonly global::System.Action s_afterAnotherAsyncMethod 150 | = global::Microsoft.Extensions.Logging.LoggerMessage.Define( 151 | global::Microsoft.Extensions.Logging.LogLevel.Debug, 152 | new global::Microsoft.Extensions.Logging.EventId(2017861863, nameof(AnotherAsyncMethod)), 153 | "Method AnotherAsyncMethod returned. Result = {result}", 154 | new global::Microsoft.Extensions.Logging.LogDefineOptions() { SkipEnabledCheck = true }); 155 | 156 | public async global::System.Threading.Tasks.Task AnotherAsyncMethod(int x) 157 | { 158 | var __logEnabled = _logger.IsEnabled(global::Microsoft.Extensions.Logging.LogLevel.Debug); 159 | 160 | if (__logEnabled) 161 | { 162 | s_beforeAnotherAsyncMethod(_logger, x, null); 163 | } 164 | 165 | string __result; 166 | try 167 | { 168 | __result = await _decorated.AnotherAsyncMethod(x).ConfigureAwait(false); 169 | } 170 | catch (global::System.InvalidOperationException __e) 171 | { 172 | global::Microsoft.Extensions.Logging.LoggerExtensions.Log( 173 | _logger, 174 | global::Microsoft.Extensions.Logging.LogLevel.Error, 175 | new global::Microsoft.Extensions.Logging.EventId(2017861863, nameof(AnotherAsyncMethod)), 176 | __e, 177 | "AnotherAsyncMethod failed"); 178 | 179 | throw; 180 | } 181 | 182 | if (__logEnabled) 183 | { 184 | s_afterAnotherAsyncMethod(_logger, __result, null); 185 | } 186 | 187 | return __result; 188 | } 189 | 190 | private static readonly global::System.Action s_beforeGetMySecretString 191 | = global::Microsoft.Extensions.Logging.LoggerMessage.Define( 192 | global::Microsoft.Extensions.Logging.LogLevel.Debug, 193 | new global::Microsoft.Extensions.Logging.EventId(1921103492, nameof(GetMySecretString)), 194 | "Entering GetMySecretString with parameters: username = {username}, password = [REDACTED]", 195 | new global::Microsoft.Extensions.Logging.LogDefineOptions() { SkipEnabledCheck = true }); 196 | 197 | private static readonly global::System.Action s_afterGetMySecretString 198 | = global::Microsoft.Extensions.Logging.LoggerMessage.Define( 199 | global::Microsoft.Extensions.Logging.LogLevel.Debug, 200 | new global::Microsoft.Extensions.Logging.EventId(1921103492, nameof(GetMySecretString)), 201 | "Method GetMySecretString returned. Result = [REDACTED]", 202 | new global::Microsoft.Extensions.Logging.LogDefineOptions() { SkipEnabledCheck = true }); 203 | 204 | public string GetMySecretString(string username, string password) 205 | { 206 | var __logEnabled = _logger.IsEnabled(global::Microsoft.Extensions.Logging.LogLevel.Debug); 207 | 208 | if (__logEnabled) 209 | { 210 | s_beforeGetMySecretString(_logger, username, null); 211 | } 212 | 213 | var __result = _decorated.GetMySecretString(username, password); 214 | 215 | if (__logEnabled) 216 | { 217 | s_afterGetMySecretString(_logger, null); 218 | } 219 | 220 | return __result; 221 | } 222 | } 223 | } 224 | 225 | ``` 226 | 227 |
228 | 229 | #### Duration as metric 230 | Reporting duration of methods as a metric has an advantage of being separated from logs, so you can enable one without the other. 231 | For example, metrics can be collected ad-hoc by [dotnet-counters](https://learn.microsoft.com/en-us/dotnet/core/diagnostics/metrics-collection#view-metrics-with-dotnet-counters) tool or Prometheus.
232 | Only if `ReportDurationAsMetric` is `true`, then [IMeterFactory](https://learn.microsoft.com/en-us/dotnet/api/system.diagnostics.metrics.imeterfactory) is required in the decorator class constructor. 233 | For the example above, name of the meter will be `decorated.GetType().ToString()` where `ISomeService decorated` is constructor parameter to `SomeServiceLoggingDecorator`. 234 | Name of the instrument is always `"logging_decorator.method.duration"` and type is [Histogram\](https://learn.microsoft.com/en-us/dotnet/api/system.diagnostics.metrics.histogram-1).
235 | For more info, see [ASP.NET Core metrics](https://learn.microsoft.com/en-us/aspnet/core/log-mon/metrics/metrics), [.NET observability with OpenTelemetry](https://learn.microsoft.com/en-us/dotnet/core/diagnostics/observability-with-otel). 236 | 237 | ## Additional documentation 238 | 239 | If you use .NET dependency injection, then you can decorate your service interface. You can do it yourself or use [Scrutor](https://github.com/khellang/Scrutor). 240 | Here is an explanation [Adding decorated classes to the ASP.NET Core DI container using Scrutor](https://andrewlock.net/adding-decorated-classes-to-the-asp.net-core-di-container-using-scrutor).
241 | If you're not familiar with Source Generators, read [Source Generators](https://learn.microsoft.com/en-us/dotnet/csharp/roslyn-sdk/source-generators-overview). 242 | 243 | ## Limitations 244 | 245 | Currently it supports non-generic interfaces, only with methods as its members and up to 6 parameters in a method which is what 246 | [LoggerMessage.Define Method](https://learn.microsoft.com/en-us/dotnet/api/microsoft.extensions.logging.loggermessage.define?view=dotnet-plat-ext-7.0) 247 | supports. To work around 6 parameters limitation, you can encapsulate some 248 | parameters in a class or a struct or omit them from logging using `[NotLogged]` attribute. 249 | 250 | ## Feedback 251 | 252 | Feel free to open issues here for questions, bugs, and improvements and I'll try to address them as soon as I can. Thank you. -------------------------------------------------------------------------------- /icon.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/DavidFineboym/LoggingDecoratorGenerator/4c9e434bed76781af37572a2de587ebf1437912c/icon.png --------------------------------------------------------------------------------