TL;DR - jump to last paragraph
Background
I'm performing some data driven testing and using the log file as one of the testing outputs. It works something like this-
- Read first file in folder
- Process first line and convert to a test
- Run Test
- Perform Validation 1
- ...
- ...
- Read next file
- Etc.
My log file reflects this:
INFO - Start RunAllFilesInFolder
INFO - File1:
INFO - Some info
INFO - Executing Test 1
INFO - Validation A result
INFO - ...
INFO - ...
INFO - File2:
...
At the moment I use/call Log 4 net like this-
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}");
}
Where indent = "\t", "\t\t" or "\t\t\t" depending on the level the test is in.
Is there a way to refactor the call to LogHelper.Log so that it takes into account a static "indent" that can be increased/decreased as I step into the different test levels without explicitly specifying the indent in each call?
I.e. Be able to call where applicable something like
Log.Indent.Increase();
Or
Log.Indent.Decrease();
And replace the above call to log simply with -
Log.Info($"Executing {t.Number}-{t.Name}");
You could use the stack trace length, by counting the number of new lines:
Note that in Release it may behave differently:
Or, you could automagically calculate the length using this approach (pseudocode):
In code:
This works when log in increasing depth order. For example, it fails if you log at stack depth 10, then 5 (without previously logging at stack depth 5 then 10).