TL;DR - 跳转到最后一段
背景
我正在执行一些数据驱动测试,并将日志文件用作测试输出之一。它的工作原理是这样的-
- 读取文件夹中的第一个文件
- 阅读下一个文件
- Chờ đợi
我的日志文件反射(reflect)了这一点:
INFO - Start RunAllFilesInFolder
INFO - File1:
INFO - Some info
INFO - Executing Test 1
INFO - Validation A result
INFO - ...
INFO - ...
INFO - File2:
...
目前我这样使用/调用 Log 4 net-
static class LogHelper
{
internal static readonly log4net.ILog Log = log4net.LogManager.GetLogger
(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
}
// another file
using static Some.Namespace.LogHelper;
class SomeClass
{
Log.Info($"\t\tExecuting {t.Number}-{t.Name}");
}
缩进 = "\t"、"\t\t"或 "\t\t\t"取决于测试所在的级别。
有没有一种方法可以重构对 LogHelper.Log 的调用,以便它考虑静态“缩进”,当我进入不同的测试级别时可以增加/减少,而无需在每次调用中明确指定缩进?
即能够在适用的情况下调用类似
Log.Indent.Increase();
hoặc
Log.Indent.Decrease();
并将上面的调用简单地替换为 -
Log.Info($"Executing {t.Number}-{t.Name}");
Bạn có thể sử dụng stack trace长度,通过计算新行的数量:
int someSensibleMinimum = 3; //something that works for you
int count = Environment.StackTrace.Count(a => a=='\n');
var indent = new string('\t', Math.Max(0, count - someSensibleMinimum));
请注意,在 Release 中它的行为可能会有所不同:
However, the StackTrace property might not report as many method calls as expected due to code transformations that occur during optimization.
或者,您可以使用这种方法(伪代码)自动计算长度:
int count = Environment.StackTrace.Count(a => a=='\n');
Look for stack length in dictionary (length to indent string)
If found use it.
If not found, find the largest entry in dictionary where key < count
add new entry to dictionary one tab char longer
在代码中:
public sealed class IndentTracker
{
private readonly ThreadLocal<>> _dictionaryLocal =
new ThreadLocal<>>(() => new Dictionary());
public string GetIndent()
{
Dictionary dictionary = _dictionaryLocal.Value;
int count = Environment.StackTrace.Count(a => a == '\n');
if (!dictionary.Any())
{
string initialIndent = string.Empty;
dictionary.Add(count, initialIndent);
return initialIndent;
}
string indent;
if (dictionary.TryGetValue(count, out indent))
return indent;
string last = dictionary.OrderByDescending(k => k.Key).First(k => k.Key < count).Value;
string newIndent = last + '\t';
dictionary.Add(count, newIndent);
return newIndent;
}
}
这在按递增深度顺序登录时有效。例如,如果您在堆栈深度 10 然后 5 记录(之前没有在堆栈深度 5 然后 10 记录),它将失败。
Tôi là một lập trình viên xuất sắc, rất giỏi!