Skip to content

Commit

Permalink
Merge pull request #36 from Abc-Arbitrage/nullalbe-ref-types
Browse files Browse the repository at this point in the history
Nullalbe reference types
  • Loading branch information
rverdier authored Jan 9, 2020
2 parents df90030 + e1c911f commit 8b15217
Show file tree
Hide file tree
Showing 38 changed files with 777 additions and 644 deletions.
12 changes: 8 additions & 4 deletions src/ZeroLog/Appenders/AppenderBase.cs
Original file line number Diff line number Diff line change
Expand Up @@ -6,9 +6,9 @@ namespace ZeroLog.Appenders
{
public abstract class AppenderBase<T> : IAppender<T>
{
private Encoding _encoding;
private Encoding _encoding = LogManager.DefaultEncoding;
private byte[] _newlineBytes = Array.Empty<byte>();
private PrefixWriter _prefixWriter;
private PrefixWriter? _prefixWriter;

protected void Configure(string prefixPattern)
{
Expand All @@ -18,8 +18,12 @@ protected void Configure(string prefixPattern)
protected int WriteEventToStream(Stream stream, ILogEventHeader logEventHeader, byte[] messageBytes, int messageLength)
{
var bytesWritten = 0;
bytesWritten += _prefixWriter.WritePrefix(stream, logEventHeader, _encoding);

if (_prefixWriter != null)
bytesWritten += _prefixWriter.WritePrefix(stream, logEventHeader, _encoding);

bytesWritten += WriteLine(stream, messageBytes, messageLength);

return bytesWritten;
}

Expand Down Expand Up @@ -55,7 +59,7 @@ public virtual void Dispose()
{
}

public string Name { get; set; }
public string? Name { get; set; }
public abstract void Configure(T parameters);
public abstract void WriteEvent(ILogEventHeader logEventHeader, byte[] messageBytes, int messageLength);
}
Expand Down
18 changes: 11 additions & 7 deletions src/ZeroLog/Appenders/AppenderFactory.cs
Original file line number Diff line number Diff line change
Expand Up @@ -9,9 +9,9 @@ public class AppenderFactory
{
public static IAppender CreateAppender(AppenderDefinition definition)
{
var appenderType = GetAppenderType(definition);
var appenderType = GetAppenderType(definition) ?? throw new InvalidOperationException($"Appender type not found: {definition.AppenderTypeName}");

var appender = (IAppender)Activator.CreateInstance(appenderType);
var appender = (IAppender)Activator.CreateInstance(appenderType)!;
appender.Name = definition.Name;

var appenderParameterType = GetAppenderParameterType(appenderType);
Expand All @@ -26,10 +26,13 @@ public static IAppender CreateAppender(AppenderDefinition definition)
return appender;
}

private static Type GetAppenderType(AppenderDefinition definition)
private static Type? GetAppenderType(AppenderDefinition definition)
{
if (string.IsNullOrEmpty(definition.AppenderTypeName))
return null;

// Check if we have an assembly-qualified name of a type
if (definition.AppenderTypeName.Contains(","))
if (definition.AppenderTypeName!.Contains(","))
return Type.GetType(definition.AppenderTypeName, true, false);

return AppDomain.CurrentDomain.GetAssemblies()
Expand All @@ -44,11 +47,12 @@ private static object GetAppenderParameters(AppenderDefinition definition, Type
return appenderParameters;
}

private static Type GetAppenderParameterType(Type appenderType)
private static Type? GetAppenderParameterType(Type? appenderType)
{
var type = appenderType;
if (appenderType is null)
return null;

var implementedInterfaceTypes = type.GetInterfaces();
var implementedInterfaceTypes = appenderType.GetInterfaces();

foreach (var interfaceType in implementedInterfaceTypes)
{
Expand Down
27 changes: 13 additions & 14 deletions src/ZeroLog/Appenders/DateAndSizeRollingFileAppender.cs
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
using System;
using System.IO;
using System.Linq;
using System.Threading;
using JetBrains.Annotations;

namespace ZeroLog.Appenders
Expand All @@ -13,20 +12,19 @@ public class DateAndSizeRollingFileAppender : AppenderBase<DateAndSizeRollingFil
public const string DefaultPrefixPattern = "%time - %level - %logger || ";

private DateTime _currentDate = DateTime.UtcNow.Date;
private string _directory;
private int _rollingFileNumber;
private Stream _stream;
private Stream? _stream;
private long _fileSize;

/// <summary>
/// Gets or sets the file name extension to use for the rolling files. Defaults to "txt".
/// </summary>
public string FilenameExtension { get; set; }
public string FilenameExtension { get; set; } = default!;

/// <summary>
/// Gets or sets the root path and file name used by this appender, not including the file extension.
/// </summary>
public string FilenameRoot { get; set; }
public string FilenameRoot { get; set; } = default!;

/// <summary>
/// Gets or sets the maximum permitted file size in bytes. Once a file exceeds this value it will
Expand All @@ -35,7 +33,7 @@ public class DateAndSizeRollingFileAppender : AppenderBase<DateAndSizeRollingFil
/// </summary>
public int MaxFileSizeInBytes { get; set; }

internal string CurrentFileName { get; private set; }
internal string? CurrentFileName { get; private set; }

/// <summary>
/// Initializes a new instance of the class.
Expand Down Expand Up @@ -97,21 +95,22 @@ private void Open()
throw new ApplicationException("Could not resolve the full path to the log file", ex);
}

_directory = Path.GetDirectoryName(FilenameRoot);
if (!string.IsNullOrEmpty(_directory) && !Directory.Exists(_directory))
var directory = Path.GetDirectoryName(FilenameRoot) ?? throw new ApplicationException($"Could not resolve the directory of {FilenameRoot}");

if (!string.IsNullOrEmpty(directory) && !Directory.Exists(directory))
{
try
{
Directory.CreateDirectory(_directory);
Directory.CreateDirectory(directory);
}
catch (Exception ex)
{
throw new ApplicationException($"Could not create directory for log file '{_directory}'", ex);
throw new ApplicationException($"Could not create directory for log file '{directory}'", ex);
}
}

FilenameExtension = FilenameExtension ?? "";
_rollingFileNumber = FindLastRollingFileNumber();
FilenameExtension ??= "";
_rollingFileNumber = FindLastRollingFileNumber(directory);

OpenStream();
CheckRollFile(DateTime.UtcNow);
Expand Down Expand Up @@ -171,12 +170,12 @@ private void CheckRollFile(DateTime timestamp)
OpenStream();
}

private int FindLastRollingFileNumber()
private int FindLastRollingFileNumber(string directory)
{
var fileNumber = 0;
var root = FilenameRoot + ".";
var extension = FilenameExtension.Length == 0 ? "" : "." + FilenameExtension;
foreach (var filename in Directory.EnumerateFiles(_directory).Select(f => f.ToUpper()))
foreach (var filename in Directory.EnumerateFiles(directory).Select(f => f.ToUpper()))
{
if (filename.StartsWith(root, StringComparison.OrdinalIgnoreCase) && filename.EndsWith(extension, StringComparison.OrdinalIgnoreCase))
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ namespace ZeroLog.Appenders
{
public class DateAndSizeRollingFileAppenderConfig
{
public string FilePathRoot { get; set; }
public string FilePathRoot { get; set; } = string.Empty;
public string Extension { get; set; } = DateAndSizeRollingFileAppender.DefaultExtension;
public int MaxFileSizeInBytes { get; set; } = DateAndSizeRollingFileAppender.DefaultMaxSize;
public string PrefixPattern { get; set; } = DateAndSizeRollingFileAppender.DefaultPrefixPattern;
Expand Down
2 changes: 1 addition & 1 deletion src/ZeroLog/Appenders/GuardedAppender.cs
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ public GuardedAppender(IAppender appender, TimeSpan quarantineDelay)
_nextActivationTime = null;
}

public string Name
public string? Name
{
get => Appender.Name;
set => Appender.Name = value;
Expand Down
2 changes: 1 addition & 1 deletion src/ZeroLog/Appenders/IAppender.cs
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ namespace ZeroLog.Appenders
{
public interface IAppender : IDisposable
{
string Name { get; set; }
string? Name { get; set; }
void WriteEvent(ILogEventHeader logEventHeader, byte[] messageBytes, int messageLength);
void SetEncoding(Encoding encoding);
void Flush();
Expand Down
46 changes: 22 additions & 24 deletions src/ZeroLog/Appenders/PrefixWriter.cs
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.IO;
using System.Linq;
using System.Reflection;
Expand Down Expand Up @@ -75,7 +74,7 @@ private static char[] BuildStrings(IEnumerable<PatternPart> parts, out Dictionar
switch (part.Type)
{
case PatternPartType.String:
AddString(part.Value);
AddString(part.Value!);
break;

case PatternPartType.Date:
Expand Down Expand Up @@ -103,7 +102,6 @@ void AddString(string value)
return strings;
}

[SuppressMessage("ReSharper", "AssignNullToNotNullAttribute")]
private static Action<PrefixWriter, ILogEventHeader> BuildAppendMethod(ICollection<PatternPart> parts, Dictionary<string, (int offset, int length)> stringMap)
{
var method = new DynamicMethod("WritePrefix", typeof(void), new[] { typeof(PrefixWriter), typeof(ILogEventHeader) }, typeof(PrefixWriter), false)
Expand All @@ -118,11 +116,11 @@ private static Action<PrefixWriter, ILogEventHeader> BuildAppendMethod(ICollecti
var dateTimeLocal = default(LocalBuilder);

il.Emit(OpCodes.Ldarg_0);
il.Emit(OpCodes.Ldfld, typeof(PrefixWriter).GetField(nameof(_stringBuffer), BindingFlags.Instance | BindingFlags.NonPublic));
il.Emit(OpCodes.Ldfld, typeof(PrefixWriter).GetField(nameof(_stringBuffer), BindingFlags.Instance | BindingFlags.NonPublic)!);
il.Emit(OpCodes.Stloc, stringBufferLocal);

il.Emit(OpCodes.Ldarg_0);
il.Emit(OpCodes.Ldfld, typeof(PrefixWriter).GetField(nameof(_strings), BindingFlags.Instance | BindingFlags.NonPublic));
il.Emit(OpCodes.Ldfld, typeof(PrefixWriter).GetField(nameof(_strings), BindingFlags.Instance | BindingFlags.NonPublic)!);
il.Emit(OpCodes.Ldc_I4_0);
il.Emit(OpCodes.Ldelema, typeof(char));
il.Emit(OpCodes.Stloc, stringsLocal);
Expand All @@ -135,7 +133,7 @@ private static Action<PrefixWriter, ILogEventHeader> BuildAppendMethod(ICollecti
{
// _stringBuffer.Append(&_strings[0] + offset * sizeof(char), length);

var (offset, length) = stringMap[part.Value];
var (offset, length) = stringMap[part.Value!];

il.Emit(OpCodes.Ldloc, stringBufferLocal);

Expand All @@ -146,7 +144,7 @@ private static Action<PrefixWriter, ILogEventHeader> BuildAppendMethod(ICollecti

il.Emit(OpCodes.Ldc_I4, length);

il.Emit(OpCodes.Call, typeof(StringBuffer).GetMethod(nameof(StringBuffer.Append), new[] { typeof(char*), typeof(int) }));
il.Emit(OpCodes.Call, typeof(StringBuffer).GetMethod(nameof(StringBuffer.Append), new[] { typeof(char*), typeof(int) })!);
break;
}

Expand All @@ -159,7 +157,7 @@ private static Action<PrefixWriter, ILogEventHeader> BuildAppendMethod(ICollecti
il.Emit(OpCodes.Ldloc, stringBufferLocal);

il.Emit(OpCodes.Ldarg_1);
il.Emit(OpCodes.Callvirt, typeof(ILogEventHeader).GetProperty(nameof(ILogEventHeader.Timestamp))?.GetGetMethod());
il.Emit(OpCodes.Callvirt, typeof(ILogEventHeader).GetProperty(nameof(ILogEventHeader.Timestamp))?.GetGetMethod()!);

il.Emit(OpCodes.Ldloc, stringsLocal);
il.Emit(OpCodes.Conv_U);
Expand All @@ -168,9 +166,9 @@ private static Action<PrefixWriter, ILogEventHeader> BuildAppendMethod(ICollecti

il.Emit(OpCodes.Ldc_I4, length);

il.Emit(OpCodes.Newobj, typeof(StringView).GetConstructor(new[] { typeof(char*), typeof(int) }));
il.Emit(OpCodes.Newobj, typeof(StringView).GetConstructor(new[] { typeof(char*), typeof(int) })!);

il.Emit(OpCodes.Call, typeof(StringBuffer).GetMethod(nameof(StringBuffer.Append), new[] { typeof(DateTime), typeof(StringView) }));
il.Emit(OpCodes.Call, typeof(StringBuffer).GetMethod(nameof(StringBuffer.Append), new[] { typeof(DateTime), typeof(StringView) })!);
break;
}

Expand All @@ -181,14 +179,14 @@ private static Action<PrefixWriter, ILogEventHeader> BuildAppendMethod(ICollecti
il.Emit(OpCodes.Ldloc, stringBufferLocal);

il.Emit(OpCodes.Ldarg_1);
il.Emit(OpCodes.Callvirt, typeof(ILogEventHeader).GetProperty(nameof(ILogEventHeader.Timestamp))?.GetGetMethod());
il.Emit(OpCodes.Stloc, dateTimeLocal ?? (dateTimeLocal = il.DeclareLocal(typeof(DateTime))));
il.Emit(OpCodes.Callvirt, typeof(ILogEventHeader).GetProperty(nameof(ILogEventHeader.Timestamp))?.GetGetMethod()!);
il.Emit(OpCodes.Stloc, dateTimeLocal ??= il.DeclareLocal(typeof(DateTime)));
il.Emit(OpCodes.Ldloca, dateTimeLocal);
il.Emit(OpCodes.Call, typeof(DateTime).GetProperty(nameof(DateTime.TimeOfDay))?.GetGetMethod());
il.Emit(OpCodes.Call, typeof(DateTime).GetProperty(nameof(DateTime.TimeOfDay))?.GetGetMethod()!);

il.Emit(OpCodes.Ldsfld, typeof(StringView).GetField(nameof(StringView.Empty)));
il.Emit(OpCodes.Ldsfld, typeof(StringView).GetField(nameof(StringView.Empty))!);

il.Emit(OpCodes.Call, typeof(StringBuffer).GetMethod(nameof(StringBuffer.Append), new[] { typeof(TimeSpan), typeof(StringView) }));
il.Emit(OpCodes.Call, typeof(StringBuffer).GetMethod(nameof(StringBuffer.Append), new[] { typeof(TimeSpan), typeof(StringView) })!);
break;
}

Expand All @@ -199,11 +197,11 @@ private static Action<PrefixWriter, ILogEventHeader> BuildAppendMethod(ICollecti
il.Emit(OpCodes.Ldloc, stringBufferLocal);

il.Emit(OpCodes.Ldarg_1);
il.Emit(OpCodes.Callvirt, typeof(ILogEventHeader).GetProperty(nameof(ILogEventHeader.ThreadId))?.GetGetMethod());
il.Emit(OpCodes.Callvirt, typeof(ILogEventHeader).GetProperty(nameof(ILogEventHeader.ThreadId))?.GetGetMethod()!);

il.Emit(OpCodes.Ldsfld, typeof(StringView).GetField(nameof(StringView.Empty)));
il.Emit(OpCodes.Ldsfld, typeof(StringView).GetField(nameof(StringView.Empty))!);

il.Emit(OpCodes.Call, typeof(StringBuffer).GetMethod(nameof(StringBuffer.Append), new[] { typeof(int), typeof(StringView) }));
il.Emit(OpCodes.Call, typeof(StringBuffer).GetMethod(nameof(StringBuffer.Append), new[] { typeof(int), typeof(StringView) })!);
break;
}

Expand All @@ -214,10 +212,10 @@ private static Action<PrefixWriter, ILogEventHeader> BuildAppendMethod(ICollecti
il.Emit(OpCodes.Ldloc, stringBufferLocal);

il.Emit(OpCodes.Ldarg_1);
il.Emit(OpCodes.Callvirt, typeof(ILogEventHeader).GetProperty(nameof(ILogEventHeader.Level))?.GetGetMethod());
il.Emit(OpCodes.Call, typeof(LevelStringCache).GetMethod(nameof(LevelStringCache.GetLevelString)));
il.Emit(OpCodes.Callvirt, typeof(ILogEventHeader).GetProperty(nameof(ILogEventHeader.Level))?.GetGetMethod()!);
il.Emit(OpCodes.Call, typeof(LevelStringCache).GetMethod(nameof(LevelStringCache.GetLevelString))!);

il.Emit(OpCodes.Call, typeof(StringBuffer).GetMethod(nameof(StringBuffer.Append), new[] { typeof(string) }));
il.Emit(OpCodes.Call, typeof(StringBuffer).GetMethod(nameof(StringBuffer.Append), new[] { typeof(string) })!);
break;
}

Expand All @@ -228,9 +226,9 @@ private static Action<PrefixWriter, ILogEventHeader> BuildAppendMethod(ICollecti
il.Emit(OpCodes.Ldloc, stringBufferLocal);

il.Emit(OpCodes.Ldarg_1);
il.Emit(OpCodes.Callvirt, typeof(ILogEventHeader).GetProperty(nameof(ILogEventHeader.Name))?.GetGetMethod());
il.Emit(OpCodes.Callvirt, typeof(ILogEventHeader).GetProperty(nameof(ILogEventHeader.Name))?.GetGetMethod()!);

il.Emit(OpCodes.Call, typeof(StringBuffer).GetMethod(nameof(StringBuffer.Append), new[] { typeof(string) }));
il.Emit(OpCodes.Call, typeof(StringBuffer).GetMethod(nameof(StringBuffer.Append), new[] { typeof(string) })!);
break;
}

Expand Down Expand Up @@ -270,7 +268,7 @@ private enum PatternPartType
private struct PatternPart
{
public PatternPartType Type { get; }
public string Value { get; }
public string? Value { get; }

public PatternPart(PatternPartType type)
{
Expand Down
8 changes: 5 additions & 3 deletions src/ZeroLog/ConcurrentQueue.cs
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,8 @@
using System.Runtime.Serialization;
using System.Threading;

#nullable disable

namespace ZeroLog
{
/// <summary>
Expand Down Expand Up @@ -510,7 +512,7 @@ public void CopyTo(T[] array, int index)
/// cref="ConcurrentQueue{T}"/>.</returns>
/// <remarks>
/// The enumeration represents a moment-in-time snapshot of the contents
/// of the queue. It does not reflect any updates to the collection after
/// of the queue. It does not reflect any updates to the collection after
/// <see cref="GetEnumerator"/> was called. The enumerator is safe to use
/// concurrently with reads from and writes to the queue.
/// </remarks>
Expand Down Expand Up @@ -799,7 +801,7 @@ public bool TryPeek(out T result)
/// <summary>
/// Provides a multi-producer, multi-consumer thread-safe bounded segment. When the queue is full,
/// enqueues fail and return false. When the queue is empty, dequeues fail and return null.
/// These segments are linked together to form the unbounded <see cref="ConcurrentQueue{T}"/>.
/// These segments are linked together to form the unbounded <see cref="ConcurrentQueue{T}"/>.
/// </summary>
[DebuggerDisplay("Capacity = {Capacity}")]
private sealed class Segment
Expand Down Expand Up @@ -1091,4 +1093,4 @@ internal struct Slot
}
}
}
}
}
10 changes: 4 additions & 6 deletions src/ZeroLog/Config/AppenderDefinition.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,8 @@
{
public class AppenderDefinition
{
public string Name { get; set; }

public string AppenderTypeName { get; set; }

public dynamic AppenderJsonConfig { get; set; }
public string? Name { get; set; }
public string? AppenderTypeName { get; set; }
public dynamic? AppenderJsonConfig { get; set; }
}
}
}
2 changes: 1 addition & 1 deletion src/ZeroLog/Config/BasicConfigurator.cs
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ public static class BasicConfigurator
{
public static ILogManager Configure(ZeroLogBasicConfiguration config)
{
config = config ?? new ZeroLogBasicConfiguration();
config ??= new ZeroLogBasicConfiguration();
var dummyResolver = new BasicResolver(config.Appenders, config.Level, config.LogEventPoolExhaustionStrategy, config.LogEventArgumentExhaustionStrategy);
return LogManager.Initialize(dummyResolver, config.ToInitializationConfig());
}
Expand Down
Loading

0 comments on commit 8b15217

Please sign in to comment.