Skip to content

Commit

Permalink
CallSiteInformation - Prepare for fast classname lookup from filename…
Browse files Browse the repository at this point in the history
… and linenumber
  • Loading branch information
snakefoot committed Dec 3, 2017
1 parent 46d55f4 commit bc920d1
Show file tree
Hide file tree
Showing 5 changed files with 51 additions and 28 deletions.
2 changes: 1 addition & 1 deletion src/NLog/Fluent/LogBuilder.cs
Original file line number Diff line number Diff line change
Expand Up @@ -306,7 +306,7 @@ public void Write(
if (callerLineNumber != 0)
Property("CallerLineNumber", callerLineNumber);

_logEvent.SetCallerInfo(callerMemberName, callerFilePath, callerLineNumber);
_logEvent.SetCallerInfo(null, callerMemberName, callerFilePath, callerLineNumber);

_logger.Log(_logEvent);
}
Expand Down
21 changes: 20 additions & 1 deletion src/NLog/Internal/CallSiteInformation.cs
Original file line number Diff line number Diff line change
Expand Up @@ -55,11 +55,13 @@ public void SetStackTrace(StackTrace stackTrace, int userStackFrame, int? userSt
/// <summary>
/// Sets the details retrieved from the Caller Information Attributes
/// </summary>
/// <param name="callerClassName"></param>
/// <param name="callerMemberName"></param>
/// <param name="callerFilePath"></param>
/// <param name="callerLineNumber"></param>
public void SetCallerInfo(string callerMemberName, string callerFilePath, int callerLineNumber)
public void SetCallerInfo(string callerClassName, string callerMemberName, string callerFilePath, int callerLineNumber)
{
CallerClassName = callerClassName;
CallerMemberName = callerMemberName;
CallerFilePath = callerFilePath;
CallerLineNumber = callerLineNumber;
Expand Down Expand Up @@ -94,6 +96,22 @@ public MethodBase GetCallerStackFrameMethod(int skipFrames)

public string GetCallerClassName(MethodBase method, bool includeNameSpace, bool cleanAsyncMoveNext, bool cleanAnonymousDelegates)
{
if (!string.IsNullOrEmpty(CallerClassName))
{
if (includeNameSpace)
{
return CallerClassName;
}
else
{
int lastDot = CallerClassName.LastIndexOf('.');
if (lastDot < 0 || lastDot >= CallerClassName.Length - 1)
return CallerClassName;
else
return CallerClassName.Substring(lastDot + 1);
}
}

method = method ?? GetCallerStackFrameMethod(0);
if (method == null)
return string.Empty;
Expand Down Expand Up @@ -139,6 +157,7 @@ public int GetCallerLineNumber(int skipFrames)
return frame?.GetFileLineNumber() ?? 0;
}

public string CallerClassName { get; private set; }
public string CallerMemberName { get; private set; }
public string CallerFilePath { get; private set; }
public int? CallerLineNumber { get; private set; }
Expand Down
11 changes: 4 additions & 7 deletions src/NLog/LayoutRenderers/CallSiteLayoutRenderer.cs
Original file line number Diff line number Diff line change
Expand Up @@ -31,17 +31,14 @@
// THE POSSIBILITY OF SUCH DAMAGE.
//

using System;

namespace NLog.LayoutRenderers
{
using System;
using System.ComponentModel;
using System.Diagnostics;
using System.IO;
using System.Reflection;
using System.Text;
using Config;
using Internal;
using NLog.Config;
using NLog.Internal;

/// <summary>
/// The call site (class name, method name and source information).
Expand Down Expand Up @@ -178,7 +175,7 @@ protected override void Append(StringBuilder builder, LogEventInfo logEvent)
if (FileName)
{
string fileName = logEvent.CallSiteInformation.GetCallerFilePath(SkipFrames);
if (fileName != null)
if (!string.IsNullOrEmpty(fileName))
{
int lineNumber = logEvent.CallSiteInformation.GetCallerLineNumber(SkipFrames);
AppendFileName(builder, fileName, lineNumber);
Expand Down
10 changes: 8 additions & 2 deletions src/NLog/LogEventInfo.cs
Original file line number Diff line number Diff line change
Expand Up @@ -193,6 +193,11 @@ public LogEventInfo(LogLevel level, string loggerName, IFormatProvider formatPro
/// </summary>
public StackTrace StackTrace => CallSiteInformation?.StackTrace;

/// <summary>
/// Gets the callsite class name
/// </summary>
public string CallerClassName => CallSiteInformation?.CallerClassName;

/// <summary>
/// Gets the callsite member function name
/// </summary>
Expand Down Expand Up @@ -516,12 +521,13 @@ public void SetStackTrace(StackTrace stackTrace, int userStackFrame)
/// <summary>
/// Sets the details retrieved from the Caller Information Attributes
/// </summary>
/// <param name="callerClassName"></param>
/// <param name="callerMemberName"></param>
/// <param name="callerFilePath"></param>
/// <param name="callerLineNumber"></param>
public void SetCallerInfo(string callerMemberName, string callerFilePath, int callerLineNumber)
public void SetCallerInfo(string callerClassName, string callerMemberName, string callerFilePath, int callerLineNumber)
{
GetCallSiteInformationInternal().SetCallerInfo(callerMemberName, callerFilePath, callerLineNumber);
GetCallSiteInformationInternal().SetCallerInfo(callerClassName, callerMemberName, callerFilePath, callerLineNumber);
}

internal string AddCachedLayoutValue(Layout layout, string value)
Expand Down
35 changes: 18 additions & 17 deletions tests/NLog.UnitTests/LayoutRenderers/CallSiteTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -217,6 +217,24 @@ public void ClassNameTestWithoutNamespace()
AssertDebugLastMessage("debug", "CallSiteTests msg");
}

[Fact]
public void ClassNameTestWithOverride()
{
LogManager.Configuration = CreateConfigurationFromString(@"
<nlog>
<targets><target name='debug' type='Debug' layout='${callsite:classname=true:methodname=false:includeNamespace=false} ${message}' /></targets>
<rules>
<logger name='*' minlevel='Debug' writeTo='debug' />
</rules>
</nlog>");

ILogger logger = LogManager.GetLogger("A");
var logEvent = LogEventInfo.Create(LogLevel.Debug, logger.Name, "msg");
logEvent.SetCallerInfo("NLog.UnitTests.LayoutRenderers.OverrideClassName", nameof(ClassNameTestWithOverride), null, 0);
logger.Log(logEvent);
AssertDebugLastMessage("debug", "OverrideClassName msg");
}

[Fact]
public void ClassNameWithPaddingTestPadLeftAlignLeftTest()
{
Expand Down Expand Up @@ -542,7 +560,6 @@ public void DontCleanClassNamesOfAnonymousDelegatesTest()
[Fact]
public void When_Wrapped_Ignore_Wrapper_Methods_In_Callstack()
{

//namespace en name of current method
const string currentMethodFullName = "NLog.UnitTests.LayoutRenderers.CallSiteTests.When_Wrapped_Ignore_Wrapper_Methods_In_Callstack";

Expand Down Expand Up @@ -633,7 +650,6 @@ public void CheckStackTraceUsageForMultipleRules()
[Fact]
public void When_WrappedInCompsition_Ignore_Wrapper_Methods_In_Callstack()
{

//namespace en name of current method
const string currentMethodFullName = "NLog.UnitTests.LayoutRenderers.CallSiteTests.When_WrappedInCompsition_Ignore_Wrapper_Methods_In_Callstack";

Expand All @@ -652,7 +668,6 @@ public void When_WrappedInCompsition_Ignore_Wrapper_Methods_In_Callstack()
CompositeWrapper wrappedLogger = new CompositeWrapper();
wrappedLogger.Log("wrapped");
AssertDebugLastMessage("debug", $"{currentMethodFullName}|wrapped");

}

#if NET3_5 || NET4_0
Expand All @@ -662,7 +677,6 @@ public void When_WrappedInCompsition_Ignore_Wrapper_Methods_In_Callstack()
#endif
public void Show_correct_method_with_async()
{

//namespace en name of current method
const string currentMethodFullName = "NLog.UnitTests.LayoutRenderers.CallSiteTests.AsyncMethod";

Expand All @@ -676,7 +690,6 @@ public void Show_correct_method_with_async()

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

}

private async Task AsyncMethod()
Expand Down Expand Up @@ -716,7 +729,6 @@ public void Show_correct_filename_with_async()
#endif
public void Show_correct_method_with_async2()
{

//namespace en name of current method
const string currentMethodFullName = "NLog.UnitTests.LayoutRenderers.CallSiteTests.AsyncMethod2b";

Expand Down Expand Up @@ -801,7 +813,6 @@ public async Task<IEnumerable<string>> AsyncMethod4()
#endif
public void Show_correct_method_with_async4()
{

//namespace en name of current method
const string currentMethodFullName = "NLog.UnitTests.LayoutRenderers.CallSiteTests.AsyncMethod4";

Expand All @@ -815,7 +826,6 @@ public void Show_correct_method_with_async4()

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

}

#if NET3_5 || NET4_0 || NETSTANDARD1_5
Expand Down Expand Up @@ -855,7 +865,6 @@ public async Task<string> GetAsyncCallSite()
#endif
public void Show_correct_method_for_moveNext()
{

//namespace en name of current method
const string currentMethodFullName = "NLog.UnitTests.LayoutRenderers.CallSiteTests.MoveNext";

Expand All @@ -877,7 +886,6 @@ private void MoveNext()
{
var logger = LogManager.GetCurrentClassLogger();
logger.Warn("direct");

}

public class CompositeWrapper
Expand Down Expand Up @@ -954,7 +962,6 @@ public void CallsiteBySubclass_interface()
Assert.True(logger is MyLogger, "logger isn't MyLogger");
logger.Debug("msg");
AssertDebugLastMessage("debug", "NLog.UnitTests.LayoutRenderers.CallSiteTests.CallsiteBySubclass_interface msg");

}

[Fact]
Expand All @@ -973,7 +980,6 @@ public void CallsiteBySubclass_mylogger()
Assert.NotNull(logger);
logger.Debug("msg");
AssertDebugLastMessage("debug", "NLog.UnitTests.LayoutRenderers.CallSiteTests.CallsiteBySubclass_mylogger msg");

}

[Fact]
Expand Down Expand Up @@ -1051,7 +1057,6 @@ public class NLogFactory
{
internal const string defaultConfigFileName = "nlog.config";


/// <summary>
/// Initializes a new instance of the <see cref="NLogFactory" /> class.
/// </summary>
Expand Down Expand Up @@ -1150,8 +1155,6 @@ public void LogAfterAwait_CleanNamesOfAsyncContinuationsIsFalse_ShouldNotCleanNa

AsyncMethod5().GetAwaiter().GetResult();



if (IsTravis())
{
Console.WriteLine("[SKIP] LogAfterAwait_CleanNamesOfAsyncContinuationsIsFalse_ShouldNotCleanNames - test is unstable on Travis");
Expand All @@ -1161,7 +1164,6 @@ public void LogAfterAwait_CleanNamesOfAsyncContinuationsIsFalse_ShouldNotCleanNa
AssertDebugLastMessageContains("debug", "NLog.UnitTests.LayoutRenderers.CallSiteTests");
AssertDebugLastMessageContains("debug", "MoveNext");
AssertDebugLastMessageContains("debug", "d__");

}

private async Task AsyncMethod5()
Expand Down Expand Up @@ -1219,7 +1221,6 @@ public void Log(LogLevel logLevel, string message)
{
Logger.Log(typeof(NLogLogger), new LogEventInfo(logLevel, Logger.Name, message));
}

}
}
}

0 comments on commit bc920d1

Please sign in to comment.