Skip to content

Commit

Permalink
Merge pull request #33 from Abc-Arbitrage/update-stringformatter
Browse files Browse the repository at this point in the history
Update StringFormatter
  • Loading branch information
MendelMonteiro authored May 31, 2019
2 parents aa12bc9 + 7a66ffc commit ed03d11
Show file tree
Hide file tree
Showing 20 changed files with 157 additions and 79 deletions.
4 changes: 0 additions & 4 deletions src/ZeroLog.Benchmarks/ZeroLog.Benchmarks.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -22,8 +22,4 @@
<PackageReference Include="System.ValueTuple" Version="4.5.0" />
</ItemGroup>

<ItemGroup>
<Reference Include="System.ComponentModel.Composition" />
<Reference Include="Microsoft.CSharp" />
</ItemGroup>
</Project>
2 changes: 1 addition & 1 deletion src/ZeroLog.Tests/Appenders/AppenderBaseTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ public void should_append()
appender.WriteEvent(logEventHeader, bytes, byteLength);
appender.Flush();

var logLine = $"{logEventHeader.Timestamp.Date:yyyy-MM-dd} - {logEventHeader.Timestamp.TimeOfDay:hh\\:mm\\:ss\\.fff} - {logEventHeader.ThreadId} - INFO - TestLog || {message}{Environment.NewLine}";
var logLine = $"{logEventHeader.Timestamp.Date:yyyy-MM-dd} - {logEventHeader.Timestamp.TimeOfDay:hh\\:mm\\:ss\\.fffffff} - {logEventHeader.ThreadId} - INFO - TestLog || {message}{Environment.NewLine}";

Check.That(appender.ToString()).IsEqualTo(logLine + logLine);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,7 @@ public void should_log_to_file()

var written = GetLastLine();

Check.That(written).IsEqualTo($"{logEventHeader.Timestamp.Date:yyyy-MM-dd} - {logEventHeader.Timestamp.TimeOfDay:hh\\:mm\\:ss\\.fff} - {logEventHeader.ThreadId} - INFO - TestLog || " + message);
Check.That(written).IsEqualTo($"{logEventHeader.Timestamp.Date:yyyy-MM-dd} - {logEventHeader.Timestamp.TimeOfDay:hh\\:mm\\:ss\\.fffffff} - {logEventHeader.ThreadId} - INFO - TestLog || " + message);
}

private string GetLastLine()
Expand Down
6 changes: 3 additions & 3 deletions src/ZeroLog.Tests/LogEventTests.Append.cs
Original file line number Diff line number Diff line change
Expand Up @@ -261,7 +261,7 @@ public void should_append_time_span()
_logEvent.Append(new TimeSpan(1, 2, 3, 4, 5));
_logEvent.WriteToStringBuffer(_output);

Assert.AreEqual("02:03:04.005", _output.ToString());
Assert.AreEqual("1.02:03:04.0050000", _output.ToString());
}

[Test]
Expand All @@ -284,7 +284,7 @@ public void should_append_all_types()

_logEvent.WriteToStringBuffer(_output);

Assert.AreEqual("AbCFalseTrue128£12345-128999999999999999999123.456789.012345.67890129ac124-e588-47e5-9d3d-fa3a4d174e292017-01-12 13:14:15.00002:03:04.005", _output.ToString());
Assert.AreEqual("AbCFalseTrue128£12345-128999999999999999999123.456789.012345.67890129ac124-e588-47e5-9d3d-fa3a4d174e292017-01-12 13:14:15.0001.02:03:04.0050000", _output.ToString());
}

[Test]
Expand All @@ -311,7 +311,7 @@ public void should_append_format()

_logEvent.WriteToStringBuffer(_output);

Assert.AreEqual("AbCFalseTrue128£12345-128999999999999999999123.456789.012345.67890129ac124-e588-47e5-9d3d-fa3a4d174e292017-01-12 13:14:15.00002:03:04.0051-2-3", _output.ToString());
Assert.AreEqual("AbCFalseTrue128£12345-128999999999999999999123.456789.012345.67890129ac124-e588-47e5-9d3d-fa3a4d174e292017-01-12 13:14:15.0001.02:03:04.00500001-2-3", _output.ToString());
}

[Test]
Expand Down
8 changes: 5 additions & 3 deletions src/ZeroLog.Tests/LogEventTests.AppendWithFormat.cs
Original file line number Diff line number Diff line change
Expand Up @@ -90,10 +90,12 @@ public void should_append_date_time_with_format()
[Test]
public void should_append_time_span_with_format()
{
_logEvent.Append(new TimeSpan(1, 2, 3, 4, 5), "TODO in StringFormatter");
_logEvent.Append(new TimeSpan(1, 2, 3, 4, 5), "g");
_logEvent.WriteToStringBuffer(_output);

Assert.AreEqual("02:03:04.005", _output.ToString());
Assert.IsNotEmpty(_output.ToString());

Assert.AreEqual("1:2:03:04.005", _output.ToString());
}

[TestCase(typeof(byte), "X4")]
Expand All @@ -105,7 +107,7 @@ public void should_append_time_span_with_format()
[TestCase(typeof(decimal), "E04")]
[TestCase(typeof(Guid), "X")]
[TestCase(typeof(DateTime), "yyyy-MM-dd")]
[TestCase(typeof(TimeSpan), "TODO in StringFormatter")]
[TestCase(typeof(TimeSpan), "g")]
public void should_append_nullable_with_format(Type type, string format)
{
typeof(LogEventTests).GetMethod(nameof(should_append_nullable_with_format), BindingFlags.Instance | BindingFlags.NonPublic, null, new[] { typeof(string) }, null)
Expand Down
2 changes: 1 addition & 1 deletion src/ZeroLog.Tests/LogManagerTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -225,7 +225,7 @@ public unsafe void should_not_throw_if_formatting_fails_when_appending_formatted
signal.Wait(TimeSpan.FromMilliseconds(100));

var logMessage = _testAppender.LoggedMessages.Single();
Check.That(logMessage).Equals("An error occured during formatting: \"Hello\", False, 1, 'a', 2, 3, 4, 5, 6, 7, " + guid + ", 2017-02-24 16:51:51.000, 16:51:51.000, \"abc\", \"abc\", Friday");
Check.That(logMessage).Equals("An error occured during formatting: \"Hello\", False, 1, 'a', 2, 3, 4, 5, 6, 7, " + guid + ", 2017-02-24 16:51:51.000, 16:51:51, \"abc\", \"abc\", Friday");
}

[Test]
Expand Down
58 changes: 58 additions & 0 deletions src/ZeroLog.Tests/LogTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -102,6 +102,64 @@ public void should_log_enums_with_simple_api()
);
}

[Test]
public void should_log_datetime_with_simple_api()
{
var log = new Log(_logManager, "logger");

var dateTime = new DateTime(2000, 1, 2, 3, 4, 5, 6);

log.InfoFormat("foo {0} bar", dateTime);
log.InfoFormat("foo {0:d} bar", dateTime);
log.InfoFormat("foo {0:yyyy-MM-dd} bar", dateTime);
log.InfoFormat("foo {0} bar", (DateTime?)dateTime);
log.InfoFormat("foo {0:d} bar", (DateTime?)dateTime);
log.InfoFormat("foo {0} bar", (DateTime?)null);
log.InfoFormat("foo {0:d} bar", (DateTime?)null);

WaitForEmptyQueue();

Check.That(_appender.LoggedMessages).ContainsExactly(
"foo 2000-01-02 03:04:05.006 bar",
"foo 2000-01-02 bar",
"foo 2000-01-02 bar",
"foo 2000-01-02 03:04:05.006 bar",
"foo 2000-01-02 bar",
"foo null bar",
"foo null bar"
);
}

[Test]
public void should_log_timespan_with_simple_api()
{
var log = new Log(_logManager, "logger");

var timeSpan = new TimeSpan(1, 2, 3, 4, 5);

log.InfoFormat("foo {0} bar", timeSpan);
log.InfoFormat("foo {0:c} bar", timeSpan);
log.InfoFormat("foo {0:g} bar", timeSpan);
log.InfoFormat("foo {0:G} bar", timeSpan);
log.InfoFormat("foo {0} bar", (TimeSpan?)timeSpan);
log.InfoFormat("foo {0:g} bar", (TimeSpan?)timeSpan);
log.InfoFormat("foo {0} bar", (TimeSpan?)null);
log.InfoFormat("foo {0:g} bar", (TimeSpan?)null);

WaitForEmptyQueue();

Check.That(_appender.LoggedMessages).ContainsExactly(
"foo 1.02:03:04.0050000 bar",
"foo 1.02:03:04.0050000 bar",
"foo 1:2:03:04.005 bar",
"foo 1:02:03:04.0050000 bar",
"foo 1.02:03:04.0050000 bar",
"foo 1:2:03:04.005 bar",
"foo null bar",
"foo null bar"
);
}

[Test]
[SuppressMessage("ReSharper", "FormatStringProblem")]
public void should_log_unmanaged_types_with_simple_api()
Expand Down
10 changes: 2 additions & 8 deletions src/ZeroLog.Tests/ZeroLog.Tests.csproj
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFrameworks>netcoreapp2.0;net452;net47</TargetFrameworks>
<TargetFrameworks>netcoreapp2.0;net47</TargetFrameworks>
<OutputType>Exe</OutputType>
<GenerateAssemblyInfo>false</GenerateAssemblyInfo>
<StartupObject>ZeroLog.Tests.Program</StartupObject>
Expand All @@ -11,19 +11,13 @@
</ItemGroup>

<ItemGroup>
<PackageReference Include="Jil" Version="2.15.4" />
<PackageReference Include="Microsoft.CSharp" Version="4.5.0" />
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="15.8.0" />
<PackageReference Include="Moq" Version="4.10.0" />
<PackageReference Include="NCrunch.Framework" Version="3.17.0" />
<PackageReference Include="NFluent" Version="2.3.1" />
<PackageReference Include="NUnit" Version="3.10.1" />
<PackageReference Include="NUnit3TestAdapter" Version="3.10.0" />
<PackageReference Include="StringFormatter" Version="1.0.0.11" />
<PackageReference Include="System.ValueTuple" Version="4.5.0" />
</ItemGroup>

<ItemGroup>
<Reference Include="Microsoft.CSharp" />
<Reference Include="System.Net.Http" />
</ItemGroup>
</Project>
3 changes: 1 addition & 2 deletions src/ZeroLog/Appenders/AppenderBase.cs
Original file line number Diff line number Diff line change
@@ -1,14 +1,13 @@
using System;
using System.IO;
using System.Text;
using ZeroLog.Utils;

namespace ZeroLog.Appenders
{
public abstract class AppenderBase<T> : IAppender<T>
{
private Encoding _encoding;
private byte[] _newlineBytes = ArrayUtil.Empty<byte>();
private byte[] _newlineBytes = Array.Empty<byte>();
private PrefixWriter _prefixWriter;

protected void Configure(string prefixPattern)
Expand Down
4 changes: 2 additions & 2 deletions src/ZeroLog/EnumCache.cs
Original file line number Diff line number Diff line change
Expand Up @@ -128,7 +128,7 @@ internal static ulong ToUInt64Slow(Enum value)
private static ulong? ToUInt64Nullable<T, TBase>(T value) // T = Nullable<SomeEnum>
where TBase : struct
{
ref var nullable = ref TypeUtil.As<T, TBase?>(ref value);
ref var nullable = ref Unsafe.As<T, TBase?>(ref value);
return nullable != null
? ToUInt64(nullable.GetValueOrDefault())
: (ulong?)null;
Expand Down Expand Up @@ -191,7 +191,7 @@ public ArrayEnumStrings(List<EnumItem> enumItems)
{
if (enumItems.Count == 0)
{
_strings = ArrayUtil.Empty<string>();
_strings = Array.Empty<string>();
return;
}

Expand Down
6 changes: 3 additions & 3 deletions src/ZeroLog/Log.Custom.cs
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
using ZeroLog.Appenders;
using ZeroLog.Utils;
using System;
using ZeroLog.Appenders;

namespace ZeroLog
{
Expand Down Expand Up @@ -39,7 +39,7 @@ internal void ResetConfiguration()
{
var config = _logManager?.ResolveLogConfig(Name);

Appenders = config?.Appenders ?? ArrayUtil.Empty<IAppender>();
Appenders = config?.Appenders ?? Array.Empty<IAppender>();
LogEventPoolExhaustionStrategy = config?.LogEventPoolExhaustionStrategy ?? default;
LogEventArgumentExhaustionStrategy = config?.LogEventArgumentExhaustionStrategy ?? default;
_logLevel = config?.Level ?? Level.Fatal;
Expand Down
6 changes: 3 additions & 3 deletions src/ZeroLog/LogEvent.cs
Original file line number Diff line number Diff line change
Expand Up @@ -207,19 +207,19 @@ private void AppendNullableEnumInternal<T>(T value) // T = Nullable<SomeEnum>
[MethodImpl(MethodImplOptions.NoInlining)]
private void AppendUnmanagedInternal<T>(T arg) // T = unmanaged or Nullable<unmanaged>
{
if (!PrepareAppend(sizeof(ArgumentType) + sizeof(UnmanagedArgHeader) + TypeUtil.SizeOf<T>()))
if (!PrepareAppend(sizeof(ArgumentType) + sizeof(UnmanagedArgHeader) + Unsafe.SizeOf<T>()))
return;

// If T is a Nullable<unmanaged>, we copy it as-is and let the formatter deal with it.
// We're already in a slower execution path at this point.

AppendArgumentType(ArgumentType.Unmanaged);
*(UnmanagedArgHeader*)_dataPointer = new UnmanagedArgHeader(TypeUtil<T>.TypeHandle, TypeUtil.SizeOf<T>());
*(UnmanagedArgHeader*)_dataPointer = new UnmanagedArgHeader(TypeUtil<T>.TypeHandle, Unsafe.SizeOf<T>());
_dataPointer += sizeof(UnmanagedArgHeader);
IL.Push(_dataPointer);
IL.Push(arg);
Stobj(typeof(T));
_dataPointer += TypeUtil.SizeOf<T>();
_dataPointer += Unsafe.SizeOf<T>();
}

public void Log()
Expand Down
2 changes: 1 addition & 1 deletion src/ZeroLog/LogManager.cs
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ public class LogManager : IInternalLogManager
private readonly Thread _writeThread;

private bool _isRunning;
private IAppender[] _appenders = ArrayUtil.Empty<IAppender>();
private IAppender[] _appenders = Array.Empty<IAppender>();

public static ZeroLogConfig Config { get; } = new ZeroLogConfig();

Expand Down
3 changes: 1 addition & 2 deletions src/ZeroLog/NoopLogEvent.cs
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
using System;
using System.Text.Formatting;
using ZeroLog.Appenders;
using ZeroLog.Utils;

namespace ZeroLog
{
Expand All @@ -13,7 +12,7 @@ internal partial class NoopLogEvent : IInternalLogEvent
public DateTime Timestamp => default;
public int ThreadId => 0;
public string Name => null;
public IAppender[] Appenders { get; } = ArrayUtil.Empty<IAppender>();
public IAppender[] Appenders { get; } = Array.Empty<IAppender>();

private NoopLogEvent()
{
Expand Down
3 changes: 1 addition & 2 deletions src/ZeroLog/NoopLogManager.cs
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
using System;
using ZeroLog.Appenders;
using ZeroLog.Utils;

namespace ZeroLog
{
Expand Down Expand Up @@ -38,7 +37,7 @@ private class NoopLog : ILog
{
public static NoopLog Instance { get; } = new NoopLog();

public IAppender[] Appenders { get; } = ArrayUtil.Empty<IAppender>();
public IAppender[] Appenders { get; } = Array.Empty<IAppender>();

public bool IsDebugEnabled => false;
public bool IsInfoEnabled => false;
Expand Down
1 change: 0 additions & 1 deletion src/ZeroLog/UnmanagedCache.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Text.Formatting;
using JetBrains.Annotations;
using ZeroLog.Utils;
Expand Down
23 changes: 0 additions & 23 deletions src/ZeroLog/Utils/ArrayUtil.cs

This file was deleted.

17 changes: 0 additions & 17 deletions src/ZeroLog/Utils/TypeUtil.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,7 @@
using System.Diagnostics.CodeAnalysis;
using System.Reflection;
using System.Runtime.CompilerServices;
using InlineIL;
using JetBrains.Annotations;
using static InlineIL.IL.Emit;
using static System.Linq.Expressions.Expression;

namespace ZeroLog.Utils
Expand All @@ -19,21 +17,6 @@ public static IntPtr GetTypeHandleSlow(Type type)
public static Type GetTypeFromHandle(IntPtr typeHandle)
=> _getTypeFromHandleFunc?.Invoke(typeHandle);

[MethodImpl(MethodImplOptions.AggressiveInlining)]
[SuppressMessage("ReSharper", "UnusedParameter.Global")]
public static ref TTo As<TFrom, TTo>(ref TFrom source)
{
Ldarg(nameof(source));
return ref IL.ReturnRef<TTo>();
}

[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static int SizeOf<T>()
{
Sizeof(typeof(T));
return IL.Return<int>();
}

private static Func<IntPtr, Type> BuildGetTypeFromHandleFunc()
{
var method = typeof(Type).GetMethod("GetTypeFromHandleUnsafe", BindingFlags.Static | BindingFlags.NonPublic, null, new[] { typeof(IntPtr) }, null);
Expand Down
Loading

0 comments on commit ed03d11

Please sign in to comment.