简体   繁体   中英

How to pass custom data to the log4net.Core.LoggingEvent object?

I want to get custom data from the log4net.Core.LoggingEvent object inside Append method of my custom log4net appender.

public sealed class SimpleAppender : AppenderSkeleton
{
    protected override void Append(LoggingEvent loggingEvent)
    {
        // How can I receive my data?
    }
}

I know that log4net.Core.LoggingEvent contains Properties property. It has type log4net.Util.PropertiesDictionary . A logger or an appender may attach additional properties to specific events, but I'm not sure that it is what the way I'm looking for. I need to get testId here. I created that testId in the method marked [TestInitialize] attribute.

public class UnitTest1
{
    public TestContext TestContext { get; set; }

    [TestInitialize]
    public void Initialize()
    {
        Guid testId = Guid.NewGuid();
    }

    [TestMethod]
    public void TestMethod1()
    {
        ApplicationLogger.LogInfo("TestMethod1 has started.");
    }       
}

ApplicationLogger class is a simple log4net logger wrapper which prints result into console. I know that I can do something like this.

ApplicationLogger.LogInfo("Test message", testId);

public static class ApplicationLogger
{
    private static readonly log4net.ILog log4netLogger;

    public static void LogInfo(Guid testId, string infoMessage)
    {
        ApplicationLogger.log4netLogger.Info(new LogMessageModel
        {
            Text = infoMessage,
            TestId = testId
        });
    }
}

But I don't want to set testId into LogInfo() method every time I need to log something. Is there another more more elegant way? Thanks in advance.

ApplicationLogger添加一个静态的Initialize()函数,该函数接受testId作为参数,然后从UnitTest1.Initialize()调用ApplicationLogger.Initialize(testId) UnitTest1.Initialize()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM