Skip to content

Commit

Permalink
Fix custom logging support.
Browse files Browse the repository at this point in the history
  • Loading branch information
xaviersolau committed Mar 8, 2024
1 parent bfb3014 commit 7c1a425
Show file tree
Hide file tree
Showing 14 changed files with 164 additions and 17 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ public static IServiceCollection AddCSharpToolsGenerator(this IServiceCollection
throw new ArgumentNullException(nameof(services));
}

services.Add(ServiceDescriptor.Transient(typeof(IGeneratorLogger<>), typeof(GeneratorLogger<>)));
services.Add(ServiceDescriptor.Transient(typeof(IGeneratorLogger<>), typeof(InjectedGeneratorLogger<>)));

return services
.AddSingleton<
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,84 @@
// ----------------------------------------------------------------------
// <copyright file="InjectedGeneratorLogger.cs" company="Xavier Solau">
// Copyright © 2021 Xavier Solau.
// Licensed under the MIT license.
// See LICENSE file in the project root for full license information.
// </copyright>
// ----------------------------------------------------------------------

using SoloX.GeneratorTools.Core.Utils;
using System;

namespace SoloX.GeneratorTools.Core.CSharp.Extensions.Utils
{
/// <summary>
/// Injected GeneratorLogger wrapper that will use the injected IGeneratorLoggerFactory to make the target IGeneratorLogger.
/// </summary>
/// <typeparam name="TType"></typeparam>
public class InjectedGeneratorLogger<TType> : IGeneratorLogger<TType>
{
private readonly IGeneratorLogger<TType> logger;

/// <summary>
/// Setup GeneratorLogger through IoC.
/// </summary>
/// <param name="generatorLoggerFactory"></param>
public InjectedGeneratorLogger(IGeneratorLoggerFactory generatorLoggerFactory)
{
if (generatorLoggerFactory == null)
{
throw new ArgumentNullException(nameof(generatorLoggerFactory));
}

this.logger = generatorLoggerFactory.CreateLogger<TType>();
}

/// <inheritdoc/>
public void LogDebug(string message)
{
this.logger.LogDebug(message);
}

/// <inheritdoc/>
public void LogDebug(Exception exception, string message)
{
this.logger.LogDebug(exception, message);
}

/// <inheritdoc/>
public void LogError(string message)
{
this.logger.LogError(message);
}

/// <inheritdoc/>
public void LogError(Exception exception, string message)
{
this.logger.LogError(exception, message);
}

/// <inheritdoc/>
public void LogInformation(string message)
{
this.logger.LogInformation(message);
}

/// <inheritdoc/>
public void LogInformation(Exception exception, string message)
{
this.logger.LogInformation(exception, message);
}

/// <inheritdoc/>
public void LogWarning(string message)
{
this.logger.LogWarning(message);
}

/// <inheritdoc/>
public void LogWarning(Exception exception, string message)
{
this.logger.LogWarning(exception, message);
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -130,7 +130,8 @@ public IEnumerable<IGeneratedItem> Generate(IEnumerable<ICSharpFile> files)
var generatorWalker = new AutomatedWalker(
writer,
this.pattern,
strategy);
strategy,
this.logger);

generatorWalker.Visit(this.pattern.SyntaxNodeProvider.SyntaxNode.SyntaxTree.GetRoot());
});
Expand Down Expand Up @@ -166,7 +167,8 @@ public IEnumerable<IGeneratedItem> Generate(IEnumerable<ICSharpFile> files)
var generatorWalker = new AutomatedWalker(
writer,
this.pattern,
strategy);
strategy,
this.logger);

generatorWalker.Visit(this.pattern.SyntaxNodeProvider.SyntaxNode.SyntaxTree.GetRoot());
});
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@
using SoloX.GeneratorTools.Core.CSharp.Generator.ReplacePattern;
using SoloX.GeneratorTools.Core.CSharp.Model;
using SoloX.GeneratorTools.Core.CSharp.Utils;
using SoloX.GeneratorTools.Core.Utils;

namespace SoloX.GeneratorTools.Core.CSharp.Generator.Impl.Walker
{
Expand All @@ -26,7 +27,7 @@ internal class AutomatedWalker : CSharpSyntaxWalker

private readonly TextWriter textWriter;
private readonly IDeclaration<SyntaxNode> pattern;

private readonly IGeneratorLogger logger;
private readonly Stack<IReplacePatternHandler> strategiesReplacePatternHandlers = new Stack<IReplacePatternHandler>();

private class StrategyCount
Expand All @@ -50,13 +51,16 @@ public StrategyCount(IAutomatedStrategy strategy)
/// <param name="textWriter">The writer where to write generated code.</param>
/// <param name="pattern">The pattern reference.</param>
/// <param name="strategy">Automated strategy that manage repeat feature.</param>
/// <param name="logger">logger instance.</param>
public AutomatedWalker(
TextWriter textWriter,
IDeclaration<SyntaxNode> pattern,
IAutomatedStrategy strategy)
IAutomatedStrategy strategy,
IGeneratorLogger logger)
{
this.textWriter = textWriter;
this.pattern = pattern;
this.logger = logger;
this.strategies = new Stack<StrategyCount>();
this.strategies.Push(new StrategyCount(strategy));

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,8 @@ internal override ISyntaxNodeProvider<TypeParameterListSyntax> GetTypeParameterL

internal override void Load(AGenericDeclaration<TNode> declaration, IDeclarationResolver resolver)
{
this.logger.LogDebug($"Loading {declaration.FullName} from assembly Metadata");

var assemblyPath = declaration.Location;

using var portableExecutableReader = new PEReader(File.OpenRead(assemblyPath));
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -35,13 +35,17 @@ internal override void Load(AGenericDeclaration<TNode> declaration, IDeclaration
{
try
{
this.logger.LogDebug($"Loading {declaration.FullName} from source code");

LoadGenericParameters(declaration);
LoadExtends(declaration, resolver);
LoadMembers(declaration, resolver);
LoadAttributes(declaration, resolver);
}
catch
catch (Exception ex)
{
this.logger.LogError($"Error while loading {declaration.FullName}: {ex.Message}");

// Make sure all collection are assigned.
declaration.GenericParameters ??= Array.Empty<IGenericParameterDeclaration>();
declaration.Extends ??= Array.Empty<IDeclarationUse<SyntaxNode>>();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -182,6 +182,8 @@ internal static IDeclarationUse<SyntaxNode> GetDeclarationUseFrom(

internal override void Load(AGenericDeclaration<TNode> declaration, IDeclarationResolver resolver)
{
this.logger.LogDebug($"Loading {declaration.FullName} from reflection");

LoadGenericParameters(declaration);
LoadExtends(declaration, resolver);
LoadMembers(declaration, resolver);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -69,6 +69,8 @@ public CSharpWorkspace(IGeneratorLogger<CSharpWorkspace> logger, ICSharpWorkspac
/// <inheritdoc/>
public void RegisterCompilation(Compilation compilation)
{
this.logger.LogDebug("Register Compilation");

if (compilation == null)
{
throw new ArgumentNullException(nameof(compilation));
Expand Down Expand Up @@ -115,6 +117,8 @@ public void RegisterCompilation(Compilation compilation)
/// <inheritdoc/>
public ICSharpFile RegisterFile(string file, IGlobalUsingDirectives? globalUsing)
{
this.logger.LogDebug($"Register file {file}");

if (globalUsing == null)
{
globalUsing = new CSharpGlobalUsing();
Expand All @@ -138,6 +142,8 @@ public ICSharpFile RegisterFile(string file, IGlobalUsingDirectives? globalUsing
/// <inheritdoc/>
public ICSharpProject RegisterProject(string projectFile)
{
this.logger.LogDebug($"Register project {projectFile}");

// Resolve the full path
projectFile = Path.GetFullPath(projectFile);
if (!this.projects.TryGetValue(projectFile, out var csProject))
Expand All @@ -161,6 +167,8 @@ public ICSharpAssembly RegisterAssembly(Assembly assembly)
return null;
}

this.logger.LogDebug($"Register assembly {assembly.FullName}");

var assemblyFileName = Path.GetFileName(assembly.FullName);

if (!this.assemblies.TryGetValue(assemblyFileName, out var csAssembly))
Expand All @@ -184,6 +192,8 @@ public ICSharpAssembly RegisterAssemblyTypes(Assembly assembly, IEnumerable<Type
return null;
}

this.logger.LogDebug($"Register types from assembly {assembly.FullName}");

var assemblyFileName = Path.GetFileName(assembly.FullName);

if (!this.assemblies.TryGetValue(assemblyFileName, out var csAssembly))
Expand All @@ -207,6 +217,8 @@ public ICSharpMetadataAssembly RegisterMetadataAssembly(string assemblyFile)
return null;
}

this.logger.LogDebug($"Register assembly file {assemblyFile}");

var assemblyFileName = Path.GetFileName(assemblyFile);

if (!this.metadataAssemblies.TryGetValue(assemblyFileName, out var csMetadataAssembly))
Expand All @@ -229,10 +241,13 @@ public ICSharpMetadataAssembly RegisterMetadataAssembly(string assemblyFile)
/// <inheritdoc/>
public IDeclarationResolver DeepLoad()
{
this.logger.LogDebug($"Deep load workspace");

var declarations = this.Assemblies.SelectMany(a => a.Declarations)
.Concat(this.MetadataAssemblies.SelectMany(f => f.Declarations))
.Concat(this.Files.SelectMany(f => f.Declarations))
.Concat(this.SyntaxTrees.SelectMany(s => s.Declarations));

var resolver = new DeclarationResolver(declarations);

resolver.Load(this.logger);
Expand Down
16 changes: 14 additions & 2 deletions src/tools/SoloX.GeneratorTools.Generator/Impl/ToolsGenerator.cs
Original file line number Diff line number Diff line change
Expand Up @@ -42,32 +42,40 @@ public void Generate(string projectFile)
{
var projectFolder = Path.GetDirectoryName(projectFile);

this.logger.LogInformation($"Loading {Path.GetFileName(projectFile)}...");
this.logger.LogInformation($"Loading {Path.GetFileName(projectFile)}");

var workspace = this.workspaceFactory.CreateWorkspace();

var project = workspace.RegisterProject(projectFile);

var locator = new RelativeLocator(projectFolder, project.RootNameSpace, suffix: "Impl");
var fileGenerator = new FileWriter(".generated.cs");
var fileGenerator = new FileWriter(".generated.cs", file => this.logger.LogInformation($"Generated file: {file}"));

// Generate with a filter on current project interface declarations.
this.Generate(
workspace,
locator,
fileGenerator,
project.Files);

this.logger.LogInformation($"Generation completed");
}

internal void Generate(ICSharpWorkspace workspace, RelativeLocator locator, IWriter fileGenerator, IEnumerable<ICSharpFile> files)
{
this.logger.LogInformation($"Registering patterns");

workspace.RegisterFile(GetContentFile("./Patterns/Itf/IObjectPattern.cs"));
workspace.RegisterFile(GetContentFile("./Patterns/Itf/IFactoryPattern.cs"));
workspace.RegisterFile(GetContentFile("./Patterns/Impl/FactoryPattern.cs"));
workspace.RegisterFile(GetContentFile("./Patterns/Impl/ObjectPattern.cs"));

this.logger.LogInformation($"Deep loading");

var resolver = workspace.DeepLoad();

this.logger.LogInformation($"Generating Factory interfaces");

var generator1 = new AutomatedGenerator(
fileGenerator,
locator,
Expand All @@ -77,6 +85,8 @@ internal void Generate(ICSharpWorkspace workspace, RelativeLocator locator, IWri

var generatedItems1 = generator1.Generate(files);

this.logger.LogInformation($"Generating Factory implementations");

var generator2 = new AutomatedGenerator(
fileGenerator,
locator,
Expand All @@ -86,6 +96,8 @@ internal void Generate(ICSharpWorkspace workspace, RelativeLocator locator, IWri

var generatedItems2 = generator2.Generate(files);

this.logger.LogInformation($"Generating Object implementations");

var generator3 = new AutomatedGenerator(
fileGenerator,
locator,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ public static class ToolsGeneratorExtensions
public static IServiceCollection AddToolsGenerator(this IServiceCollection services, ILoggerFactory loggerFactory = null)
{
return services
.AddCSharpToolsGenerator()
.AddCSharpToolsGenerator(loggerFactory)
.AddTransient<IToolsGenerator, ToolsGenerator>();
}
}
Expand Down
29 changes: 24 additions & 5 deletions src/tools/SoloX.GeneratorTools.Tools/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
// </copyright>
// ----------------------------------------------------------------------

using System;
using System.Globalization;
using System.IO;
using Microsoft.Extensions.Configuration;
Expand All @@ -19,10 +20,13 @@ namespace SoloX.GeneratorTools.Tools
/// <summary>
/// Program entry point class.
/// </summary>
public class Program
#pragma warning disable CA1063 // Implement IDisposable Correctly
public class Program : IDisposable
#pragma warning restore CA1063 // Implement IDisposable Correctly
{
private readonly ILogger<Program> logger;
private readonly IConfiguration configuration;
private readonly ILoggerFactory generatorLoggerFactory;

/// <summary>
/// Initializes a new instance of the <see cref="Program"/> class.
Expand All @@ -34,21 +38,24 @@ public Program(IConfiguration configuration)

var fileLogger = new LoggerConfiguration()
.WriteTo
.File("logs.txt", formatProvider: CultureInfo.InvariantCulture)
.File("logs.txt", formatProvider: CultureInfo.InvariantCulture, rollOnFileSizeLimit: true, fileSizeLimitBytes: 5 * 1_024 * 1_024)
.MinimumLevel
.Debug()
.CreateLogger();

using var loggerFactory = LoggerFactory.Create(
generatorLoggerFactory = LoggerFactory.Create(
b =>
{
b.ClearProviders();
b.AddSerilog(fileLogger);
b.SetMinimumLevel(LogLevel.Debug);
});

IServiceCollection sc = new ServiceCollection();

sc.AddLogging(b => b.AddConsole());
sc.AddSingleton(configuration);
sc.AddToolsGenerator(loggerFactory);
sc.AddToolsGenerator(generatorLoggerFactory);

this.Service = sc.BuildServiceProvider();

Expand All @@ -68,7 +75,19 @@ public static int Main(string[] args)
builder.AddCommandLine(args);
var config = builder.Build();

return new Program(config).Run();
using var program = new Program(config);

return program.Run();
}

/// <inheritdoc/>
#pragma warning disable CA1063 // Implement IDisposable Correctly
public void Dispose()
#pragma warning restore CA1063 // Implement IDisposable Correctly
{
generatorLoggerFactory.Dispose();

GC.SuppressFinalize(this);
}

/// <summary>
Expand Down
Loading

0 comments on commit 7c1a425

Please sign in to comment.