Skip to content
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

Use string interpolation #2337

Merged
merged 2 commits into from
Oct 12, 2017
Merged
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
4 changes: 1 addition & 3 deletions src/NLog/Config/NLogXmlElement.cs
Original file line number Diff line number Diff line change
Expand Up @@ -253,9 +253,7 @@ private void Parse(XmlReader reader)
else
{
string message =
string.Format(
"Duplicate attribute detected. Attribute name: [{0}]. Duplicate value:[{1}], Current value:[{2}]",
reader.LocalName, reader.Value, this.AttributeValues[reader.LocalName]);
$"Duplicate attribute detected. Attribute name: [{reader.LocalName}]. Duplicate value:[{reader.Value}], Current value:[{this.AttributeValues[reader.LocalName]}]";
_parsingErrors.Add(message);
}
}
Expand Down
2 changes: 1 addition & 1 deletion src/NLog/Internal/EnumHelpers.cs
Original file line number Diff line number Diff line change
Expand Up @@ -90,7 +90,7 @@ private static bool TryParseEnum_net3<TEnum>(string value, bool ignoreCase, out

var enumType = typeof(TEnum);
if (!enumType.IsEnum)
throw new ArgumentException(string.Format("Type '{0}' is not an enum", enumType.FullName));
throw new ArgumentException($"Type '{enumType.FullName}' is not an enum");



Expand Down
2 changes: 1 addition & 1 deletion src/NLog/Internal/SimpleStringReader.cs
Original file line number Diff line number Diff line change
Expand Up @@ -77,7 +77,7 @@ string CurrentState
var current = (char)Peek();
var done = Substring(0, Position - 1);
var todo = ((Position > _text.Length) ? Text.Substring(Position + 1) : "");
return string.Format("done: '{0}'. current: '{1}'. todo: '{2}'", done, current, todo);
return $"done: '{done}'. current: '{current}'. todo: '{todo}'";
}
}
#endif
Expand Down
2 changes: 1 addition & 1 deletion src/NLog/LayoutRenderers/AssemblyVersionLayoutRenderer.cs
Original file line number Diff line number Diff line change
Expand Up @@ -88,7 +88,7 @@ protected override void Append(StringBuilder builder, LogEventInfo logEvent)

#endif
}
var message = string.Format("Could not find {0}", nameNotEmpty ? "assembly " + Name : "entry assembly");
var message = $"Could not find {(nameNotEmpty ? "assembly " + Name : "entry assembly")}";

#if !SILVERLIGHT
var assemblyVersion = assembly == null ? message : assembly.GetName().Version.ToString();
Expand Down
3 changes: 2 additions & 1 deletion src/NLog/LayoutRenderers/ExceptionLayoutRenderer.cs
Original file line number Diff line number Diff line change
Expand Up @@ -292,7 +292,8 @@ protected virtual void AppendMessage(StringBuilder sb, Exception ex)
}
catch (Exception exception)
{
var message = string.Format("Exception in {0}.AppendMessage(): {1}.", typeof(ExceptionLayoutRenderer).FullName, exception.GetType().FullName);
var message =
$"Exception in {typeof(ExceptionLayoutRenderer).FullName}.AppendMessage(): {exception.GetType().FullName}.";
sb.Append("NLog message: ");
sb.Append(message);
InternalLogger.Warn(exception, message);
Expand Down
2 changes: 1 addition & 1 deletion src/NLog/LayoutRenderers/RegistryLayoutRenderer.cs
Original file line number Diff line number Diff line change
Expand Up @@ -260,7 +260,7 @@ private static RegistryHive ParseHiveName(string hiveName)
}

//ArgumentException is consistent
throw new ArgumentException(string.Format("Key name is not supported. Root hive '{0}' not recognized.", hiveName));
throw new ArgumentException($"Key name is not supported. Root hive '{hiveName}' not recognized.");
}

#if NET3_5
Expand Down
7 changes: 4 additions & 3 deletions src/NLog/LogFactory.cs
Original file line number Diff line number Diff line change
Expand Up @@ -1146,8 +1146,8 @@ private Logger GetLogger(LoggerCacheKey cacheKey)
//creating instance of static class isn't possible, and also not wanted (it cannot inherited from Logger)
if (cacheKey.ConcreteType.IsStaticClass())
{
var errorMessage = String.Format("GetLogger / GetCurrentClassLogger is '{0}' as loggerType can be a static class and should inherit from Logger",
fullName);
var errorMessage =
$"GetLogger / GetCurrentClassLogger is '{fullName}' as loggerType can be a static class and should inherit from Logger";
InternalLogger.Error(errorMessage);
if (ThrowExceptions)
{
Expand All @@ -1164,7 +1164,8 @@ private Logger GetLogger(LoggerCacheKey cacheKey)
{
//well, it's not a Logger, and we should return a Logger.

var errorMessage = String.Format("GetLogger / GetCurrentClassLogger got '{0}' as loggerType which doesn't inherit from Logger", fullName);
var errorMessage =
$"GetLogger / GetCurrentClassLogger got '{fullName}' as loggerType which doesn't inherit from Logger";
InternalLogger.Error(errorMessage);
if (ThrowExceptions)
{
Expand Down
2 changes: 1 addition & 1 deletion src/NLog/Targets/ConsoleTargetHelper.cs
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,7 @@ public static bool IsConsoleAvailable(out string reason)
}
catch (Exception ex)
{
reason = string.Format("Unexpected exception: {0}:{1}", ex.GetType().Name, ex.Message);
reason = $"Unexpected exception: {ex.GetType().Name}:{ex.Message}";
InternalLogger.Warn(ex, "Failed to detect whether console is available.");
return false;
}
Expand Down
2 changes: 1 addition & 1 deletion src/NLog/Targets/DefaultJsonSerializer.cs
Original file line number Diff line number Diff line change
Expand Up @@ -356,7 +356,7 @@ private bool SerializeTypeCodeValue(object value, StringBuilder destination, Jso
}
else if (value is DateTimeOffset)
{
QuoteValue(destination, string.Format("{0:yyyy-MM-dd HH:mm:ss zzz}", value));
QuoteValue(destination, $"{value:yyyy-MM-dd HH:mm:ss zzz}");
}
else
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -92,7 +92,7 @@ public override DateAndSequenceArchive GenerateArchiveFileName(string archiveFil
int minSequenceLength = archiveFileNameTemplate.EndAt - archiveFileNameTemplate.BeginAt - 2;
string paddedSequence = nextSequenceNumber.ToString().PadLeft(minSequenceLength, '0');
string archiveFileNameWithoutPath = archiveFileNameTemplate.ReplacePattern("*").Replace("*",
string.Format("{0}.{1}", archiveDate.ToString(_archiveDateFormat), paddedSequence));
$"{archiveDate.ToString(_archiveDateFormat)}.{paddedSequence}");
string dirName = Path.GetDirectoryName(archiveFilePath);
archiveFilePath = Path.Combine(dirName, archiveFileNameWithoutPath);
return new DateAndSequenceArchive(archiveFilePath, archiveDate, _archiveDateFormat, nextSequenceNumber);
Expand Down
2 changes: 1 addition & 1 deletion tests/NLog.UnitTests/Common/InternalLoggerTests_Trace.cs
Original file line number Diff line number Diff line change
Expand Up @@ -256,7 +256,7 @@ private T SetupTestConfiguration<T>(LogLevel logLevel, bool? internalLogToTrace,
var internalLogToTraceAttribute = "";
if (internalLogToTrace.HasValue)
{
internalLogToTraceAttribute = string.Format(" internalLogToTrace='{0}'", internalLogToTrace.Value);
internalLogToTraceAttribute = $" internalLogToTrace='{internalLogToTrace.Value}'";
}

var xmlConfiguration = string.Format(XmlConfigurationFormat, logLevel, internalLogToTraceAttribute);
Expand Down
18 changes: 12 additions & 6 deletions tests/NLog.UnitTests/Config/InternalLoggingTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -96,8 +96,8 @@ public void InternalLoggingConfig_off_should_be_off()
var stringWriter = new StringWriter(sb);
InternalLogger.LogWriter = stringWriter;
string wrongFileName = "WRONG/***[]???////WRONG";
LogManager.Configuration = CreateConfigurationFromString(string.Format(@"<?xml version='1.0' encoding='utf-8' ?>
<nlog internalLogFile='{0}'
LogManager.Configuration = CreateConfigurationFromString($@"<?xml version='1.0' encoding='utf-8' ?>
<nlog internalLogFile='{wrongFileName}'
internalLogLevel='Off'
throwExceptions='true' >

Expand All @@ -109,7 +109,7 @@ public void InternalLoggingConfig_off_should_be_off()
<logger name='*' writeTo='logfile' />
</rules>
</nlog>
", wrongFileName));
");

Assert.Equal("", sb.ToString());
Assert.Equal(LogLevel.Off, InternalLogger.LogLevel);
Expand All @@ -129,9 +129,15 @@ private void InternalLoggingConfigTest(LogLevel logLevel, bool logToConsole, boo

using (new InternalLoggerScope(true))
{
CreateConfigurationFromString(string.Format(@"
<nlog internalLogFile='{0}' internalLogLevel='{1}' internalLogToConsole='{2}' internalLogToConsoleError='{3}' globalThreshold='{4}' throwExceptions='{5}' throwConfigExceptions='{6}' internalLogToTrace='{7}'>
</nlog>", file, logLevelString, internalLogToConsoleString, internalLogToConsoleErrorString, globalThresholdString, throwExceptionsString, throwConfigExceptionsString, logToTraceString));
CreateConfigurationFromString($@"
<nlog internalLogFile='{file}' internalLogLevel='{logLevelString}' internalLogToConsole='{
internalLogToConsoleString
}' internalLogToConsoleError='{internalLogToConsoleErrorString}' globalThreshold='{
globalThresholdString
}' throwExceptions='{throwExceptionsString}' throwConfigExceptions='{
throwConfigExceptionsString
}' internalLogToTrace='{logToTraceString}'>
</nlog>");

Assert.Same(logLevel, InternalLogger.LogLevel);

Expand Down
2 changes: 1 addition & 1 deletion tests/NLog.UnitTests/Config/ReloadTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -579,7 +579,7 @@ private static void ChangeAndReloadConfigFile(string configFilePath, string conf
reloadWaiter.WaitForReload();

if (assertDidReload)
Assert.True(reloadWaiter.DidReload, string.Format("Config '{0}' did not reload.", configFilePath));
Assert.True(reloadWaiter.DidReload, $"Config '{configFilePath}' did not reload.");
}
}

Expand Down
6 changes: 3 additions & 3 deletions tests/NLog.UnitTests/Config/XmlConfigTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -93,17 +93,17 @@ public void ParseNLogOptionsTest()
[InlineData("1:0:0:0", 86400)] //1 day
public void SetTimeSpanFromXmlTest(string interval, int seconds)
{
var config = CreateConfigurationFromString(string.Format(@"
var config = CreateConfigurationFromString($@"
<nlog throwExceptions='true'>
<targets>
<wrapper-target name='limiting' type='LimitingWrapper' messagelimit='5' interval='{0}'>
<wrapper-target name='limiting' type='LimitingWrapper' messagelimit='5' interval='{interval}'>
<target name='debug' type='Debug' layout='${{message}}' />
</wrapper-target>
</targets>
<rules>
<logger name='*' level='Debug' writeTo='limiting' />
</rules>
</nlog>", interval));
</nlog>");

var target = config.FindTargetByName<LimitingTargetWrapper>("limiting");
Assert.NotNull(target);
Expand Down
2 changes: 1 addition & 1 deletion tests/NLog.UnitTests/Fluent/LogBuilderTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -105,7 +105,7 @@ private void TraceWrite_internal(Func<LogBuilder> logBuilder, bool isStatic = fa
.Write();

{
var rendered = string.Format("This is a test fluent message '{0}'.", ticks);
var rendered = $"This is a test fluent message '{ticks}'.";
var expectedEvent = new LogEventInfo(LogLevel.Trace, loggerName, "This is a test fluent message '{0}'.");
expectedEvent.Properties["Test"] = "TraceWrite";
AssertLastLogEventTarget(expectedEvent);
Expand Down
8 changes: 5 additions & 3 deletions tests/NLog.UnitTests/Internal/AppDomainPartialTrustTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -114,18 +114,20 @@ public void PartialTrustSuccess(int times, string fileWritePath)
var filePath = Path.Combine(fileWritePath, "${level}.txt");

// NOTE Using BufferingWrapper to validate that DomainUnload remembers to perform flush
var configXml = string.Format(@"
var configXml = $@"
<nlog throwExceptions='false'>
<targets async='true'>
<target name='file' type='BufferingWrapper' bufferSize='10000' flushTimeout='15000'>
<target name='filewrapped' type='file' layout='${{message}} ${{threadid}}' filename='{0}' LineEnding='lf' />
<target name='filewrapped' type='file' layout='${{message}} ${{threadid}}' filename='{
filePath
}' LineEnding='lf' />
</target>
</targets>
<rules>
<logger name='*' minlevel='Debug' appendto='file'>
</logger>
</rules>
</nlog>", filePath);
</nlog>";

LogManager.Configuration = NLogTestBase.CreateConfigurationFromString(configXml);

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,7 @@ public class AppDomainLayoutRendererTests : NLogTestBase
public void AppDomainTest()
{
//example: 0003: NLog.UnitTests
AssertLayoutRendererOutput("${appdomain}", string.Format("{0:0000}:{1}", id, friendlyname));
AssertLayoutRendererOutput("${appdomain}", $"{id:0000}:{friendlyname}");
}

[Fact]
Expand All @@ -62,7 +62,7 @@ public void AppDomainShortFormatTest()
public void AppDomainTestLongFormatTest()
{
//example: 0003: NLog.UnitTests
AssertLayoutRendererOutput("${appdomain:format=long}", string.Format("{0:0000}:{1}", id, friendlyname));
AssertLayoutRendererOutput("${appdomain:format=long}", $"{id:0000}:{friendlyname}");
}

[Fact]
Expand Down
4 changes: 2 additions & 2 deletions tests/NLog.UnitTests/LayoutRenderers/BaseDirTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -71,7 +71,7 @@ public void BaseDirCurrentProcessTest()
var dir = l.Render(LogEventInfo.CreateNullEvent());

Assert.NotNull(dir);
Assert.True(Directory.Exists(dir), string.Format("dir '{0}' doesn't exists", dir));
Assert.True(Directory.Exists(dir), $"dir '{dir}' doesn't exists");
Assert.Equal(Path.GetDirectoryName(System.Diagnostics.Process.GetCurrentProcess().MainModule.FileName), dir);
}

Expand Down Expand Up @@ -99,7 +99,7 @@ public void InjectBaseDirAndCheckConfigPathsTest()
var paths = LogManager.LogFactory.GetCandidateConfigFilePaths().ToList();
var count = paths.Count(p => p.StartsWith(fakeBaseDir));

Assert.True(count > 0, string.Format("At least one path should start with '{0}'", fakeBaseDir));
Assert.True(count > 0, $"At least one path should start with '{fakeBaseDir}'");

}
finally
Expand Down
18 changes: 9 additions & 9 deletions tests/NLog.UnitTests/LayoutRenderers/CallSiteTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -556,11 +556,11 @@ public void When_Wrapped_Ignore_Wrapper_Methods_In_Callstack()

var logger = LogManager.GetLogger("A");
logger.Warn("direct");
AssertDebugLastMessage("debug", string.Format("{0}|direct", currentMethodFullName));
AssertDebugLastMessage("debug", $"{currentMethodFullName}|direct");

LoggerTests.BaseWrapper wrappedLogger = new LoggerTests.MyWrapper();
wrappedLogger.Log("wrapped");
AssertDebugLastMessage("debug", string.Format("{0}|wrapped", currentMethodFullName));
AssertDebugLastMessage("debug", $"{currentMethodFullName}|wrapped");
}

[Fact]
Expand Down Expand Up @@ -647,11 +647,11 @@ public void When_WrappedInCompsition_Ignore_Wrapper_Methods_In_Callstack()

var logger = LogManager.GetLogger("A");
logger.Warn("direct");
AssertDebugLastMessage("debug", string.Format("{0}|direct", currentMethodFullName));
AssertDebugLastMessage("debug", $"{currentMethodFullName}|direct");

CompositeWrapper wrappedLogger = new CompositeWrapper();
wrappedLogger.Log("wrapped");
AssertDebugLastMessage("debug", string.Format("{0}|wrapped", currentMethodFullName));
AssertDebugLastMessage("debug", $"{currentMethodFullName}|wrapped");

}

Expand All @@ -675,7 +675,7 @@ public void Show_correct_method_with_async()
</nlog>");

AsyncMethod().Wait();
AssertDebugLastMessage("debug", string.Format("{0}|direct", currentMethodFullName));
AssertDebugLastMessage("debug", $"{currentMethodFullName}|direct");

}

Expand Down Expand Up @@ -707,7 +707,7 @@ public void Show_correct_method_with_async2()
</nlog>");

AsyncMethod2a().Wait();
AssertDebugLastMessage("debug", string.Format("{0}|direct", currentMethodFullName));
AssertDebugLastMessage("debug", $"{currentMethodFullName}|direct");

}

Expand Down Expand Up @@ -745,7 +745,7 @@ public void Show_correct_method_with_async3()
</nlog>");

AsyncMethod3a().Wait();
AssertDebugLastMessage("debug", string.Format("{0}|direct", currentMethodFullName));
AssertDebugLastMessage("debug", $"{currentMethodFullName}|direct");
}

private async Task AsyncMethod3a()
Expand Down Expand Up @@ -792,7 +792,7 @@ public void Show_correct_method_with_async4()
</nlog>");

AsyncMethod4().Wait();
AssertDebugLastMessage("debug", string.Format("{0}|Direct, async method", currentMethodFullName));
AssertDebugLastMessage("debug", $"{currentMethodFullName}|Direct, async method");

}

Expand Down Expand Up @@ -844,7 +844,7 @@ public void Show_correct_method_for_moveNext()
</nlog>");

MoveNext();
AssertDebugLastMessage("debug", string.Format("{0}|direct", currentMethodFullName));
AssertDebugLastMessage("debug", $"{currentMethodFullName}|direct");

}

Expand Down
4 changes: 2 additions & 2 deletions tests/NLog.UnitTests/LayoutRenderers/DateTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -74,12 +74,12 @@ public void TimeZoneTest()
if (offset2 >= new TimeSpan(0))
{
//+00:00, +01:00 etc
Assert.Contains(string.Format("+{0:D2}:{1:D2}", offset2.Hours, offset2.Minutes), result);
Assert.Contains($"+{offset2.Hours:D2}:{offset2.Minutes:D2}", result);
}
else
{
//-01:00, etc
Assert.Contains(string.Format("{0:D2}:{1:D2}", offset2.Hours, offset2.Minutes), result);
Assert.Contains($"{offset2.Hours:D2}:{offset2.Minutes:D2}", result);
}

}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,7 @@ public void RenderNLogDir()

Assert.NotNull(actual);

Assert.True(File.Exists(Path.Combine(actual, "NLog.dll")), string.Format("cannot find NLog.dll in '{0}'", actual));
Assert.True(File.Exists(Path.Combine(actual, "NLog.dll")), $"cannot find NLog.dll in '{actual}'");
}


Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,8 @@ public void RenderProcessNameLayoutRenderer()
//lowercase
var allowedProcessNames = new List<string> {"vstest.executionengine", "xunit", "mono-sgen", "dotnet", "testhost.x86", "testhost.x64" };

Assert.True(allowedProcessNames.Any(p => lower.Contains(p)), string.Format("validating processname failed. Please add (if correct) '{0}' to 'allowedProcessNames'", actual));
Assert.True(allowedProcessNames.Any(p => lower.Contains(p)),
$"validating processname failed. Please add (if correct) '{actual}' to 'allowedProcessNames'");
}

[Fact]
Expand Down
Loading