Skip to content

Commit

Permalink
Merge pull request #3339 from NLog/cleanup3
Browse files Browse the repository at this point in the history
Small code improvements
  • Loading branch information
repo-ranger[bot] committed Apr 27, 2019
2 parents 92b0b37 + f1ad170 commit 610f368
Show file tree
Hide file tree
Showing 20 changed files with 55 additions and 97 deletions.
2 changes: 1 addition & 1 deletion src/NLog/Conditions/ConditionMethodExpression.cs
Original file line number Diff line number Diff line change
Expand Up @@ -186,7 +186,7 @@ public override string ToString()
protected override object EvaluateNode(LogEventInfo context)
{
int parameterOffset = _acceptsLogEvent ? 1 : 0;
int parameterDefaults = _lateBoundMethodDefaultParameters != null ? _lateBoundMethodDefaultParameters.Length : 0;
int parameterDefaults = _lateBoundMethodDefaultParameters?.Length ?? 0;

var callParameters = new object[MethodParameters.Count + parameterOffset + parameterDefaults];

Expand Down
2 changes: 1 addition & 1 deletion src/NLog/Internal/EnvironmentHelper.cs
Original file line number Diff line number Diff line change
Expand Up @@ -82,7 +82,7 @@ internal static string GetSafeEnvironmentVariable(string name)
{
string s = Environment.GetEnvironmentVariable(name);

if (s == null || s.Length == 0)
if (string.IsNullOrEmpty(s))
{
return null;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -138,14 +138,11 @@ public override void Write(byte[] bytes, int offset, int count)
return;
}

if (_enableFileDeleteSimpleMonitor)
if (_enableFileDeleteSimpleMonitor && MonitorForEnableFileDeleteEvent(FileName, ref _lastSimpleMonitorCheckTimeUtc))
{
if (MonitorForEnableFileDeleteEvent(FileName, ref _lastSimpleMonitorCheckTimeUtc))
{
_file.Dispose();
_file = CreateFileStream(false);
_currentFileLength = _file.Length;
}
_file.Dispose();
_file = CreateFileStream(false);
_currentFileLength = _file.Length;
}

_currentFileLength += count;
Expand Down
9 changes: 3 additions & 6 deletions src/NLog/Internal/FileAppenders/SingleProcessFileAppender.cs
Original file line number Diff line number Diff line change
Expand Up @@ -77,13 +77,10 @@ public override void Write(byte[] bytes, int offset, int count)
return;
}

if (_enableFileDeleteSimpleMonitor)
if (_enableFileDeleteSimpleMonitor && MonitorForEnableFileDeleteEvent(FileName, ref _lastSimpleMonitorCheckTimeUtc))
{
if (MonitorForEnableFileDeleteEvent(FileName, ref _lastSimpleMonitorCheckTimeUtc))
{
_file.Dispose();
_file = CreateFileStream(false);
}
_file.Dispose();
_file = CreateFileStream(false);
}

_file.Write(bytes, offset, count);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -210,7 +210,7 @@ public override void Flush()
public override long? GetFileLength()
{
var fileChars = GetFileCharacteristics();
return fileChars != null ? fileChars.FileLength : (long?)null;
return fileChars?.FileLength;
}

private FileCharacteristics GetFileCharacteristics()
Expand Down
5 changes: 2 additions & 3 deletions src/NLog/Internal/FilePathLayout.cs
Original file line number Diff line number Diff line change
Expand Up @@ -174,11 +174,10 @@ private string GetRenderedFileName(LogEventInfo logEvent, System.Text.StringBuil

_layout.RenderAppendBuilder(logEvent, reusableBuilder);

if (_cachedPrevRawFileName != null)
if (_cachedPrevRawFileName != null && reusableBuilder.EqualTo(_cachedPrevRawFileName))
{
// If old filename matches the newly rendered, then no need to call StringBuilder.ToString()
if (reusableBuilder.EqualTo(_cachedPrevRawFileName))
return _cachedPrevRawFileName;
return _cachedPrevRawFileName;
}

_cachedPrevRawFileName = reusableBuilder.ToString();
Expand Down
2 changes: 1 addition & 1 deletion src/NLog/Internal/MruCache.cs
Original file line number Diff line number Diff line change
Expand Up @@ -115,7 +115,7 @@ private void PruneCache()

oldestGeneration = long.MaxValue;

long elementGeneration = 0;
long elementGeneration;
foreach (var element in _dictionary)
{
elementGeneration = element.Value.Version;
Expand Down
7 changes: 2 additions & 5 deletions src/NLog/Internal/NetworkSenders/TcpNetworkSender.cs
Original file line number Diff line number Diff line change
Expand Up @@ -319,15 +319,12 @@ private void SocketOperationCompleted(object sender, SocketAsyncEventArgs e)

if (e.SocketError != SocketError.Success)
{
_pendingError = new IOException($"Error: " + e.SocketError);
_pendingError = new IOException("Error: " + e.SocketError);
}

e.Dispose();

if (asyncContinuation != null)
{
asyncContinuation(_pendingError);
}
asyncContinuation?.Invoke(_pendingError);
}

ProcessNextQueuedItem();
Expand Down
15 changes: 6 additions & 9 deletions src/NLog/Internal/ObjectReflectionCache.cs
Original file line number Diff line number Diff line change
Expand Up @@ -213,8 +213,8 @@ public struct ObjectPropertyList : IEnumerable<ObjectPropertyList.PropertyValue>

public struct PropertyValue
{
readonly public string Name;
readonly public object Value;
public readonly string Name;
public readonly object Value;
public TypeCode TypeCode
{
get
Expand All @@ -228,7 +228,7 @@ public TypeCode TypeCode
}
}

readonly private TypeCode _typecode;
private readonly TypeCode _typecode;

public PropertyValue(string name, object value, TypeCode typeCode)
{
Expand Down Expand Up @@ -293,13 +293,10 @@ public bool TryGetPropertyValue(string name, out PropertyValue propertyValue)
}
}
}
else if (_object is IDictionary<string, object> expandoObject)
else if (_object is IDictionary<string, object> expandoObject && expandoObject.TryGetValue(name, out var objectValue))
{
if (expandoObject.TryGetValue(name, out var objectValue))
{
propertyValue = new PropertyValue(name, objectValue, TypeCode.Object);
return true;
}
propertyValue = new PropertyValue(name, objectValue, TypeCode.Object);
return true;
}
propertyValue = default(PropertyValue);
return false;
Expand Down
2 changes: 1 addition & 1 deletion src/NLog/Internal/StringBuilderExt.cs
Original file line number Diff line number Diff line change
Expand Up @@ -157,7 +157,7 @@ public static void CopyToStream(this StringBuilder builder, MemoryStream ms, Enc
#if !SILVERLIGHT
if (transformBuffer != null)
{
int charCount = 0;
int charCount;
int byteCount = encoding.GetMaxByteCount(builder.Length);
ms.SetLength(ms.Position + byteCount);
for (int i = 0; i < builder.Length; i += transformBuffer.Length)
Expand Down
10 changes: 1 addition & 9 deletions src/NLog/LayoutRenderers/ProcessNameLayoutRenderer.cs
Original file line number Diff line number Diff line change
Expand Up @@ -63,15 +63,7 @@ public class ProcessNameLayoutRenderer : LayoutRenderer
/// <param name="logEvent">Logging event.</param>
protected override void Append(StringBuilder builder, LogEventInfo logEvent)
{
string output;
if (FullName)
{
output = ProcessIDHelper.Instance.CurrentProcessFilePath;
}
else
{
output = ProcessIDHelper.Instance.CurrentProcessBaseName;
}
var output = FullName ? ProcessIDHelper.Instance.CurrentProcessFilePath : ProcessIDHelper.Instance.CurrentProcessBaseName;
builder.Append(output);
}
}
Expand Down
9 changes: 3 additions & 6 deletions src/NLog/Layouts/SimpleLayout.cs
Original file line number Diff line number Diff line change
Expand Up @@ -332,13 +332,10 @@ internal override bool TryGetRawValue(LogEventInfo logEvent, out object rawValue
{
if (_rawValueRenderer != null)
{
if (!ThreadAgnostic || MutableUnsafe)
if ((!ThreadAgnostic || MutableUnsafe) && logEvent.TryGetCachedLayoutValue(this, out _))
{
if (logEvent.TryGetCachedLayoutValue(this, out _))
{
rawValue = null;
return false; // Raw-Value has been precalculated, so not available
}
rawValue = null;
return false; // Raw-Value has been precalculated, so not available
}

var success = _rawValueRenderer.TryGetRawValue(logEvent, out rawValue);
Expand Down
2 changes: 1 addition & 1 deletion src/NLog/LogFactory.cs
Original file line number Diff line number Diff line change
Expand Up @@ -509,7 +509,7 @@ public void Flush(AsyncContinuation asyncContinuation, TimeSpan timeout)
try
{
InternalLogger.Trace("LogFactory.Flush({0})", timeout);
LoggingConfiguration loggingConfiguration = null;
LoggingConfiguration loggingConfiguration;
lock (_syncRoot)
{
loggingConfiguration = _config; // Flush should not attempt to auto-load Configuration
Expand Down
7 changes: 2 additions & 5 deletions src/NLog/Targets/AsyncTaskTarget.cs
Original file line number Diff line number Diff line change
Expand Up @@ -689,12 +689,9 @@ private void TaskTimeout(object state)
{
if (previousTask.Status != TaskStatus.Canceled &&
previousTask.Status != TaskStatus.Faulted &&
previousTask.Status != TaskStatus.RanToCompletion)
previousTask.Status != TaskStatus.RanToCompletion && !previousTask.Wait(100))
{
if (!previousTask.Wait(100))
{
InternalLogger.Debug("{0} WriteAsyncTask had timeout. Task did not cancel properly: {1}.", Name, previousTask.Status);
}
InternalLogger.Debug("{0} WriteAsyncTask had timeout. Task did not cancel properly: {1}.", Name, previousTask.Status);
}

Exception actualException = ExtractActualException(previousTask.Exception);
Expand Down
17 changes: 7 additions & 10 deletions src/NLog/Targets/FileArchiveModes/FileArchiveModeRolling.cs
Original file line number Diff line number Diff line change
Expand Up @@ -107,19 +107,16 @@ public IEnumerable<DateAndSequenceArchive> CheckArchiveCleanup(string archiveFil

existingArchiveFiles.Sort((x, y) => x.Sequence.CompareTo(y.Sequence));

if (maxArchiveFiles > 0)
if (maxArchiveFiles > 0 && existingArchiveFiles.Count > maxArchiveFiles)
{
if (existingArchiveFiles.Count > maxArchiveFiles)
for (int i = 0; i < existingArchiveFiles.Count; i++)
{
for (int i = 0; i < existingArchiveFiles.Count; i++)
{
if (existingArchiveFiles[i].Sequence == int.MinValue || existingArchiveFiles[i].Sequence == int.MaxValue)
continue;
if (existingArchiveFiles[i].Sequence == int.MinValue || existingArchiveFiles[i].Sequence == int.MaxValue)
continue;

if ((i + 1) > maxArchiveFiles)
{
yield return existingArchiveFiles[i];
}
if (i + 1 > maxArchiveFiles)
{
yield return existingArchiveFiles[i];
}
}
}
Expand Down
16 changes: 5 additions & 11 deletions src/NLog/Targets/FileTarget.cs
Original file line number Diff line number Diff line change
Expand Up @@ -1335,13 +1335,10 @@ private void ArchiveFileAppendExisting(string fileName, string archiveFileName)
//clear old content
fileStream.SetLength(0);

if (EnableFileDelete)
if (EnableFileDelete && !DeleteOldArchiveFile(fileName))
{
// Attempt to delete file to reset File-Creation-Time (Delete under file-lock)
if (!DeleteOldArchiveFile(fileName))
{
fileShare &= ~FileShare.Delete; // Retry after having released file-lock
}
fileShare &= ~FileShare.Delete; // Retry after having released file-lock
}

fileStream.Close(); // This flushes the content, too.
Expand Down Expand Up @@ -1646,13 +1643,10 @@ private string GenerateArchiveFileNameAfterCleanup(string fileName, FileInfo fil
}
}

if (initializedNewFile)
if (initializedNewFile && string.Equals(Path.GetDirectoryName(archiveFilePattern), fileInfo.DirectoryName, StringComparison.OrdinalIgnoreCase))
{
if (string.Equals(Path.GetDirectoryName(archiveFilePattern), fileInfo.DirectoryName, StringComparison.OrdinalIgnoreCase))
{
DeleteOldArchiveFile(fileName);
return null;
}
DeleteOldArchiveFile(fileName);
return null;
}
}

Expand Down
21 changes: 9 additions & 12 deletions src/NLog/Targets/MailTarget.cs
Original file line number Diff line number Diff line change
Expand Up @@ -170,19 +170,16 @@ public Layout From
get
{
#if !__ANDROID__ && !__IOS__ && !NETSTANDARD
if (UseSystemNetMailSettings)
{
// In contrary to other settings, System.Net.Mail.SmtpClient doesn't read the 'From' attribute from the system.net/mailSettings/smtp section in the config file.
// Thus, when UseSystemNetMailSettings is enabled we have to read the configuration section of system.net/mailSettings/smtp to initialize the 'From' address.
// It will do so only if the 'From' attribute in system.net/mailSettings/smtp is not empty.

// In contrary to other settings, System.Net.Mail.SmtpClient doesn't read the 'From' attribute from the system.net/mailSettings/smtp section in the config file.
// Thus, when UseSystemNetMailSettings is enabled we have to read the configuration section of system.net/mailSettings/smtp to initialize the 'From' address.
// It will do so only if the 'From' attribute in system.net/mailSettings/smtp is not empty.

//only use from config when not set in current
if (_from == null)
{
var from = SmtpSection.From;
if (from == null) return null;
return from;
}
//only use from config when not set in current
if (UseSystemNetMailSettings && _from == null)
{
var from = SmtpSection.From;
return from;
}
#endif
return _from;
Expand Down
9 changes: 3 additions & 6 deletions src/NLog/Targets/Target.cs
Original file line number Diff line number Diff line change
Expand Up @@ -756,14 +756,11 @@ protected string RenderLogEvent(Layout layout, LogEventInfo logEvent)

private static bool TryGetCachedValue(Layout layout, LogEventInfo logEvent, out string value)
{
if (!layout.ThreadAgnostic || layout.MutableUnsafe)
if ((!layout.ThreadAgnostic || layout.MutableUnsafe) && logEvent.TryGetCachedLayoutValue(layout, out var value2))
{
if (logEvent.TryGetCachedLayoutValue(layout, out var value2))
{
{
value = value2?.ToString() ?? string.Empty;
return true;
}
value = value2?.ToString() ?? string.Empty;
return true;
}
}

Expand Down
2 changes: 1 addition & 1 deletion src/NLog/Targets/WebServiceTarget.cs
Original file line number Diff line number Diff line change
Expand Up @@ -487,7 +487,7 @@ private Uri BuildWebServiceUrl(object[] parameterValues)
}

//if the protocol is HttpGet, we need to add the parameters to the query string of the url
string queryParameters = string.Empty;
string queryParameters;
using (var targetBuilder = OptimizeBufferReuse ? ReusableLayoutBuilder.Allocate() : ReusableLayoutBuilder.None)
{
StringBuilder sb = targetBuilder.Result ?? new StringBuilder();
Expand Down
2 changes: 1 addition & 1 deletion src/NLog/Targets/Wrappers/ConcurrentRequestQueue.cs
Original file line number Diff line number Diff line change
Expand Up @@ -117,7 +117,7 @@ public override bool Enqueue(AsyncLogEventInfo logEventInfo)

private long WaitForBelowRequestLimit()
{
long currentCount = 0;
long currentCount;
bool lockTaken = false;
try
{
Expand Down

0 comments on commit 610f368

Please sign in to comment.