Skip to content

Add check to see if a logger is enabled before logging #1144

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 2 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion src/GitVersionCore.Tests/ModuleInitializer.cs
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ public static class ModuleInitializer
/// </summary>
public static void Initialize()
{
Logger.SetLoggers(
Logger.SetLoggers(VerbosityLevel.Debug,
s => Console.WriteLine(s),
s => Console.WriteLine(s),
s => Console.WriteLine(s),
Expand Down
8 changes: 4 additions & 4 deletions src/GitVersionCore/BranchConfigurationCalculator.cs
Original file line number Diff line number Diff line change
Expand Up @@ -32,9 +32,9 @@ public static BranchConfig GetBranchConfiguration(GitVersionContext context, Bra
}
else
{
Logger.WriteInfo(string.Format(
"No branch configuration found for branch {0}, falling back to default configuration",
targetBranch.FriendlyName));
if (Logger.IsInfoEnabled) Logger.WriteInfo(string.Format(
"No branch configuration found for branch {0}, falling back to default configuration",
targetBranch.FriendlyName));

branchConfiguration = new BranchConfig { Name = string.Empty };
ConfigurationProvider.ApplyBranchDefaults(context.FullConfiguration, branchConfiguration, "");
Expand Down Expand Up @@ -119,7 +119,7 @@ static BranchConfig InheritBranchConfiguration(GitVersionContext context, Branch
}
}

Logger.WriteInfo("Found possible parent branches: " + string.Join(", ", possibleParents.Select(p => p.FriendlyName)));
if (Logger.IsInfoEnabled) Logger.WriteInfo("Found possible parent branches: " + string.Join(", ", possibleParents.Select(p => p.FriendlyName)));

if (possibleParents.Count == 1)
{
Expand Down
7 changes: 5 additions & 2 deletions src/GitVersionCore/ExecuteCore.cs
Original file line number Diff line number Diff line change
Expand Up @@ -42,8 +42,11 @@ public VersionVariables ExecuteGitVersion(string targetUrl, string dynamicReposi
// },
// Directory = workingDirectory
//});
Logger.WriteInfo(string.Format("Project root is: {0}", projectRoot));
Logger.WriteInfo(string.Format("DotGit directory is: {0}", dotGitDirectory));
if (Logger.IsInfoEnabled)
{
Logger.WriteInfo(string.Format("Project root is: {0}", projectRoot));
Logger.WriteInfo(string.Format("DotGit directory is: {0}", dotGitDirectory));
}
if (string.IsNullOrEmpty(dotGitDirectory) || string.IsNullOrEmpty(projectRoot))
{
// TODO Link to wiki article
Expand Down
4 changes: 2 additions & 2 deletions src/GitVersionCore/GitPreparer.cs
Original file line number Diff line number Diff line change
Expand Up @@ -125,7 +125,7 @@ public string GetDotGitDirectory()

public string GetProjectRootDirectory()
{
Logger.WriteInfo(string.Format("IsDynamicGitRepository: {0}", IsDynamicGitRepository));
if(Logger.IsInfoEnabled) Logger.WriteInfo(string.Format("IsDynamicGitRepository: {0}", IsDynamicGitRepository));
if (IsDynamicGitRepository)
{
Logger.WriteInfo(string.Format("Returning Project Root as {0}", targetPath));
Expand All @@ -134,7 +134,7 @@ public string GetProjectRootDirectory()

var dotGetGitDirectory = GetDotGitDirectory();
var result = Directory.GetParent(dotGetGitDirectory).FullName;
Logger.WriteInfo(string.Format("Returning Project Root from DotGitDirectory: {0} - {1}", dotGetGitDirectory, result));
if (Logger.IsInfoEnabled) Logger.WriteInfo(string.Format("Returning Project Root from DotGitDirectory: {0} - {1}", dotGetGitDirectory, result));
return result;
}

Expand Down
14 changes: 7 additions & 7 deletions src/GitVersionCore/GitRepoMetadataProvider.cs
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,7 @@ public IEnumerable<Branch> GetBranchesContainingCommit([NotNull] Commit commit,
using (Logger.IndentLog(string.Format("Getting branches containing the commit '{0}'.", commit.Id)))
{
var directBranchHasBeenFound = false;
Logger.WriteInfo("Trying to find direct branches.");
if (Logger.IsInfoEnabled) Logger.WriteInfo("Trying to find direct branches.");
// TODO: It looks wasteful looping through the branches twice. Can't these loops be merged somehow? @asbjornu
foreach (var branch in branches)
{
Expand All @@ -81,10 +81,10 @@ public IEnumerable<Branch> GetBranchesContainingCommit([NotNull] Commit commit,
yield break;
}

Logger.WriteInfo(string.Format("No direct branches found, searching through {0} branches.", onlyTrackedBranches ? "tracked" : "all"));
if (Logger.IsInfoEnabled) Logger.WriteInfo(string.Format("No direct branches found, searching through {0} branches.", onlyTrackedBranches ? "tracked" : "all"));
foreach (var branch in branches.Where(b => onlyTrackedBranches && !b.IsTracking))
{
Logger.WriteInfo(string.Format("Searching for commits reachable from '{0}'.", branch.FriendlyName));
if (Logger.IsInfoEnabled) Logger.WriteInfo(string.Format("Searching for commits reachable from '{0}'.", branch.FriendlyName));

var commits = this.Repository.Commits.QueryBy(new CommitFilter
{
Expand All @@ -93,11 +93,11 @@ public IEnumerable<Branch> GetBranchesContainingCommit([NotNull] Commit commit,

if (!commits.Any())
{
Logger.WriteInfo(string.Format("The branch '{0}' has no matching commits.", branch.FriendlyName));
if (Logger.IsInfoEnabled) Logger.WriteInfo(string.Format("The branch '{0}' has no matching commits.", branch.FriendlyName));
continue;
}

Logger.WriteInfo(string.Format("The branch '{0}' has a matching commit.", branch.FriendlyName));
if (Logger.IsInfoEnabled) Logger.WriteInfo(string.Format("The branch '{0}' has a matching commit.", branch.FriendlyName));
yield return branch;
}
}
Expand Down Expand Up @@ -131,7 +131,7 @@ public Commit FindMergeBase(Branch branch, Branch otherBranch)
var findMergeBase = this.Repository.ObjectDatabase.FindMergeBase(commit, commitToFindCommonBase);
if (findMergeBase != null)
{
Logger.WriteInfo(string.Format("Found merge base of {0}", findMergeBase.Sha));
if (Logger.IsInfoEnabled) Logger.WriteInfo(string.Format("Found merge base of {0}", findMergeBase.Sha));
// We do not want to include merge base commits which got forward merged into the other branch
bool mergeBaseWasForwardMerge;
do
Expand All @@ -150,7 +150,7 @@ public Commit FindMergeBase(Branch branch, Branch otherBranch)
break;
}
findMergeBase = mergeBase;
Logger.WriteInfo(string.Format("Merge base was due to a forward merge, next merge base is {0}", findMergeBase));
if (Logger.IsInfoEnabled) Logger.WriteInfo(string.Format("Merge base was due to a forward merge, next merge base is {0}", findMergeBase));
}
} while (mergeBaseWasForwardMerge);
}
Expand Down
2 changes: 1 addition & 1 deletion src/GitVersionCore/GitVersionCache.cs
Original file line number Diff line number Diff line change
Expand Up @@ -74,7 +74,7 @@ public VersionVariables LoadVersionVariablesFromDiskCache(GitPreparer gitPrepare
var cacheFileName = GetCacheFileName(key, cacheDir);
if (!fileSystem.Exists(cacheFileName))
{
Logger.WriteInfo("Cache file " + cacheFileName + " not found.");
if (Logger.IsInfoEnabled) Logger.WriteInfo("Cache file " + cacheFileName + " not found.");
return null;
}

Expand Down
2 changes: 1 addition & 1 deletion src/GitVersionCore/GitVersionContext.cs
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@ public GitVersionContext(IRepository repository, Branch currentBranch, Config co

if (CurrentCommit == null)
{
Logger.WriteInfo("Using latest commit on specified branch");
if (Logger.IsInfoEnabled) Logger.WriteInfo("Using latest commit on specified branch");
CurrentCommit = currentBranch.Tip;
}

Expand Down
8 changes: 4 additions & 4 deletions src/GitVersionCore/GitVersionFinder.cs
Original file line number Diff line number Diff line change
Expand Up @@ -8,10 +8,10 @@ public class GitVersionFinder
{
public SemanticVersion FindVersion(GitVersionContext context)
{
Logger.WriteInfo(string.Format(
"Running against branch: {0} ({1})",
context.CurrentBranch.FriendlyName,
context.CurrentCommit == null ? "-" : context.CurrentCommit.Sha));
if (Logger.IsInfoEnabled) Logger.WriteInfo(string.Format(
"Running against branch: {0} ({1})",
context.CurrentBranch.FriendlyName,
context.CurrentCommit == null ? "-" : context.CurrentCommit.Sha));
EnsureMainTopologyConstraints(context);

var filePath = Path.Combine(context.Repository.GetRepositoryDirectory(), "NextVersion.txt");
Expand Down
58 changes: 47 additions & 11 deletions src/GitVersionCore/Logger.cs
Original file line number Diff line number Diff line change
Expand Up @@ -14,13 +14,19 @@ static Logger()
Reset();
}

public static bool IsDebugEnabled;
public static bool IsInfoEnabled;
public static bool IsWarningEnabled;
public static bool IsErrorEnabled;

public static Action<string> WriteDebug { get; private set; }
public static Action<string> WriteInfo { get; private set; }
public static Action<string> WriteWarning { get; private set; }
public static Action<string> WriteError { get; private set; }

public static IDisposable IndentLog(string operationDescription)
{
if (!IsInfoEnabled) return new ActionDisposable(() => { });
var start = DateTime.Now;
WriteInfo("Begin: " + operationDescription);
indent = indent + " ";
Expand All @@ -41,17 +47,47 @@ static Action<string> ObscurePassword(Action<string> info)
return logAction;
}

public static void SetLoggers(Action<string> debug, Action<string> info, Action<string> warn, Action<string> error)
public static void SetLoggers(VerbosityLevel verbosity, Action<string> debug, Action<string> info, Action<string> warn, Action<string> error)
{
if (debug == null) throw new ArgumentNullException("debug");
if (info == null) throw new ArgumentNullException("info");
if (warn == null) throw new ArgumentNullException("warn");
if (error == null) throw new ArgumentNullException("error");

WriteDebug = LogMessage(ObscurePassword(debug), "DEBUG");
WriteInfo = LogMessage(ObscurePassword(info), "INFO");
WriteWarning = LogMessage(ObscurePassword(warn), "WARN");
WriteError = LogMessage(ObscurePassword(error), "ERROR");
if (verbosity >= VerbosityLevel.Debug)
{
if (debug == null) throw new ArgumentNullException("debug");
IsDebugEnabled = true;
WriteDebug = LogMessage(ObscurePassword(debug), "DEBUG");
}
else {
WriteDebug = (m) => { };
}
if (verbosity >= VerbosityLevel.Info)
{
if (info == null) throw new ArgumentNullException("Info");
IsInfoEnabled = true;
WriteInfo = LogMessage(ObscurePassword(info), "INFO");
}
else
{
WriteInfo = (m) => { };
}
if (verbosity >= VerbosityLevel.Warn)
{
if (warn == null) throw new ArgumentNullException("Warn");
IsWarningEnabled = true;
WriteWarning = LogMessage(ObscurePassword(warn), "WARN");
}
else
{
WriteWarning = (m) => { };
}
if (verbosity >= VerbosityLevel.Error)
{
if (error == null) throw new ArgumentNullException("Error");
IsErrorEnabled = true;
WriteError = LogMessage(ObscurePassword(error), "ERROR");
}
else
{
WriteError = (m) => { };
}
}

public static IDisposable AddLoggersTemporarily(Action<string> debug, Action<string> info, Action<string> warn, Action<string> error)
Expand All @@ -60,7 +96,7 @@ public static IDisposable AddLoggersTemporarily(Action<string> debug, Action<str
var currentInfo = WriteInfo;
var currentWarn = WriteWarning;
var currentError = WriteError;
SetLoggers(s =>
SetLoggers(VerbosityLevel.Debug, s =>
{
debug(s);
currentDebug(s);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -23,14 +23,14 @@ public BaseVersion GetBaseVersion(GitVersionContext context)
{
if (v == null) return false;

Logger.WriteInfo(v.ToString());
if (Logger.IsInfoEnabled) Logger.WriteInfo(v.ToString());

foreach (var filter in context.Configuration.VersionFilters)
{
string reason;
if (filter.Exclude(v, out reason))
{
Logger.WriteInfo(reason);
if (Logger.IsInfoEnabled) Logger.WriteInfo(reason);
return false;
}
}
Expand All @@ -52,7 +52,7 @@ public BaseVersion GetBaseVersion(GitVersionContext context)
if (matchingVersionsOnceIncremented.Any())
{
baseVersionWithOldestSource = matchingVersionsOnceIncremented.Aggregate((v1, v2) => v1.Version.BaseVersionSource.Committer.When < v2.Version.BaseVersionSource.Committer.When ? v1 : v2).Version;
Logger.WriteInfo(string.Format(
if (Logger.IsInfoEnabled) Logger.WriteInfo(string.Format(
"Found multiple base versions which will produce the same SemVer ({0}), taking oldest source for commit counting ({1})",
maxVersion.IncrementedVersion,
baseVersionWithOldestSource.Source));
Expand All @@ -74,7 +74,7 @@ public BaseVersion GetBaseVersion(GitVersionContext context)
context, maxVersion.Version.Source, maxVersion.Version.ShouldIncrement, maxVersion.Version.SemanticVersion,
baseVersionWithOldestSource.BaseVersionSource, maxVersion.Version.BranchNameOverride);

Logger.WriteInfo(string.Format("Base version used: {0}", calculatedBase));
if (Logger.IsInfoEnabled) Logger.WriteInfo(string.Format("Base version used: {0}", calculatedBase));

return calculatedBase;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ public SemanticVersionBuildMetaData Create(Commit baseVersionSource, GitVersionC

var commitLog = context.Repository.Commits.QueryBy(qf);
var commitsSinceTag = commitLog.Count();
Logger.WriteInfo(string.Format("{0} commits found between {1} and {2}", commitsSinceTag, baseVersionSource.Sha, context.CurrentCommit.Sha));
if (Logger.IsInfoEnabled) Logger.WriteInfo(string.Format("{0} commits found between {1} and {2}", commitsSinceTag, baseVersionSource.Sha, context.CurrentCommit.Sha));

return new SemanticVersionBuildMetaData(
commitsSinceTag,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -286,7 +286,7 @@ public static string GetBranchSpecificTag(EffectiveConfiguration configuration,
}
if (tagToUse.Contains("{BranchName}"))
{
Logger.WriteInfo("Using branch name to calculate version tag");
if (Logger.IsInfoEnabled) Logger.WriteInfo("Using branch name to calculate version tag");

var branchName = branchNameOverride ?? branchFriendlyName;
if (!string.IsNullOrWhiteSpace(configuration.BranchPrefixToTrim))
Expand Down
12 changes: 6 additions & 6 deletions src/GitVersionExe/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -81,7 +81,7 @@ static int VerifyArgumentsAndRun()
}
else
{
Logger.WriteInfo("Working directory: " + arguments.TargetPath);
if (Logger.IsInfoEnabled) Logger.WriteInfo("Working directory: " + arguments.TargetPath);
}
VerifyConfiguration(arguments, fileSystem);

Expand Down Expand Up @@ -179,11 +179,11 @@ static void ConfigureLogging(Arguments arguments)
}
}

Logger.SetLoggers(
s => writeActions.ForEach(a => { if (arguments.Verbosity >= VerbosityLevel.Debug) a(s); }),
s => writeActions.ForEach(a => { if (arguments.Verbosity >= VerbosityLevel.Info) a(s); }),
s => writeActions.ForEach(a => { if (arguments.Verbosity >= VerbosityLevel.Warn) a(s); }),
s => writeActions.ForEach(a => { if (arguments.Verbosity >= VerbosityLevel.Error) a(s); }));
Logger.SetLoggers(arguments.Verbosity,
s => writeActions.ForEach(a => { a(s); }),
s => writeActions.ForEach(a => { a(s); }),
s => writeActions.ForEach(a => { a(s); }),
s => writeActions.ForEach(a => { a(s); }));

if (exception != null)
Logger.WriteError(string.Format("Failed to configure logging for '{0}': {1}", arguments.LogFilePath, exception.Message));
Expand Down
2 changes: 1 addition & 1 deletion src/GitVersionExe/SpecifiedArgumentRunner.cs
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ class SpecifiedArgumentRunner

public static void Run(Arguments arguments, IFileSystem fileSystem)
{
Logger.WriteInfo(string.Format("Running on {0}.", runningOnMono ? "Mono" : "Windows"));
if (Logger.IsInfoEnabled) Logger.WriteInfo(string.Format("Running on {0}.", runningOnMono ? "Mono" : "Windows"));

var noFetch = arguments.NoFetch;
var authentication = arguments.Authentication;
Expand Down
2 changes: 1 addition & 1 deletion src/GitVersionTask.Tests/ModuleInitializer.cs
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ public static class ModuleInitializer
/// </summary>
public static void Initialize()
{
Logger.SetLoggers(
Logger.SetLoggers(VerbosityLevel.Debug,
s => System.Console.WriteLine(s),
s => System.Console.WriteLine(s),
s => System.Console.WriteLine(s),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ public UpdateAssemblyInfo()
{
};
logger = new TaskLogger(this);
Logger.SetLoggers(this.LogDebug, this.LogInfo, this.LogWarning, s => this.LogError(s));
Logger.SetLoggers(VerbosityLevel.Debug, this.LogDebug, this.LogInfo, this.LogWarning, s => this.LogError(s));
}

[Required]
Expand Down
2 changes: 1 addition & 1 deletion src/GitVersionTask/GetVersion.cs
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ public class GetVersion : GitVersionTaskBase
public GetVersion()
{
logger = new TaskLogger(this);
Logger.SetLoggers(this.LogDebug, this.LogInfo, this.LogWarning, s => this.LogError(s));
Logger.SetLoggers(VerbosityLevel.Debug, this.LogDebug, this.LogInfo, this.LogWarning, s => this.LogError(s));
}

[Required]
Expand Down
2 changes: 1 addition & 1 deletion src/GitVersionTask/WriteVersionInfoToBuildLog.cs
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ public class WriteVersionInfoToBuildLog : GitVersionTaskBase
public WriteVersionInfoToBuildLog()
{
logger = new TaskLogger(this);
Logger.SetLoggers(this.LogDebug, this.LogInfo, this.LogWarning, s => this.LogError(s));
Logger.SetLoggers(VerbosityLevel.Debug, this.LogDebug, this.LogInfo, this.LogWarning, s => this.LogError(s));
}

[Required]
Expand Down