RSCG – AOP.Logging.SourceGenerator

RSCG – AOP.Logging.SourceGenerator
 
 

name AOP.Logging.SourceGenerator
nuget https://www.nuget.org/packages/AOP.Logging.SourceGenerator/
link https://github.com/dborgards/aop.logging.net
author Dietmar Borgards

Logging methods by generating new ones

 

This is how you can use AOP.Logging.SourceGenerator .

The code that you start with is


<Project Sdk="Microsoft.NET.Sdk">

  <PropertyGroup>
    <OutputType>Exe</OutputType>
    <TargetFramework>net10.0</TargetFramework>
    <ImplicitUsings>enable</ImplicitUsings>
    <Nullable>enable</Nullable>
  </PropertyGroup>

  <ItemGroup>
    <PackageReference Include="AOP.Logging.Core" Version="1.4.0" />
    <PackageReference Include="AOP.Logging.SourceGenerator" Version="1.4.0">
      <PrivateAssets>all</PrivateAssets>
      <IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
    </PackageReference>
    <PackageReference Include="Microsoft.Extensions.Logging.Console" Version="10.0.11" />
  </ItemGroup>

	<PropertyGroup>
		<EmitCompilerGeneratedFiles>true</EmitCompilerGeneratedFiles>
		<CompilerGeneratedFilesOutputPath>$(BaseIntermediateOutputPath)\GX</CompilerGeneratedFilesOutputPath>
	</PropertyGroup>

</Project>


The code that you will use is


using AOP.Logging.Core.Configuration;
using AOP.Logging.Core.Logging;
using DemoLog;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;

#region this is usually done by DI
using ILoggerFactory factory = LoggerFactory.Create(builder => builder.AddConsole());
var logger = factory.CreateLogger<DefaultMethodLogger>();
IOptions<AopLoggingOptions> options = Options.Create(new AopLoggingOptions());
DefaultMethodLogger defaultMethodLogger = new(logger,options);
#endregion

Person p = new();
p.SetMethodLogger(defaultMethodLogger);
p.FirstName = "Andrei";
p.LastName = "Ignat";
Console.WriteLine (p.Name());
Console.WriteLine (await p.WithMiddleNameLogged("G"));



using AOP.Logging.Core.Attributes;
using Microsoft.Extensions.Logging;

namespace DemoLog;

[LogClass]
internal partial class Person
{
    public string FirstName { get; set; } = string.Empty;
    public string LastName { get; set; } = string.Empty; 
    [LogMethod(LogLevel.Warning)]
    public string NameCore() => $"{FirstName} {LastName}";

    [LogMethod(LogLevel.Warning)]
    private async Task<string> WithMiddleName(string middleName)
    {
        await Task.Delay(50);
        return $"{FirstName} {middleName} {LastName}";
    }
}


 

The code that is generated is

// <auto-generated/>
#nullable enable

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Threading.Tasks;
using Microsoft.Extensions.Logging;
using AOP.Logging.Core.Interfaces;

namespace DemoLog
{
    partial class Person
    {
        private IMethodLogger? __methodLogger;

        /// <summary>
        /// Sets the method logger for AOP logging.
        /// This is typically called by the DI container.
        /// </summary>
        public void SetMethodLogger(IMethodLogger methodLogger)
        {
            __methodLogger = methodLogger;
        }

        /// <summary>
        /// Logging wrapper for Name.
        /// </summary>
        public string Name()
        {
            if (__methodLogger != null)
            {
                var __parameters = new Dictionary<string, object?>();
                __methodLogger.LogEntry("Person", "Name", __parameters, LogLevel.Warning);
            }

            var __stopwatch = Stopwatch.StartNew();
            try
            {
                var __result = NameCore();
                __stopwatch.Stop();
                if (__methodLogger != null)
                {
                    __methodLogger.LogExit("Person", "Name", __result, __stopwatch.ElapsedMilliseconds, LogLevel.Warning);
                }
                return __result;
            }
            catch (Exception __ex)
            {
                __stopwatch.Stop();
                if (__methodLogger != null)
                {
                    __methodLogger.LogException("Person", "Name", __ex, __stopwatch.ElapsedMilliseconds, LogLevel.Error);
                }
                throw;
            }
        }

        /// <summary>
        /// Logging wrapper for WithMiddleNameLogged.
        /// </summary>
        public async global::System.Threading.Tasks.Task<string> WithMiddleNameLogged(string middleName)
        {
            if (__methodLogger != null)
            {
                var __parameters = new Dictionary<string, object?>
                {
                    { "middleName", middleName }
                };
                __methodLogger.LogEntry("Person", "WithMiddleNameLogged", __parameters, LogLevel.Warning);
            }

            var __stopwatch = Stopwatch.StartNew();
            try
            {
                var __result = await WithMiddleName(middleName);
                __stopwatch.Stop();
                if (__methodLogger != null)
                {
                    __methodLogger.LogExit("Person", "WithMiddleNameLogged", __result, __stopwatch.ElapsedMilliseconds, LogLevel.Warning);
                }
                return __result;
            }
            catch (Exception __ex)
            {
                __stopwatch.Stop();
                if (__methodLogger != null)
                {
                    __methodLogger.LogException("Person", "WithMiddleNameLogged", __ex, __stopwatch.ElapsedMilliseconds, LogLevel.Error);
                }
                throw;
            }
        }

    }
}

Code and pdf at

https://ignatandrei.github.io/RSCG_Examples/v2/docs/AOP.Logging.SourceGenerator


Posted

in

,

by

Tags: