如何克隆log4net Appender?

时间:2017-12-08 16:01:20

标签: c# log4net

我想创建许多不同的记录器,每个记录器都写入自己的文件。

如何克隆我已经配置的appender,只需更改它使用的名称和文件,这样我就可以在一个地方控制所有这些配置?

到目前为止,我的目标是:

public Client(string host, int port, string sessionId, TimeSpan timeoutMilliseconds, TimeSpan reconnectAttemptInterval)
{
    //SNIP

    // Create an individual logger for each client
    string loggerName = "Client #" + _id.ToString();
    string logFilename = loggerName + ".log";

    var hierarchy = (Hierarchy)LogManager.GetRepository();
    var logger = hierarchy.LoggerFactory.CreateLogger((ILoggerRepository)hierarchy, loggerName);
    logger.Hierarchy = hierarchy;

    // Get the appenders from config
    var consoleAppender = (ConsoleAppender)LogManager.GetRepository().GetAppenders().First(x => x.Name == "Console");
    var rollingAppender = (RollingFileAppender)LogManager.GetRepository().GetAppenders().First(x => x.Name == "RollingFile");

    // Create the per client appenders
    // TODO - Instead, clone this from the rolling appender in the config and change its name and its file.
    //        That way we can configure all appenders without a rebuild
    var fileAppender = new RollingFileAppender
    {
        Name = loggerName + "Appender",
        File = logFilename,
        LockingModel = new FileAppender.MinimalLock(),
        AppendToFile = false,
        RollingStyle = RollingFileAppender.RollingMode.Size,
        MaxSizeRollBackups = 20,
        MaximumFileSize = "50MB",
        StaticLogFileName = true,
        Layout = new log4net.Layout.PatternLayout("%-5p %d [%t] %m %n")
    };
    fileAppender.ActivateOptions();
    logger.AddAppender(fileAppender);
    logger.AddAppender(consoleAppender);

    logger.Level        = Level.All;     // See appender for filtering
    hierarchy.Threshold = Level.Fatal;

    logger.Repository.Configured = true;

    _log = new LogImpl(logger);
    _log.Debug(string.Format("{0} has been created.", loggerName));
}

一位用户建议这是一个重复的问题Deep cloning objects

我不知道列出的任何解决方案是如何适用的,因为log4net是第三方库,我无法在第三方的源中实现ICloneable或ISerializable。

1 个答案:

答案 0 :(得分:0)

AppenderCollection 实现 ICloneable 所以你可以这样做:

// Copies the appenders in the default repository
AppenderCollection copyAppenders = new AppenderCollection(LogManager.GetRepository().GetAppenders()).Clone() as AppenderCollection;

foreach (IAppender appender in copyAppenders)
{
    // Assuming we only have a RollingFileAppender
    RollingFileAppender file = appender as RollingFileAppender;
    file.Name = "FooBar";
    ...
    file.ActivateOptions();
}