如何在 log4net 中以编程方式创建 Seq Appender?

How do you create SeqAppender programatically in log4net?

我根据其他关于如何以编程方式添加自定义附加程序的回复尝试了以下代码。我确实看到日志消息出现在控制台上,但我没有在本地 运行 Seq 服务器中看到它们。我验证了 Seq URL 已设置 http://localhost:5341/。我还尝试了一个带有 API Key 的托管版本的 Seq,看看我是否可以捕获通过 Fiddler 设置的任何内容,但没有发送任何内容。我错过了什么?

public static void SetLevel(string loggerName, string levelName)
{
    ILog log = LogManager.GetLogger(loggerName);
    Logger l = (Logger)log.Logger;

    l.Level = l.Hierarchy.LevelMap[levelName];
}

// Add an appender to a logger
public static void AddAppender(string loggerName, IAppender appender)
{
    ILog log = LogManager.GetLogger(loggerName);
    Logger l = (Logger)log.Logger;

    l.AddAppender(appender);
    l.Repository.Configured = true;
}

// Create a new file appender
public static IAppender CreateSeqAppender(string name)
{
    var seqAppender = new SeqAppender();
    seqAppender.ServerUrl = ConfigurationManager.AppSettings["Seq:Url"];
    var seqApiKey = ConfigurationManager.AppSettings["Seq:ApiKey"];
    if (seqApiKey != null)
    {
        seqAppender.ApiKey = seqApiKey;
    }
    PatternLayout patternLayout = new PatternLayout();

    var LOG_PATTERN = "%d [%t] %-5p %m%n";
    patternLayout.ConversionPattern = LOG_PATTERN;
    patternLayout.ActivateOptions();
    seqAppender.Name = name;
    seqAppender.BufferSize = 1;
    seqAppender.Layout = patternLayout;
    seqAppender.ActivateOptions();

    return seqAppender;
}

static void Main()
{
    BasicConfigurator.Configure();
    // In order to set the level for a logger and add an appender reference you
    // can then use the following calls:
    SetLevel("Log4net.MainForm", "ALL");
    AddAppender("Log4net.MainForm", CreateSeqAppender("SeqAppender"));

    //BasicConfigurator.Configure();

    var logger = LogManager.GetLogger("MyLogger");

    logger.Info("This is a test log message");
}

经过更多调查后,我想出了如何让它发挥作用。相反,我只是做了以下 AddAppender 中的代码:

var root = ((Hierarchy)LogManager.GetRepository()).Root;
        root.AddAppender(CreateSeqAppender());

希望这对其他人有所帮助。