diff --git a/src/Directory.Packages.props b/src/Directory.Packages.props index 307f97342f..967d09b660 100644 --- a/src/Directory.Packages.props +++ b/src/Directory.Packages.props @@ -14,7 +14,13 @@ + + + + + + diff --git a/src/GitVersion.App/CliHost.cs b/src/GitVersion.App/CliHost.cs index 357e7df742..5423bae9df 100644 --- a/src/GitVersion.App/CliHost.cs +++ b/src/GitVersion.App/CliHost.cs @@ -1,10 +1,15 @@ +using System.IO.Abstractions; +using GitVersion; using GitVersion.Agents; using GitVersion.Configuration; using GitVersion.Extensions; +using GitVersion.Logging; using GitVersion.Output; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; +using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; +using Serilog; namespace GitVersion; @@ -12,8 +17,19 @@ internal static class CliHost { internal static HostApplicationBuilder CreateCliHostBuilder(string[] args) { + // Parse arguments early to configure logging + var tempServices = new ServiceCollection(); + tempServices.AddSingleton(); + var tempProvider = tempServices.BuildServiceProvider(); + var argumentParser = tempProvider.GetRequiredService(); + var arguments = argumentParser.ParseArguments(args); + var gitVersionOptions = arguments.ToOptions(); + var builder = Host.CreateApplicationBuilder(args); + // Configure Serilog based on parsed arguments + ConfigureSerilog(builder, gitVersionOptions); + builder.Services.AddModule(new GitVersionCoreModule()); builder.Services.AddModule(new GitVersionLibGit2SharpModule()); builder.Services.AddModule(new GitVersionBuildAgentsModule()); @@ -21,15 +37,28 @@ internal static HostApplicationBuilder CreateCliHostBuilder(string[] args) builder.Services.AddModule(new GitVersionOutputModule()); builder.Services.AddModule(new GitVersionAppModule()); - builder.Services.AddSingleton(sp => - { - var arguments = sp.GetRequiredService().ParseArguments(args); - var gitVersionOptions = arguments.ToOptions(); - return Options.Create(gitVersionOptions); - }); + builder.Services.AddSingleton(sp => Options.Create(gitVersionOptions)); builder.Services.AddSingleton(); return builder; } + + private static void ConfigureSerilog(HostApplicationBuilder builder, GitVersionOptions options) + { + var loggerConfiguration = LoggingModule.CreateLoggerConfiguration( + options.Verbosity, + options.Output.Contains(OutputType.BuildServer) || options.LogFilePath == "console", + options.LogFilePath != null && options.LogFilePath != "console" ? options.LogFilePath : null, + new FileSystem() + ); + + Serilog.Log.Logger = loggerConfiguration.CreateLogger(); + + builder.Services.AddLogging(loggingBuilder => + { + loggingBuilder.ClearProviders(); + loggingBuilder.AddSerilog(Serilog.Log.Logger, dispose: true); + }); + } } diff --git a/src/GitVersion.App/GitVersion.App.csproj b/src/GitVersion.App/GitVersion.App.csproj index 00c1587488..9732be23dc 100644 --- a/src/GitVersion.App/GitVersion.App.csproj +++ b/src/GitVersion.App/GitVersion.App.csproj @@ -20,6 +20,7 @@ + diff --git a/src/GitVersion.Configuration/ConfigurationFileLocator.cs b/src/GitVersion.Configuration/ConfigurationFileLocator.cs index 489c39e1f1..707ee1509c 100644 --- a/src/GitVersion.Configuration/ConfigurationFileLocator.cs +++ b/src/GitVersion.Configuration/ConfigurationFileLocator.cs @@ -1,14 +1,14 @@ using System.IO.Abstractions; using GitVersion.Extensions; using GitVersion.Helpers; -using GitVersion.Logging; +using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; namespace GitVersion.Configuration; internal class ConfigurationFileLocator( IFileSystem fileSystem, - ILog log, + ILogger logger, IOptions options) : IConfigurationFileLocator { @@ -26,7 +26,7 @@ internal class ConfigurationFileLocator( ]; private readonly IFileSystem fileSystem = fileSystem.NotNull(); - private readonly ILog log = log.NotNull(); + private readonly ILogger logger = log.NotNull(); private readonly IOptions options = options.NotNull(); private string? ConfigurationFile => options.Value.ConfigurationInfo.ConfigurationFile; @@ -43,7 +43,7 @@ public void Verify(string? workingDirectory, string? projectRootDirectory) var customConfigurationFile = GetCustomConfigurationFilePathIfEligable(directoryPath); if (!string.IsNullOrWhiteSpace(customConfigurationFile)) { - this.log.Info($"Found configuration file at '{customConfigurationFile}'"); + this.logger.LogInformation($"Found configuration file at '{customConfigurationFile}'"); return customConfigurationFile; } @@ -55,10 +55,10 @@ public void Verify(string? workingDirectory, string? projectRootDirectory) var files = fileSystem.Directory.GetFiles(directoryPath); foreach (var fileName in this.SupportedConfigFileNames) { - this.log.Debug($"Trying to find configuration file {fileName} at '{directoryPath}'"); + this.logger.LogDebug($"Trying to find configuration file {fileName} at '{directoryPath}'"); var matchingFile = files.FirstOrDefault(file => string.Equals(FileSystemHelper.Path.GetFileName(file), fileName, StringComparison.OrdinalIgnoreCase)); if (matchingFile == null) continue; - this.log.Info($"Found configuration file at '{matchingFile}'"); + this.logger.LogInformation($"Found configuration file at '{matchingFile}'"); return matchingFile; } diff --git a/src/GitVersion.Configuration/ConfigurationProvider.cs b/src/GitVersion.Configuration/ConfigurationProvider.cs index 644e1656cc..d7c243c039 100644 --- a/src/GitVersion.Configuration/ConfigurationProvider.cs +++ b/src/GitVersion.Configuration/ConfigurationProvider.cs @@ -1,7 +1,7 @@ using System.IO.Abstractions; using GitVersion.Configuration.Workflows; using GitVersion.Extensions; -using GitVersion.Logging; +using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; using YamlDotNet.Core; @@ -10,14 +10,14 @@ namespace GitVersion.Configuration; internal class ConfigurationProvider( IConfigurationFileLocator configFileLocator, IFileSystem fileSystem, - ILog log, + ILogger logger, IConfigurationSerializer configurationSerializer, IOptions options) : IConfigurationProvider { private readonly IConfigurationFileLocator configFileLocator = configFileLocator.NotNull(); private readonly IFileSystem fileSystem = fileSystem.NotNull(); - private readonly ILog log = log.NotNull(); + private readonly ILogger logger = log.NotNull(); private readonly IConfigurationSerializer configurationSerializer = configurationSerializer.NotNull(); private readonly IOptions options = options.NotNull(); @@ -77,17 +77,17 @@ private IGitVersionConfiguration ProvideConfiguration(string? configFile, { if (configFilePath == null) { - this.log.Info("No configuration file found, using default configuration"); + this.logger.LogInformation("No configuration file found, using default configuration"); return null; } if (!this.fileSystem.File.Exists(configFilePath)) { - this.log.Info($"Configuration file '{configFilePath}' not found"); + this.logger.LogInformation($"Configuration file '{configFilePath}' not found"); return null; } - this.log.Info($"Using configuration file '{configFilePath}'"); + this.logger.LogInformation($"Using configuration file '{configFilePath}'"); var content = fileSystem.File.ReadAllText(configFilePath); return configurationSerializer.Deserialize>(content); } diff --git a/src/GitVersion.Core/Core/BranchesContainingCommitFinder.cs b/src/GitVersion.Core/Core/BranchesContainingCommitFinder.cs index d078714e98..5f92c4d837 100644 --- a/src/GitVersion.Core/Core/BranchesContainingCommitFinder.cs +++ b/src/GitVersion.Core/Core/BranchesContainingCommitFinder.cs @@ -1,13 +1,14 @@ using GitVersion.Common; using GitVersion.Extensions; using GitVersion.Git; +using Microsoft.Extensions.Logging; using GitVersion.Logging; namespace GitVersion; -internal class BranchesContainingCommitFinder(IRepositoryStore repositoryStore, ILog log) +internal class BranchesContainingCommitFinder(IRepositoryStore repositoryStore, ILogger logger) { - private readonly ILog log = log.NotNull(); + private readonly ILogger logger = log.NotNull(); private readonly IRepositoryStore repositoryStore = repositoryStore.NotNull(); public IEnumerable GetBranchesContainingCommit(ICommit commit, IEnumerable? branches = null, bool onlyTrackedBranches = false) @@ -23,16 +24,16 @@ public IEnumerable GetBranchesContainingCommit(ICommit commit, IEnumera private IEnumerable InnerGetBranchesContainingCommit(ICommit commit, IEnumerable branches, bool onlyTrackedBranches) { - using (log.IndentLog($"Getting branches containing the commit '{commit.Id}'.")) + using (logger.IndentLog($"Getting branches containing the commit '{commit.Id}'.")) { var directBranchHasBeenFound = false; - log.Info("Trying to find direct branches."); + logger.LogInformation("Trying to find direct branches."); // TODO: It looks wasteful looping through the branches twice. Can't these loops be merged somehow? @asbjornu var branchList = branches.ToList(); foreach (var branch in branchList.Where(branch => BranchTipIsNullOrCommit(branch, commit) && !IncludeTrackedBranches(branch, onlyTrackedBranches))) { directBranchHasBeenFound = true; - log.Info($"Direct branch found: '{branch}'."); + logger.LogInformation($"Direct branch found: '{branch}'."); yield return branch; } @@ -41,20 +42,20 @@ private IEnumerable InnerGetBranchesContainingCommit(ICommit commit, IE yield break; } - log.Info($"No direct branches found, searching through {(onlyTrackedBranches ? "tracked" : "all")} branches."); + logger.LogInformation($"No direct branches found, searching through {(onlyTrackedBranches ? "tracked" : "all")} branches."); foreach (var branch in branchList.Where(b => IncludeTrackedBranches(b, onlyTrackedBranches))) { - log.Info($"Searching for commits reachable from '{branch}'."); + logger.LogInformation($"Searching for commits reachable from '{branch}'."); var commits = this.repositoryStore.GetCommitsReacheableFrom(commit, branch); if (!commits.Any()) { - log.Info($"The branch '{branch}' has no matching commits."); + logger.LogInformation($"The branch '{branch}' has no matching commits."); continue; } - log.Info($"The branch '{branch}' has a matching commit."); + logger.LogInformation($"The branch '{branch}' has a matching commit."); yield return branch; } } diff --git a/src/GitVersion.Core/Core/GitPreparer.cs b/src/GitVersion.Core/Core/GitPreparer.cs index 52281942de..8f0b158eae 100644 --- a/src/GitVersion.Core/Core/GitPreparer.cs +++ b/src/GitVersion.Core/Core/GitPreparer.cs @@ -4,13 +4,14 @@ using GitVersion.Extensions; using GitVersion.Git; using GitVersion.Helpers; +using Microsoft.Extensions.Logging; using GitVersion.Logging; using Microsoft.Extensions.Options; namespace GitVersion; internal class GitPreparer( - ILog log, + ILogger logger, IFileSystem fileSystem, IEnvironment environment, ICurrentBuildAgent buildAgent, @@ -20,7 +21,7 @@ internal class GitPreparer( Lazy versionContext) : IGitPreparer { - private readonly ILog log = log.NotNull(); + private readonly ILogger logger = logger.NotNull(); private readonly IFileSystem fileSystem = fileSystem.NotNull(); private readonly IEnvironment environment = environment.NotNull(); private readonly IMutatingGitRepository repository = repository.NotNull(); @@ -38,8 +39,8 @@ public void Prepare() var dotGitDirectory = this.repositoryInfo.DotGitDirectory; var projectRoot = this.repositoryInfo.ProjectRootDirectory; - this.log.Info($"Project root is: {projectRoot}"); - this.log.Info($"DotGit directory is: {dotGitDirectory}"); + this.logger.LogInformation($"Project root is: {projectRoot}"); + this.logger.LogInformation($"DotGit directory is: {dotGitDirectory}"); if (dotGitDirectory.IsNullOrEmpty() || projectRoot.IsNullOrEmpty()) { throw new($"Failed to prepare or find the .git directory in path '{gitVersionOptions.WorkingDirectory}'."); @@ -77,7 +78,7 @@ private void PrepareInternal(GitVersionOptions gitVersionOptions) var isDynamicRepository = !gitVersionOptions.RepositoryInfo.ClonePath.IsNullOrWhiteSpace(); var currentBranch = this.buildAgent.GetCurrentBranch(isDynamicRepository) ?? targetBranch; - this.log.Info("Branch from build environment: " + currentBranch); + this.logger.LogInformation("Branch from build environment: " + currentBranch); return currentBranch; } @@ -111,7 +112,7 @@ private void CreateDynamicRepository(string? targetBranch) var gitDirectory = this.repositoryInfo.DynamicGitRepositoryPath; - using (this.log.IndentLog($"Creating dynamic repository at '{gitDirectory}'")) + using (this.logger.IndentLog($"Creating dynamic repository at '{gitDirectory}'")) { var gitVersionOptions = this.options.Value; var authentication = gitVersionOptions.AuthenticationInfo; @@ -125,14 +126,14 @@ private void CreateDynamicRepository(string? targetBranch) } else { - this.log.Info("Git repository already exists"); + this.logger.LogInformation("Git repository already exists"); } } } private void NormalizeGitDirectory(string? targetBranch, bool isDynamicRepository) { - using (this.log.IndentLog($"Normalizing git directory for branch '{targetBranch}'")) + using (this.logger.IndentLog($"Normalizing git directory for branch '{targetBranch}'")) { // Normalize (download branches) before using the branch NormalizeGitDirectory(this.options.Value.Settings.NoFetch, targetBranch, isDynamicRepository); @@ -141,7 +142,7 @@ private void NormalizeGitDirectory(string? targetBranch, bool isDynamicRepositor private void CloneRepository(string? repositoryUrl, string? gitDirectory, AuthenticationInfo auth) { - using (this.log.IndentLog($"Cloning repository from url '{repositoryUrl}'")) + using (this.logger.IndentLog($"Cloning repository from url '{repositoryUrl}'")) { this.retryAction.Execute(() => this.repository.Clone(repositoryUrl, gitDirectory, auth)); } @@ -179,7 +180,7 @@ private void NormalizeGitDirectory(bool noFetch, string? currentBranchName, bool var newExpectedSha = this.repository.Head.Tip?.Sha; var newExpectedBranchName = this.repository.Head.Name.Canonical; - this.log.Info($"Head has moved from '{expectedBranchName} | {expectedSha}' => '{newExpectedBranchName} | {newExpectedSha}', allowed since this is a dynamic repository"); + this.logger.LogInformation($"Head has moved from '{expectedBranchName} | {expectedSha}' => '{newExpectedBranchName} | {newExpectedSha}', allowed since this is a dynamic repository"); expectedSha = newExpectedSha; } @@ -191,7 +192,7 @@ private void NormalizeGitDirectory(bool noFetch, string? currentBranchName, bool if (!this.repository.IsShallow) return; if (this.options.Value.Settings.AllowShallow) { - this.log.Info("Repository is a shallow clone. GitVersion will continue, but it is recommended to use a full clone for accurate versioning."); + this.logger.LogInformation("Repository is a shallow clone. GitVersion will continue, but it is recommended to use a full clone for accurate versioning."); } else { @@ -221,13 +222,13 @@ private void EnsureHeadIsAttachedToBranch(string? currentBranchName, Authenticat var headSha = this.repository.References.Head?.TargetIdentifier; if (!this.repository.IsHeadDetached) { - this.log.Info($"HEAD points at branch '{headSha}'."); + this.logger.LogInformation($"HEAD points at branch '{headSha}'."); return; } - this.log.Info($"HEAD is detached and points at commit '{headSha}'."); + this.logger.LogInformation($"HEAD is detached and points at commit '{headSha}'."); var localRefs = this.repository.References.FromGlob("*").Select(r => $"{r.Name.Canonical} ({r.TargetIdentifier})"); - this.log.Info($"Local Refs:{FileSystemHelper.Path.NewLine}" + string.Join(FileSystemHelper.Path.NewLine, localRefs)); + this.logger.LogInformation($"Local Refs:{FileSystemHelper.Path.NewLine}" + string.Join(FileSystemHelper.Path.NewLine, localRefs)); // In order to decide whether a fake branch is required or not, first check to see if any local branches have the same commit SHA of the head SHA. // If they do, go ahead and checkout that branch @@ -239,7 +240,7 @@ private void EnsureHeadIsAttachedToBranch(string? currentBranchName, Authenticat : null; if (matchingCurrentBranch != null) { - this.log.Info($"Checking out local branch '{currentBranchName}'."); + this.logger.LogInformation($"Checking out local branch '{currentBranchName}'."); Checkout(matchingCurrentBranch.Name.Canonical); } else @@ -250,11 +251,11 @@ private void EnsureHeadIsAttachedToBranch(string? currentBranchName, Authenticat ChooseLocalBranchToAttach(headSha, localBranchesWhereCommitShaIsHead); break; case 0: - this.log.Info($"No local branch pointing at the commit '{headSha}'. Fake branch needs to be created."); + this.logger.LogInformation($"No local branch pointing at the commit '{headSha}'. Fake branch needs to be created."); this.retryAction.Execute(() => this.repository.CreateBranchForPullRequestBranch(authentication)); break; default: - this.log.Info($"Checking out local branch 'refs/heads/{localBranchesWhereCommitShaIsHead[0]}'."); + this.logger.LogInformation($"Checking out local branch 'refs/heads/{localBranchesWhereCommitShaIsHead[0]}'."); Checkout(localBranchesWhereCommitShaIsHead[0].Name.Friendly); break; } @@ -266,11 +267,11 @@ private void ChooseLocalBranchToAttach(string? headSha, IReadOnlyCollection n.Name.EquivalentTo(ConfigurationConstants.MainBranchKey)); if (mainBranch != null) { - this.log.Warning("Because one of the branches is 'main', will build main." + moveBranchMsg); + this.logger.LogWarning("Because one of the branches is 'main', will build main." + moveBranchMsg); Checkout(ConfigurationConstants.MainBranchKey); } else @@ -279,7 +280,7 @@ private void ChooseLocalBranchToAttach(string? headSha, IReadOnlyCollection r.Specification)); - this.log.Info($"Fetching from remote '{remote.Name}' using the following refspecs: {refSpecs}."); + this.logger.LogInformation($"Fetching from remote '{remote.Name}' using the following refspecs: {refSpecs}."); this.retryAction.Execute(() => this.repository.Fetch(remote.Name, [], authentication, null)); } } @@ -312,12 +313,12 @@ private IRemote EnsureOnlyOneRemoteIsDefined() if (howMany == 1) { var remote = remotes.Single(); - this.log.Info($"One remote found ({remote.Name} -> '{remote.Url}')."); + this.logger.LogInformation($"One remote found ({remote.Name} -> '{remote.Url}')."); if (remote.FetchRefSpecs.Any(r => r.Source == "refs/heads/*")) return remote; var allBranchesFetchRefSpec = $"+refs/heads/*:refs/remotes/{remote.Name}/*"; - this.log.Info($"Adding refspec: {allBranchesFetchRefSpec}"); + this.logger.LogInformation($"Adding refspec: {allBranchesFetchRefSpec}"); remotes.Update(remote.Name, allBranchesFetchRefSpec); return remote; } @@ -349,19 +350,19 @@ private void CreateOrUpdateLocalBranchesFromRemoteTrackingOnes(string remoteName { if (localRef.TargetIdentifier == remoteTrackingReference.TargetIdentifier) { - this.log.Info($"Skipping update of '{remoteTrackingReference.Name.Canonical}' as it already matches the remote ref."); + this.logger.LogInformation($"Skipping update of '{remoteTrackingReference.Name.Canonical}' as it already matches the remote ref."); continue; } var remoteRefTipId = remoteTrackingReference.ReferenceTargetId; if (remoteRefTipId != null) { - this.log.Info($"Updating local ref '{localRef.Name.Canonical}' to point at {remoteRefTipId}."); + this.logger.LogInformation($"Updating local ref '{localRef.Name.Canonical}' to point at {remoteRefTipId}."); this.retryAction.Execute(() => this.repository.References.UpdateTarget(localRef, remoteRefTipId)); } continue; } - this.log.Info($"Creating local branch from remote tracking '{remoteTrackingReference.Name.Canonical}'."); + this.logger.LogInformation($"Creating local branch from remote tracking '{remoteTrackingReference.Name.Canonical}'."); this.repository.References.Add(localReferenceName.Canonical, remoteTrackingReference.TargetIdentifier, true); var branch = this.repository.Branches[branchName]; @@ -403,14 +404,14 @@ public void EnsureLocalBranchExistsForCurrentBranch(IRemote remote, string? curr var referenceName = ReferenceName.Parse(localCanonicalName); if (this.repository.Branches.All(b => !b.Name.Equals(referenceName))) { - this.log.Info(isLocalBranch + this.logger.LogInformation(isLocalBranch ? $"Creating local branch {referenceName}" : $"Creating local branch {referenceName} pointing at {repoTipId}"); this.repository.References.Add(localCanonicalName, repoTipId.Sha); } else { - this.log.Info(isLocalBranch + this.logger.LogInformation(isLocalBranch ? $"Updating local branch {referenceName} to point at {repoTipId}" : $"Updating local branch {referenceName} to match ref {currentBranch}"); var localRef = this.repository.References[localCanonicalName]; diff --git a/src/GitVersion.Core/Core/GitVersionCalculateTool.cs b/src/GitVersion.Core/Core/GitVersionCalculateTool.cs index 72703484ec..a72206f492 100644 --- a/src/GitVersion.Core/Core/GitVersionCalculateTool.cs +++ b/src/GitVersion.Core/Core/GitVersionCalculateTool.cs @@ -1,7 +1,7 @@ using GitVersion.Configuration; using GitVersion.Extensions; using GitVersion.Helpers; -using GitVersion.Logging; +using Microsoft.Extensions.Logging; using GitVersion.OutputVariables; using GitVersion.VersionCalculation; using GitVersion.VersionCalculation.Caching; @@ -10,7 +10,7 @@ namespace GitVersion; internal class GitVersionCalculateTool( - ILog log, + ILogger logger, INextVersionCalculator nextVersionCalculator, IVariableProvider variableProvider, IGitPreparer gitPreparer, @@ -19,7 +19,7 @@ internal class GitVersionCalculateTool( Lazy versionContext) : IGitVersionCalculateTool { - private readonly ILog log = log.NotNull(); + private readonly ILogger logger = logger.NotNull(); private readonly IGitVersionCacheProvider gitVersionCacheProvider = gitVersionCacheProvider.NotNull(); private readonly INextVersionCalculator nextVersionCalculator = nextVersionCalculator.NotNull(); private readonly IVariableProvider variableProvider = variableProvider.NotNull(); @@ -56,7 +56,7 @@ public GitVersionVariables CalculateVersionVariables() } catch (AggregateException e) { - this.log.Warning($"One or more exceptions during cache write:{FileSystemHelper.Path.NewLine}{e}"); + this.logger.LogWarning($"One or more exceptions during cache write:{FileSystemHelper.Path.NewLine}{e}"); } return versionVariables; diff --git a/src/GitVersion.Core/Core/MergeBaseFinder.cs b/src/GitVersion.Core/Core/MergeBaseFinder.cs index a281a01ce7..8e1d37206c 100644 --- a/src/GitVersion.Core/Core/MergeBaseFinder.cs +++ b/src/GitVersion.Core/Core/MergeBaseFinder.cs @@ -1,13 +1,14 @@ using GitVersion.Common; using GitVersion.Extensions; using GitVersion.Git; +using Microsoft.Extensions.Logging; using GitVersion.Logging; namespace GitVersion; -internal class MergeBaseFinder(IRepositoryStore repositoryStore, ILog log) +internal class MergeBaseFinder(IRepositoryStore repositoryStore, ILogger logger) { - private readonly ILog log = log.NotNull(); + private readonly ILogger logger = logger.NotNull(); private readonly IRepositoryStore repositoryStore = repositoryStore.NotNull(); private readonly Dictionary, ICommit> mergeBaseCache = []; @@ -20,11 +21,11 @@ internal class MergeBaseFinder(IRepositoryStore repositoryStore, ILog log) if (this.mergeBaseCache.TryGetValue(key, out var mergeBase)) { - this.log.Debug($"Cache hit for merge base between '{first}' and '{second}'."); + this.logger.LogDebug($"Cache hit for merge base between '{first}' and '{second}'."); return mergeBase; } - using (this.log.IndentLog($"Finding merge base between '{first}' and '{second}'.")) + using (this.logger.IndentLog($"Finding merge base between '{first}' and '{second}'.")) { // Other branch tip is a forward merge var commitToFindCommonBase = second.Tip; @@ -45,14 +46,14 @@ internal class MergeBaseFinder(IRepositoryStore repositoryStore, ILog log) if (findMergeBase == null) { - this.log.Info($"No merge base of '{first}' and '{second}' could be found."); + this.logger.LogInformation($"No merge base of '{first}' and '{second}' could be found."); return null; } // Store in cache. this.mergeBaseCache.Add(key, findMergeBase); - this.log.Info($"Merge base of '{first}' and '{second}' is '{findMergeBase}'"); + this.logger.LogInformation($"Merge base of '{first}' and '{second}' is '{findMergeBase}'"); return findMergeBase; } } @@ -63,7 +64,7 @@ internal class MergeBaseFinder(IRepositoryStore repositoryStore, ILog log) if (findMergeBase == null) return null; - this.log.Info($"Found merge base of '{findMergeBase}'"); + this.logger.LogInformation($"Found merge base of '{findMergeBase}'"); // We do not want to include merge base commits which got forward merged into the other branch ICommit? forwardMerge; @@ -77,26 +78,26 @@ internal class MergeBaseFinder(IRepositoryStore repositoryStore, ILog log) // TODO Fix the logging up in this section var second = forwardMerge.Parents[0]; - this.log.Debug($"Second {second}"); + this.logger.LogDebug($"Second {second}"); var mergeBase = this.repositoryStore.FindMergeBase(commit, second); if (mergeBase == null) { - this.log.Warning("Could not find merge base for " + commit); + this.logger.LogWarning("Could not find merge base for " + commit); } else { - this.log.Debug($"New Merge base {mergeBase}"); + this.logger.LogDebug($"New Merge base {mergeBase}"); } if (Equals(mergeBase, findMergeBase)) { - this.log.Debug("Breaking"); + this.logger.LogDebug("Breaking"); break; } findMergeBase = mergeBase; commitToFindCommonBase = second; - this.log.Info($"next merge base --> {findMergeBase}"); + this.logger.LogInformation($"next merge base --> {findMergeBase}"); } while (forwardMerge != null); return findMergeBase; diff --git a/src/GitVersion.Core/Core/MergeCommitFinder.cs b/src/GitVersion.Core/Core/MergeCommitFinder.cs index c38da050af..d61911a759 100644 --- a/src/GitVersion.Core/Core/MergeCommitFinder.cs +++ b/src/GitVersion.Core/Core/MergeCommitFinder.cs @@ -2,13 +2,13 @@ using GitVersion.Configuration; using GitVersion.Extensions; using GitVersion.Git; -using GitVersion.Logging; +using Microsoft.Extensions.Logging; namespace GitVersion; -internal class MergeCommitFinder(IRepositoryStore repositoryStore, IGitVersionConfiguration configuration, IEnumerable excludedBranches, ILog log) +internal class MergeCommitFinder(IRepositoryStore repositoryStore, IGitVersionConfiguration configuration, IEnumerable excludedBranches, ILogger logger) { - private readonly ILog log = log.NotNull(); + private readonly ILogger logger = logger.NotNull(); private readonly IEnumerable branches = repositoryStore.ExcludingBranches(excludedBranches.NotNull()); private readonly IRepositoryStore repositoryStore = repositoryStore.NotNull(); private readonly IGitVersionConfiguration configuration = configuration.NotNull(); @@ -20,7 +20,7 @@ public IEnumerable FindMergeCommitsFor(IBranch branch) if (this.mergeBaseCommitsCache.TryGetValue(branch, out var mergeCommitsFor)) { - this.log.Debug($"Cache hit for getting merge commits for branch {branch.Name.Canonical}."); + this.logger.LogDebug($"Cache hit for getting merge commits for branch {branch.Name.Canonical}."); return mergeCommitsFor; } @@ -42,7 +42,7 @@ private IEnumerable FindMergeBases(IBranch branch) { if (sourceBranch.Tip == null) { - this.log.Warning($"{sourceBranch} has no tip."); + this.logger.LogWarning($"{sourceBranch} has no tip."); continue; } diff --git a/src/GitVersion.Core/Core/RepositoryStore.cs b/src/GitVersion.Core/Core/RepositoryStore.cs index 50b5512a07..7447520369 100644 --- a/src/GitVersion.Core/Core/RepositoryStore.cs +++ b/src/GitVersion.Core/Core/RepositoryStore.cs @@ -3,13 +3,14 @@ using GitVersion.Extensions; using GitVersion.Git; using GitVersion.Helpers; +using Microsoft.Extensions.Logging; using GitVersion.Logging; namespace GitVersion; -internal class RepositoryStore(ILog log, IGitRepository repository) : IRepositoryStore +internal class RepositoryStore(ILogger logger, IGitRepository repository) : IRepositoryStore { - private readonly ILog log = log.NotNull(); + private readonly ILogger logger = logger.NotNull(); private readonly IGitRepository repository = repository.NotNull(); public int UncommittedChangesCount => this.repository.UncommittedChangesCount(); @@ -25,7 +26,7 @@ internal class RepositoryStore(ILog log, IGitRepository repository) : IRepositor /// public ICommit? FindMergeBase(IBranch? branch, IBranch? otherBranch) { - var mergeBaseFinder = new MergeBaseFinder(this, log); + var mergeBaseFinder = new MergeBaseFinder(this, logger); return mergeBaseFinder.FindMergeBaseOf(branch, otherBranch); } @@ -37,7 +38,7 @@ internal class RepositoryStore(ILog log, IGitRepository repository) : IRepositor ICommit? currentCommit = null; if (!commitId.IsNullOrWhiteSpace()) { - this.log.Info($"Searching for specific commit '{commitId}'"); + this.logger.LogInformation($"Searching for specific commit '{commitId}'"); var commit = this.repository.Commits.FirstOrDefault(c => string.Equals(c.Sha, commitId, StringComparison.OrdinalIgnoreCase)); if (commit != null) @@ -46,7 +47,7 @@ internal class RepositoryStore(ILog log, IGitRepository repository) : IRepositor } else { - this.log.Warning($"Commit '{commitId}' specified but not found"); + this.logger.LogWarning($"Commit '{commitId}' specified but not found"); } } @@ -57,7 +58,7 @@ internal class RepositoryStore(ILog log, IGitRepository repository) : IRepositor } else { - this.log.Info("Using latest commit on specified branch"); + this.logger.LogInformation("Using latest commit on specified branch"); } commits = ignore.Filter(commits.ToArray()); @@ -175,11 +176,11 @@ public BranchCommit FindCommitBranchBranchedFrom(IBranch? branch, IGitVersionCon { branch = branch.NotNull(); - using (this.log.IndentLog($"Finding branch source of '{branch}'")) + using (this.logger.IndentLog($"Finding branch source of '{branch}'")) { if (branch.Tip == null) { - this.log.Warning($"{branch} has no tip."); + this.logger.LogWarning($"{branch} has no tip."); return BranchCommit.Empty; } @@ -192,7 +193,7 @@ public BranchCommit FindCommitBranchBranchedFrom(IBranch? branch, IGitVersionCon return possibleBranches.SingleOrDefault(); var first = possibleBranches[0]; - this.log.Info($"Multiple source branches have been found, picking the first one ({first.Branch}).{FileSystemHelper.Path.NewLine}" + + this.logger.LogInformation($"Multiple source branches have been found, picking the first one ({first.Branch}).{FileSystemHelper.Path.NewLine}" + $"This may result in incorrect commit counting.{FileSystemHelper.Path.NewLine}Options were:{FileSystemHelper.Path.NewLine}" + string.Join(", ", possibleBranches.Select(b => b.Branch.ToString()))); return first; @@ -267,10 +268,10 @@ public bool IsCommitOnBranch(ICommit? baseVersionSource, IBranch branch, ICommit private List FindCommitBranchesBranchedFrom( IBranch branch, IGitVersionConfiguration configuration, IEnumerable excludedBranches) { - using (this.log.IndentLog($"Finding branches source of '{branch}'")) + using (this.logger.IndentLog($"Finding branches source of '{branch}'")) { if (branch.Tip != null) return [.. new MergeCommitFinder(this, configuration, excludedBranches, this.log).FindMergeCommitsFor(branch)]; - this.log.Warning($"{branch} has no tip."); + this.logger.LogWarning($"{branch} has no tip."); return []; } } diff --git a/src/GitVersion.Core/Core/TaggedSemanticVersionRepository.cs b/src/GitVersion.Core/Core/TaggedSemanticVersionRepository.cs index 60bf291f6b..b0caa50ee0 100644 --- a/src/GitVersion.Core/Core/TaggedSemanticVersionRepository.cs +++ b/src/GitVersion.Core/Core/TaggedSemanticVersionRepository.cs @@ -3,11 +3,12 @@ using GitVersion.Configuration; using GitVersion.Extensions; using GitVersion.Git; +using Microsoft.Extensions.Logging; using GitVersion.Logging; namespace GitVersion.Core; -internal sealed class TaggedSemanticVersionRepository(ILog log, IRepositoryStore repositoryStore) : ITaggedSemanticVersionRepository +internal sealed class TaggedSemanticVersionRepository(ILogger logger, IRepositoryStore repositoryStore) : ITaggedSemanticVersionRepository { private readonly ConcurrentDictionary<(IBranch, string, SemanticVersionFormat), IReadOnlyList> taggedSemanticVersionsOfBranchCache = new(); @@ -15,7 +16,7 @@ internal sealed class TaggedSemanticVersionRepository(ILog log, IRepositoryStore taggedSemanticVersionsOfMergeTargetCache = new(); private readonly ConcurrentDictionary<(string, SemanticVersionFormat), IReadOnlyList> taggedSemanticVersionsCache = new(); - private readonly ILog log = log.NotNull(); + private readonly ILogger logger = log.NotNull(); private readonly IRepositoryStore repositoryStore = repositoryStore.NotNull(); @@ -34,7 +35,7 @@ public ILookup GetTaggedSemanticVersionsOfBranc if (isCached) { - this.log.Debug( + this.logger.LogDebug( $"Returning cached tagged semantic versions on branch '{branch.Name.Canonical}'. " + $"TagPrefix: {tagPrefix} and Format: {format}" ); @@ -44,7 +45,7 @@ public ILookup GetTaggedSemanticVersionsOfBranc IEnumerable GetElements() { - using (this.log.IndentLog($"Getting tagged semantic versions on branch '{branch.Name.Canonical}'. " + + using (this.logger.IndentLog($"Getting tagged semantic versions on branch '{branch.Name.Canonical}'. " + $"TagPrefix: {tagPrefix} and Format: {format}")) { var semanticVersions = GetTaggedSemanticVersions(tagPrefix, format, ignore); @@ -75,7 +76,7 @@ public ILookup GetTaggedSemanticVersionsOfMerge if (isCached) { - this.log.Debug( + this.logger.LogDebug( $"Returning cached tagged semantic versions by track merge target '{branch.Name.Canonical}'. " + $"TagPrefix: {tagPrefix} and Format: {format}" ); @@ -85,7 +86,7 @@ public ILookup GetTaggedSemanticVersionsOfMerge IEnumerable<(ICommit Key, SemanticVersionWithTag Value)> GetElements() { - using (this.log.IndentLog($"Getting tagged semantic versions by track merge target '{branch.Name.Canonical}'. " + + using (this.logger.IndentLog($"Getting tagged semantic versions by track merge target '{branch.Name.Canonical}'. " + $"TagPrefix: {tagPrefix} and Format: {format}")) { var shaHashSet = new HashSet(ignore.Filter(branch.Commits.ToArray()).Select(element => element.Id.Sha)); @@ -115,14 +116,14 @@ public ILookup GetTaggedSemanticVersions( if (isCached) { - this.log.Debug($"Returning cached tagged semantic versions. TagPrefix: {tagPrefix} and Format: {format}"); + this.logger.LogDebug($"Returning cached tagged semantic versions. TagPrefix: {tagPrefix} and Format: {format}"); } return result.ToLookup(element => element.Tag.Commit, element => element); IEnumerable GetElements() { - this.log.Info($"Getting tagged semantic versions. TagPrefix: {tagPrefix} and Format: {format}"); + this.logger.LogInformation($"Getting tagged semantic versions. TagPrefix: {tagPrefix} and Format: {format}"); foreach (var tag in ignore.Filter(this.repositoryStore.Tags.ToArray())) { diff --git a/src/GitVersion.Core/GitVersion.Core.csproj b/src/GitVersion.Core/GitVersion.Core.csproj index 0843eba8da..42c22f7b1d 100644 --- a/src/GitVersion.Core/GitVersion.Core.csproj +++ b/src/GitVersion.Core/GitVersion.Core.csproj @@ -14,7 +14,12 @@ + + + + + diff --git a/src/GitVersion.Core/GitVersionCommonModule.cs b/src/GitVersion.Core/GitVersionCommonModule.cs index 767b780e52..2966ba1272 100644 --- a/src/GitVersion.Core/GitVersionCommonModule.cs +++ b/src/GitVersion.Core/GitVersionCommonModule.cs @@ -9,7 +9,6 @@ public class GitVersionCommonModule : IGitVersionModule { public void RegisterTypes(IServiceCollection services) { - services.AddSingleton(); services.AddSingleton(); services.AddSingleton(); services.AddSingleton(); diff --git a/src/GitVersion.Core/Logging/LoggerExtensions.cs b/src/GitVersion.Core/Logging/LoggerExtensions.cs new file mode 100644 index 0000000000..96a54d2086 --- /dev/null +++ b/src/GitVersion.Core/Logging/LoggerExtensions.cs @@ -0,0 +1,23 @@ +using System.Diagnostics; +using GitVersion.Helpers; +using Microsoft.Extensions.Logging; + +namespace GitVersion.Logging; + +public static class LoggerExtensions +{ + public static IDisposable IndentLog(this ILogger logger, string operationDescription) + { + var start = Stopwatch.GetTimestamp(); + logger.LogInformation("-< Begin: {Operation} >-", operationDescription); + + return Disposable.Create(() => + { + var duration = Stopwatch.GetElapsedTime(start).TotalMilliseconds; + logger.LogInformation("-< End: {Operation} (Took: {Duration:N}ms) >-", operationDescription, duration); + }); + } + + public static void Separator(this ILogger logger) + => logger.LogInformation("-------------------------------------------------------"); +} diff --git a/src/GitVersion.Core/Logging/LoggingModule.cs b/src/GitVersion.Core/Logging/LoggingModule.cs new file mode 100644 index 0000000000..8265ba0dd0 --- /dev/null +++ b/src/GitVersion.Core/Logging/LoggingModule.cs @@ -0,0 +1,111 @@ +using System.IO.Abstractions; +using GitVersion.Extensions; +using GitVersion.Helpers; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Logging; +using Serilog; +using Serilog.Events; +using Serilog.Sinks.SystemConsole.Themes; + +namespace GitVersion.Logging; + +public static class LoggingModule +{ + public static LoggerConfiguration CreateLoggerConfiguration( + Verbosity verbosity = Verbosity.Normal, + bool addConsole = false, + string? logFilePath = null, + IFileSystem? fileSystem = null) + { + var loggerConfiguration = new LoggerConfiguration() + .MinimumLevel.Verbose() + .Enrich.FromLogContext(); + + if (addConsole) + { + loggerConfiguration = AddConsoleLogger(loggerConfiguration, verbosity); + } + + if (!string.IsNullOrWhiteSpace(logFilePath) && fileSystem != null) + { + loggerConfiguration = AddFileLogger(loggerConfiguration, fileSystem, logFilePath, verbosity); + } + + return loggerConfiguration; + } + + public static IServiceCollection AddLogging( + IServiceCollection services, + Verbosity verbosity = Verbosity.Normal, + bool addConsole = false, + string? logFilePath = null, + IFileSystem? fileSystem = null) + { + var loggerConfiguration = CreateLoggerConfiguration(verbosity, addConsole, logFilePath, fileSystem); + + Serilog.Log.Logger = loggerConfiguration.CreateLogger(); + + services.AddLogging(builder => + { + builder.ClearProviders(); + builder.AddSerilog(Serilog.Log.Logger, dispose: true); + builder.SetMinimumLevel(MapVerbosityToMicrosoftLogLevel(verbosity)); + }); + + return services; + } + + private static LoggerConfiguration AddConsoleLogger(LoggerConfiguration configuration, Verbosity verbosity) + { + var logLevel = MapVerbosityToSerilogLevel(verbosity); + + return configuration.WriteTo.Console( + restrictedToMinimumLevel: logLevel, + outputTemplate: "{Level:u} [{Timestamp:yy-MM-dd H:mm:ss:ff}] {Message:lj}{NewLine}{Exception}", + theme: AnsiConsoleTheme.Code, + applyThemeToRedirectedOutput: true + ); + } + + private static LoggerConfiguration AddFileLogger( + LoggerConfiguration configuration, + IFileSystem fileSystem, + string filePath, + Verbosity verbosity) + { + fileSystem.NotNull(); + + var logFile = fileSystem.FileInfo.New(FileSystemHelper.Path.GetFullPath(filePath)); + logFile.Directory?.Create(); + + var logLevel = MapVerbosityToSerilogLevel(verbosity); + + return configuration.WriteTo.File( + path: filePath, + restrictedToMinimumLevel: logLevel, + outputTemplate: "{Level:u} [{Timestamp:yyyy-MM-dd HH:mm:ss}] {Message:lj}{NewLine}{Exception}", + shared: true, + flushToDiskInterval: TimeSpan.FromSeconds(1) + ); + } + + private static LogEventLevel MapVerbosityToSerilogLevel(Verbosity verbosity) => verbosity switch + { + Verbosity.Quiet => LogEventLevel.Error, + Verbosity.Minimal => LogEventLevel.Warning, + Verbosity.Normal => LogEventLevel.Information, + Verbosity.Verbose => LogEventLevel.Verbose, + Verbosity.Diagnostic => LogEventLevel.Debug, + _ => LogEventLevel.Information + }; + + private static Microsoft.Extensions.Logging.LogLevel MapVerbosityToMicrosoftLogLevel(Verbosity verbosity) => verbosity switch + { + Verbosity.Quiet => Microsoft.Extensions.Logging.LogLevel.Error, + Verbosity.Minimal => Microsoft.Extensions.Logging.LogLevel.Warning, + Verbosity.Normal => Microsoft.Extensions.Logging.LogLevel.Information, + Verbosity.Verbose => Microsoft.Extensions.Logging.LogLevel.Debug, + Verbosity.Diagnostic => Microsoft.Extensions.Logging.LogLevel.Trace, + _ => Microsoft.Extensions.Logging.LogLevel.Information + }; +} diff --git a/src/GitVersion.Core/PublicAPI.Unshipped.txt b/src/GitVersion.Core/PublicAPI.Unshipped.txt index 7dc5c58110..54bad99b27 100644 --- a/src/GitVersion.Core/PublicAPI.Unshipped.txt +++ b/src/GitVersion.Core/PublicAPI.Unshipped.txt @@ -1 +1,7 @@ #nullable enable +GitVersion.Logging.LoggerExtensions +static GitVersion.Logging.LoggerExtensions.IndentLog(this Microsoft.Extensions.Logging.ILogger! logger, string! operationDescription) -> System.IDisposable! +static GitVersion.Logging.LoggerExtensions.Separator(this Microsoft.Extensions.Logging.ILogger! logger) -> void +GitVersion.Logging.LoggingModule +static GitVersion.Logging.LoggingModule.AddLogging(Microsoft.Extensions.DependencyInjection.IServiceCollection! services, GitVersion.Logging.Verbosity verbosity = GitVersion.Logging.Verbosity.Normal, bool addConsole = false, string? logFilePath = null, System.IO.Abstractions.IFileSystem? fileSystem = null) -> Microsoft.Extensions.DependencyInjection.IServiceCollection! +static GitVersion.Logging.LoggingModule.CreateLoggerConfiguration(GitVersion.Logging.Verbosity verbosity = GitVersion.Logging.Verbosity.Normal, bool addConsole = false, string? logFilePath = null, System.IO.Abstractions.IFileSystem? fileSystem = null) -> Serilog.LoggerConfiguration! diff --git a/src/GitVersion.Core/VersionCalculation/Caching/GitVersionCacheKeyFactory.cs b/src/GitVersion.Core/VersionCalculation/Caching/GitVersionCacheKeyFactory.cs index 368713f464..389e9e1bb3 100644 --- a/src/GitVersion.Core/VersionCalculation/Caching/GitVersionCacheKeyFactory.cs +++ b/src/GitVersion.Core/VersionCalculation/Caching/GitVersionCacheKeyFactory.cs @@ -5,14 +5,14 @@ using GitVersion.Extensions; using GitVersion.Git; using GitVersion.Helpers; -using GitVersion.Logging; +using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; namespace GitVersion.VersionCalculation.Caching; internal class GitVersionCacheKeyFactory( IFileSystem fileSystem, - ILog log, + ILogger logger, IOptions options, IConfigurationFileLocator configFileLocator, IConfigurationSerializer configurationSerializer, @@ -21,7 +21,7 @@ internal class GitVersionCacheKeyFactory( : IGitVersionCacheKeyFactory { private readonly IFileSystem fileSystem = fileSystem.NotNull(); - private readonly ILog log = log.NotNull(); + private readonly ILogger logger = logger.NotNull(); private readonly IOptions options = options.NotNull(); private readonly IConfigurationFileLocator configFileLocator = configFileLocator.NotNull(); private readonly IConfigurationSerializer configurationSerializer = configurationSerializer.NotNull(); @@ -88,12 +88,12 @@ private List CalculateDirectoryContents(string root) // about the systems on which this code will run. catch (UnauthorizedAccessException e) { - this.log.Error(e.Message); + this.logger.LogError("{Message}", e.Message); continue; } catch (DirectoryNotFoundException e) { - this.log.Error(e.Message); + this.logger.LogError("{Message}", e.Message); continue; } @@ -104,12 +104,12 @@ private List CalculateDirectoryContents(string root) } catch (UnauthorizedAccessException e) { - this.log.Error(e.Message); + this.logger.LogError("{Message}", e.Message); continue; } catch (DirectoryNotFoundException e) { - this.log.Error(e.Message); + this.logger.LogError("{Message}", e.Message); continue; } @@ -123,7 +123,7 @@ private List CalculateDirectoryContents(string root) } catch (IOException e) { - this.log.Error(e.Message); + this.logger.LogError("{Message}", e.Message); } } diff --git a/src/GitVersion.Core/VersionCalculation/Caching/GitVersionCacheProvider.cs b/src/GitVersion.Core/VersionCalculation/Caching/GitVersionCacheProvider.cs index d80979db7a..690f377366 100644 --- a/src/GitVersion.Core/VersionCalculation/Caching/GitVersionCacheProvider.cs +++ b/src/GitVersion.Core/VersionCalculation/Caching/GitVersionCacheProvider.cs @@ -2,6 +2,7 @@ using GitVersion.Extensions; using GitVersion.Git; using GitVersion.Helpers; +using Microsoft.Extensions.Logging; using GitVersion.Logging; using GitVersion.OutputVariables; using Microsoft.Extensions.Options; @@ -10,7 +11,7 @@ namespace GitVersion.VersionCalculation.Caching; internal class GitVersionCacheProvider( IFileSystem fileSystem, - ILog log, + ILogger logger, IOptions options, IVersionVariableSerializer serializer, IGitVersionCacheKeyFactory cacheKeyFactory, @@ -18,7 +19,7 @@ internal class GitVersionCacheProvider( : IGitVersionCacheProvider { private readonly IFileSystem fileSystem = fileSystem.NotNull(); - private readonly ILog log = log.NotNull(); + private readonly ILogger logger = logger.NotNull(); private readonly IOptions options = options.NotNull(); private readonly IVersionVariableSerializer serializer = serializer.NotNull(); private readonly IGitVersionCacheKeyFactory cacheKeyFactory = cacheKeyFactory.NotNull(); @@ -28,7 +29,7 @@ public void WriteVariablesToDiskCache(GitVersionVariables versionVariables) { var cacheKey = GetCacheKey(); var cacheFileName = GetCacheFileName(cacheKey); - using (this.log.IndentLog($"Write version variables to cache file {cacheFileName}")) + using (this.logger.IndentLog($"Write version variables to cache file {cacheFileName}")) { try { @@ -36,7 +37,7 @@ public void WriteVariablesToDiskCache(GitVersionVariables versionVariables) } catch (Exception ex) { - this.log.Error($"Unable to write cache file {cacheFileName}. Got {ex.GetType().FullName} exception."); + this.logger.LogError($"Unable to write cache file {cacheFileName}. Got {ex.GetType().FullName} exception."); } } } @@ -45,11 +46,11 @@ public void WriteVariablesToDiskCache(GitVersionVariables versionVariables) { var cacheKey = GetCacheKey(); var cacheFileName = GetCacheFileName(cacheKey); - using (this.log.IndentLog($"Loading version variables from disk cache file {cacheFileName}")) + using (this.logger.IndentLog($"Loading version variables from disk cache file {cacheFileName}")) { if (!this.fileSystem.File.Exists(cacheFileName)) { - this.log.Info($"Cache file {cacheFileName} not found."); + this.logger.LogInformation($"Cache file {cacheFileName} not found."); return null; } @@ -60,15 +61,15 @@ public void WriteVariablesToDiskCache(GitVersionVariables versionVariables) } catch (Exception ex) { - this.log.Warning($"Unable to read cache file {cacheFileName}, deleting it."); - this.log.Info(ex.ToString()); + this.logger.LogWarning($"Unable to read cache file {cacheFileName}, deleting it."); + this.logger.LogInformation(ex.ToString()); try { this.fileSystem.File.Delete(cacheFileName); } catch (Exception deleteEx) { - this.log.Warning($"Unable to delete corrupted version cache file {cacheFileName}. Got {deleteEx.GetType().FullName} exception."); + this.logger.LogWarning($"Unable to delete corrupted version cache file {cacheFileName}. Got {deleteEx.GetType().FullName} exception."); } return null; diff --git a/src/GitVersion.Core/VersionCalculation/EffectiveBranchConfigurationFinder.cs b/src/GitVersion.Core/VersionCalculation/EffectiveBranchConfigurationFinder.cs index 7d9fc16476..f80c19d98f 100644 --- a/src/GitVersion.Core/VersionCalculation/EffectiveBranchConfigurationFinder.cs +++ b/src/GitVersion.Core/VersionCalculation/EffectiveBranchConfigurationFinder.cs @@ -2,13 +2,13 @@ using GitVersion.Configuration; using GitVersion.Extensions; using GitVersion.Git; -using GitVersion.Logging; +using Microsoft.Extensions.Logging; namespace GitVersion.VersionCalculation; -internal sealed class EffectiveBranchConfigurationFinder(ILog log, IRepositoryStore repositoryStore) : IEffectiveBranchConfigurationFinder +internal sealed class EffectiveBranchConfigurationFinder(ILogger logger, IRepositoryStore repositoryStore) : IEffectiveBranchConfigurationFinder { - private readonly ILog log = log.NotNull(); + private readonly ILogger logger = logger.NotNull(); private readonly IRepositoryStore repositoryStore = repositoryStore.NotNull(); public IEnumerable GetConfigurations(IBranch branch, IGitVersionConfiguration configuration) @@ -41,7 +41,7 @@ private IEnumerable GetEffectiveConfigurationsRecu // Because the actual branch is marked with the inherit increment strategy we need to either skip the iteration or go further // while inheriting from the fallback branch configuration. This behavior is configurable via the increment settings of the configuration. var skipTraversingOfOrphanedBranches = configuration.Increment == IncrementStrategy.Inherit; - this.log.Info( + this.logger.LogInformation( $"An orphaned branch '{branch}' has been detected and will be skipped={skipTraversingOfOrphanedBranches}." ); if (skipTraversingOfOrphanedBranches) yield break; diff --git a/src/GitVersion.Core/VersionCalculation/VersionCalculators/ContinuousDeliveryVersionCalculator.cs b/src/GitVersion.Core/VersionCalculation/VersionCalculators/ContinuousDeliveryVersionCalculator.cs index 91098dae31..1c6c5f0ad8 100644 --- a/src/GitVersion.Core/VersionCalculation/VersionCalculators/ContinuousDeliveryVersionCalculator.cs +++ b/src/GitVersion.Core/VersionCalculation/VersionCalculators/ContinuousDeliveryVersionCalculator.cs @@ -1,16 +1,17 @@ using GitVersion.Common; using GitVersion.Git; +using Microsoft.Extensions.Logging; using GitVersion.Logging; namespace GitVersion.VersionCalculation; internal sealed class ContinuousDeliveryVersionCalculator( - ILog log, IRepositoryStore repositoryStore, Lazy versionContext) - : VersionCalculatorBase(log, repositoryStore, versionContext), IDeploymentModeCalculator + ILogger logger, IRepositoryStore repositoryStore, Lazy versionContext) + : VersionCalculatorBase(logger, repositoryStore, versionContext), IDeploymentModeCalculator { public SemanticVersion Calculate(SemanticVersion semanticVersion, ICommit? baseVersionSource) { - using (this.log.IndentLog("Using continuous delivery workflow to calculate the incremented version.")) + using (this.logger.IndentLog("Using continuous delivery workflow to calculate the incremented version.")) { var preReleaseTag = semanticVersion.PreReleaseTag; if (!preReleaseTag.HasTag() || !preReleaseTag.Number.HasValue) diff --git a/src/GitVersion.Core/VersionCalculation/VersionCalculators/ContinuousDeploymentVersionCalculator.cs b/src/GitVersion.Core/VersionCalculation/VersionCalculators/ContinuousDeploymentVersionCalculator.cs index eb8bcc3acc..3a03ab24fe 100644 --- a/src/GitVersion.Core/VersionCalculation/VersionCalculators/ContinuousDeploymentVersionCalculator.cs +++ b/src/GitVersion.Core/VersionCalculation/VersionCalculators/ContinuousDeploymentVersionCalculator.cs @@ -1,16 +1,17 @@ using GitVersion.Common; using GitVersion.Git; +using Microsoft.Extensions.Logging; using GitVersion.Logging; namespace GitVersion.VersionCalculation; internal sealed class ContinuousDeploymentVersionCalculator( - ILog log, IRepositoryStore repositoryStore, Lazy versionContext) - : VersionCalculatorBase(log, repositoryStore, versionContext), IDeploymentModeCalculator + ILogger logger, IRepositoryStore repositoryStore, Lazy versionContext) + : VersionCalculatorBase(logger, repositoryStore, versionContext), IDeploymentModeCalculator { public SemanticVersion Calculate(SemanticVersion semanticVersion, ICommit? baseVersionSource) { - using (this.log.IndentLog("Using continuous deployment workflow to calculate the incremented version.")) + using (this.logger.IndentLog("Using continuous deployment workflow to calculate the incremented version.")) { return CalculateInternal(semanticVersion, baseVersionSource); } diff --git a/src/GitVersion.Core/VersionCalculation/VersionCalculators/ManualDeploymentVersionCalculator.cs b/src/GitVersion.Core/VersionCalculation/VersionCalculators/ManualDeploymentVersionCalculator.cs index 537ee7b360..b8f0706df9 100644 --- a/src/GitVersion.Core/VersionCalculation/VersionCalculators/ManualDeploymentVersionCalculator.cs +++ b/src/GitVersion.Core/VersionCalculation/VersionCalculators/ManualDeploymentVersionCalculator.cs @@ -1,16 +1,17 @@ using GitVersion.Common; using GitVersion.Git; +using Microsoft.Extensions.Logging; using GitVersion.Logging; namespace GitVersion.VersionCalculation; internal sealed class ManualDeploymentVersionCalculator( - ILog log, IRepositoryStore repositoryStore, Lazy versionContext) - : VersionCalculatorBase(log, repositoryStore, versionContext), IDeploymentModeCalculator + ILogger logger, IRepositoryStore repositoryStore, Lazy versionContext) + : VersionCalculatorBase(logger, repositoryStore, versionContext), IDeploymentModeCalculator { public SemanticVersion Calculate(SemanticVersion semanticVersion, ICommit? baseVersionSource) { - using (this.log.IndentLog("Using manual deployment workflow to calculate the incremented version.")) + using (this.logger.IndentLog("Using manual deployment workflow to calculate the incremented version.")) { return CalculateInternal(semanticVersion, baseVersionSource); } diff --git a/src/GitVersion.Core/VersionCalculation/VersionCalculators/NextVersionCalculator.cs b/src/GitVersion.Core/VersionCalculation/VersionCalculators/NextVersionCalculator.cs index fc38d26801..65bbb88974 100644 --- a/src/GitVersion.Core/VersionCalculation/VersionCalculators/NextVersionCalculator.cs +++ b/src/GitVersion.Core/VersionCalculation/VersionCalculators/NextVersionCalculator.cs @@ -4,12 +4,13 @@ using GitVersion.Core; using GitVersion.Extensions; using GitVersion.Git; +using Microsoft.Extensions.Logging; using GitVersion.Logging; namespace GitVersion.VersionCalculation; internal class NextVersionCalculator( - ILog log, + ILogger logger, Lazy versionContext, IEnumerable deploymentModeCalculators, IEnumerable versionStrategies, @@ -17,7 +18,7 @@ internal class NextVersionCalculator( ITaggedSemanticVersionService taggedSemanticVersionService) : INextVersionCalculator { - private readonly ILog log = log.NotNull(); + private readonly ILogger logger = log.NotNull(); private readonly Lazy versionContext = versionContext.NotNull(); private readonly IVersionStrategy[] versionStrategies = [.. versionStrategies.NotNull()]; private readonly IEffectiveBranchConfigurationFinder effectiveBranchConfigurationFinder = effectiveBranchConfigurationFinder.NotNull(); @@ -26,7 +27,7 @@ internal class NextVersionCalculator( public virtual SemanticVersion FindVersion() { - this.log.Info($"Running against branch: {Context.CurrentBranch} ({Context.CurrentCommit.ToString() ?? "-"})"); + this.logger.LogInformation($"Running against branch: {Context.CurrentBranch} ({Context.CurrentCommit.ToString() ?? "-"})"); var branchConfiguration = Context.Configuration.GetBranchConfiguration(Context.CurrentBranch); EffectiveConfiguration effectiveConfiguration = new(Context.Configuration, branchConfiguration); @@ -154,7 +155,7 @@ private SemanticVersion CalculateSemanticVersion( private NextVersion CalculateNextVersion(IBranch branch, IGitVersionConfiguration configuration) { var nextVersions = GetNextVersions(branch, configuration); - log.Separator(); + logger.Separator(); var maxVersion = nextVersions.Max() ?? throw new GitVersionException("No base versions determined on the current branch."); @@ -171,7 +172,7 @@ private NextVersion CalculateNextVersion(IBranch branch, IGitVersionConfiguratio var latestVersion = matchingVersionsOnceIncremented.Aggregate(CompareVersions); latestBaseVersionSource = latestVersion.BaseVersion.BaseVersionSource; maxVersion = latestVersion; - log.Info( + logger.LogInformation( $"Found multiple base versions which will produce the same SemVer ({maxVersion.IncrementedVersion}), " + $"taking latest source for commit counting ({latestVersion.BaseVersion.Source})"); } @@ -208,8 +209,8 @@ private NextVersion CalculateNextVersion(IBranch branch, IGitVersionConfiguratio } }; - log.Info($"Base version used: {calculatedBase}"); - log.Separator(); + logger.LogInformation($"Base version used: {calculatedBase}"); + logger.Separator(); return new(maxVersion.IncrementedVersion, calculatedBase, maxVersion.BranchConfiguration); } @@ -229,7 +230,7 @@ private static NextVersion CompareVersions(NextVersion version1, NextVersion ver private List GetNextVersions(IBranch branch, IGitVersionConfiguration configuration) { - using (log.IndentLog("Fetching the base versions for version calculation...")) + using (logger.IndentLog("Fetching the base versions for version calculation...")) { if (branch.Tip == null) throw new GitVersionException("No commits found on the current branch."); @@ -242,7 +243,7 @@ IEnumerable GetNextVersionsInternal() var effectiveBranchConfigurations = this.effectiveBranchConfigurationFinder.GetConfigurations(branch, configuration).ToArray(); foreach (var effectiveBranchConfiguration in effectiveBranchConfigurations) { - using (this.log.IndentLog($"Calculating base versions for '{effectiveBranchConfiguration.Branch.Name}'")) + using (this.logger.IndentLog($"Calculating base versions for '{effectiveBranchConfiguration.Branch.Name}'")) { var strategies = this.versionStrategies.ToList(); var fallbackVersionStrategy = strategies.Find(element => element is FallbackVersionStrategy); @@ -257,11 +258,11 @@ IEnumerable GetNextVersionsInternal() { if (atLeastOneBaseVersionReturned && versionStrategy is FallbackVersionStrategy) continue; - using (this.log.IndentLog($"[Using '{versionStrategy.GetType().Name}' strategy]")) + using (this.logger.IndentLog($"[Using '{versionStrategy.GetType().Name}' strategy]")) { foreach (var baseVersion in versionStrategy.GetBaseVersions(effectiveBranchConfiguration)) { - log.Info(baseVersion.ToString()); + logger.LogInformation(baseVersion.ToString()); if (!IncludeVersion(baseVersion, configuration.Ignore)) continue; atLeastOneBaseVersionReturned = true; @@ -285,7 +286,7 @@ private bool IncludeVersion(IBaseVersion baseVersion, IIgnoreConfiguration ignor if (!versionFilter.Exclude(baseVersion, out var reason)) continue; if (reason != null) { - this.log.Info(reason); + this.logger.LogInformation(reason); } return false; diff --git a/src/GitVersion.Core/VersionCalculation/VersionCalculators/VersionCalculatorBase.cs b/src/GitVersion.Core/VersionCalculation/VersionCalculators/VersionCalculatorBase.cs index db6c3eb135..be78972dfe 100644 --- a/src/GitVersion.Core/VersionCalculation/VersionCalculators/VersionCalculatorBase.cs +++ b/src/GitVersion.Core/VersionCalculation/VersionCalculators/VersionCalculatorBase.cs @@ -1,14 +1,14 @@ using GitVersion.Common; using GitVersion.Extensions; using GitVersion.Git; -using GitVersion.Logging; +using Microsoft.Extensions.Logging; namespace GitVersion.VersionCalculation; -internal abstract class VersionCalculatorBase( - ILog log, IRepositoryStore repositoryStore, Lazy versionContext) +internal abstract class VersionCalculatorBase( + ILogger logger, IRepositoryStore repositoryStore, Lazy versionContext) { - protected readonly ILog log = log.NotNull(); + protected readonly ILogger logger = logger.NotNull(); protected readonly IRepositoryStore repositoryStore = repositoryStore.NotNull(); private readonly Lazy versionContext = versionContext.NotNull(); @@ -23,7 +23,8 @@ protected SemanticVersionBuildMetaData CreateVersionBuildMetaData(ICommit? baseV ); var commitsSinceTag = commitLogs.Count; - this.log.Info($"{commitsSinceTag} commits found between {baseVersionSource} and {Context.CurrentCommit}"); + this.logger.LogInformation("{CommitsSinceTag} commits found between {BaseVersionSource} and {CurrentCommit}", + commitsSinceTag, baseVersionSource, Context.CurrentCommit); var shortSha = Context.CurrentCommit.Id.ToString(7); return new SemanticVersionBuildMetaData( diff --git a/src/GitVersion.Core/VersionCalculation/VersionSearchStrategies/MergeMessageVersionStrategy.cs b/src/GitVersion.Core/VersionCalculation/VersionSearchStrategies/MergeMessageVersionStrategy.cs index 8731031a8d..bedb2139c8 100644 --- a/src/GitVersion.Core/VersionCalculation/VersionSearchStrategies/MergeMessageVersionStrategy.cs +++ b/src/GitVersion.Core/VersionCalculation/VersionSearchStrategies/MergeMessageVersionStrategy.cs @@ -2,7 +2,7 @@ using GitVersion.Configuration; using GitVersion.Extensions; using GitVersion.Git; -using GitVersion.Logging; +using Microsoft.Extensions.Logging; namespace GitVersion.VersionCalculation; @@ -11,11 +11,11 @@ namespace GitVersion.VersionCalculation; /// BaseVersionSource is the commit where the message was found. /// Increments if PreventIncrementOfMergedBranchVersion (from the branch configuration) is false. /// -internal sealed class MergeMessageVersionStrategy(ILog log, Lazy contextLazy, +internal sealed class MergeMessageVersionStrategy(ILogger logger, Lazy contextLazy, IRepositoryStore repositoryStore, IIncrementStrategyFinder incrementStrategyFinder) : IVersionStrategy { - private readonly ILog log = log.NotNull(); + private readonly ILogger logger = log.NotNull(); private readonly Lazy contextLazy = contextLazy.NotNull(); private readonly IRepositoryStore repositoryStore = repositoryStore.NotNull(); private readonly IIncrementStrategyFinder incrementStrategyFinder = incrementStrategyFinder.NotNull(); @@ -44,7 +44,7 @@ private IEnumerable GetBaseVersionsInternal(EffectiveBranchConfigur continue; } - this.log.Info($"Found commit [{commit}] matching merge message format: {mergeMessage.FormatName}"); + this.logger.LogInformation($"Found commit [{commit}] matching merge message format: {mergeMessage.FormatName}"); var baseVersionSource = commit; if (commit.IsMergeCommit()) diff --git a/src/GitVersion.Core/VersionCalculation/VersionSearchStrategies/TaggedCommitVersionStrategy.cs b/src/GitVersion.Core/VersionCalculation/VersionSearchStrategies/TaggedCommitVersionStrategy.cs index 4e08eef9c8..7437131a4b 100644 --- a/src/GitVersion.Core/VersionCalculation/VersionSearchStrategies/TaggedCommitVersionStrategy.cs +++ b/src/GitVersion.Core/VersionCalculation/VersionSearchStrategies/TaggedCommitVersionStrategy.cs @@ -1,7 +1,7 @@ using GitVersion.Configuration; using GitVersion.Core; using GitVersion.Extensions; -using GitVersion.Logging; +using Microsoft.Extensions.Logging; namespace GitVersion.VersionCalculation; @@ -11,13 +11,13 @@ namespace GitVersion.VersionCalculation; /// Increments if the tag is not the current commit. /// internal sealed class TaggedCommitVersionStrategy( - ILog log, + ILogger logger, Lazy contextLazy, ITaggedSemanticVersionService taggedSemanticVersionService, IIncrementStrategyFinder incrementStrategyFinder) : IVersionStrategy { - private readonly ILog log = log.NotNull(); + private readonly ILogger logger = log.NotNull(); private readonly ITaggedSemanticVersionService taggedSemanticVersionService = taggedSemanticVersionService.NotNull(); private readonly Lazy contextLazy = contextLazy.NotNull(); private readonly IIncrementStrategyFinder incrementStrategyFinder = incrementStrategyFinder.NotNull(); @@ -60,7 +60,7 @@ private IEnumerable GetBaseVersionsInternal(EffectiveBranchConfigur ); if (highestPossibleSemanticVersion.IsLessThan(semanticVersionTreshold, includePreRelease: false)) { - this.log.Info( + this.logger.LogInformation( $"The tag '{semanticVersion.Value}' is skipped because it provides a lower base version than other tags." ); alternativeSemanticVersionsWithTag.Clear();