Log4Net:以编程方式指定多个记录器(具有多个文件追加器)

时间:2008-11-21 11:06:11

标签: c# log4net

如何(以编程方式,没有xml配置)使用Log4Net配置多个记录器? 我需要他们写入不同的文件。

4 个答案:

答案 0 :(得分:43)

This thread at the log4net Dashboard details an approach

总结一下,希望不要扯掉太多的代码:

using log4net;
using log4net.Appender;
using log4net.Layout;
using log4net.Repository.Hierarchy;

// Set the level for a named logger
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);
}

// Create a new file appender
public static IAppender CreateFileAppender(string name, string fileName)
{
    FileAppender appender = new
        FileAppender();
    appender.Name = name;
    appender.File = fileName;
    appender.AppendToFile = true;

    PatternLayout layout = new PatternLayout();
    layout.ConversionPattern = "%d [%t] %-5p %c [%x] - %m%n";
    layout.ActivateOptions();

    appender.Layout = layout;
    appender.ActivateOptions();

    return appender;
}

// 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", CreateFileAppender("appenderName", "fileName.log"));

// repeat as desired

答案 1 :(得分:3)

using System;
using Com.Foo;
using System.Collections.Generic;
using System.Text;
using log4net.Config;
using log4net;
using log4net.Appender;
using log4net.Layout;
using log4net.Repository.Hierarchy;


public class MyApp
{


    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);
    }
    // Add an appender to a logger
    public static void AddAppender2(ILog log, IAppender appender)
    {
       // ILog log = LogManager.GetLogger(loggerName);
        Logger l = (Logger)log.Logger;

        l.AddAppender(appender);
    }

    // Create a new file appender
    public static IAppender CreateFileAppender(string name, string fileName)
    {
        FileAppender appender = new
            FileAppender();
        appender.Name = name;
        appender.File = fileName;
        appender.AppendToFile = true;

        PatternLayout layout = new PatternLayout();
        layout.ConversionPattern = "%d [%t] %-5p %c [%logger] - %m%n";
        layout.ActivateOptions();

        appender.Layout = layout;
        appender.ActivateOptions();

        return appender;
    }

    private static readonly ILog log = LogManager.GetLogger(typeof(MyApp));
    static void Main(string[] args)
    {
        BasicConfigurator.Configure();
        SetLevel("Log4net.MainForm", "ALL");
        AddAppender2(log, CreateFileAppender("appenderName", "fileName.log"));
        log.Info("Entering application.");
        Console.WriteLine("starting.........");
        log.Info("Entering application.");
        Bar bar = new Bar();
        bar.DoIt();
        Console.WriteLine("starting.........");
        log.Error("Exiting application.");
        Console.WriteLine("starting.........");
    }
}


namespace Com.Foo
{
    public class Bar
    {
        private static readonly ILog log = LogManager.GetLogger(typeof(Bar));

        public void DoIt()
        {
            log.Debug("Did it again!");
        }
    }
}

答案 2 :(得分:1)

我希望这有帮助,它配置一个简单的控制台记录器。

static void Main(string[] args)
{
    const string logLayoutPattern =
        "[%date %timestamp][%level] %message %newline" +
        "Domain: %appdomain, User: %username %identity %newline" +
        "%stacktracedetail{10} %newline" +
        "%exception %newline";

    var wrapperLogger = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
    var logger = (Logger) wrapperLogger.Logger;
    logger.Hierarchy.Root.Level = Level.All;

    var consoleAppender = new ConsoleAppender
    {
        Name = "ConsoleAppender",
        Layout = new PatternLayout(logLayoutPattern)
    };

    logger.Hierarchy.Root.AddAppender(consoleAppender);
    logger.Hierarchy.Configured = true;

    wrapperLogger.Debug("Hello");
    Console.ReadKey();
}

答案 3 :(得分:0)

在这篇文章中,我将布莱尔·康拉德(Blair Conrad)的回答与菲利普·M(Philipp M)的代码混合在一起:

stackoverflow.com/questions/16336917/can-you-configure-log4net-in-code-instead-of-using-a-config-file

我将结果编译成我在项目中引用的dll,并通常这样在主程序的第一行中调用:

public static Log = new Log4NetWrapper.LogWrapper().Setup(@"c:\myLog.log", "TestLog");

这是DLL中的代码:

public class LogWrapper
    {
        public ILog Setup(string logFilePath, string logName, string maxFileSize = "10MB")
        {
            var patternLayout = new PatternLayout();
            patternLayout.ConversionPattern = "%date [%thread] %-5level %logger - %message%newline";
            patternLayout.ActivateOptions();

            var roller = new RollingFileAppender();
            roller.AppendToFile = true;
            roller.File = logFilePath;
            roller.Layout = patternLayout;
            roller.MaxSizeRollBackups = 5;
            roller.MaximumFileSize = maxFileSize;
            roller.RollingStyle = RollingFileAppender.RollingMode.Size;
            roller.StaticLogFileName = true;
            roller.ActivateOptions();
            //hierarchy.Root.AddAppender(roller);

            var memory = new MemoryAppender();
            memory.ActivateOptions();

            ILog log = LogManager.GetLogger(logName);
            var l = (Logger)log.Logger;
            l.AddAppender(roller);
            l.AddAppender(memory);

            l.Level = l.Hierarchy.LevelMap["Debug"];
            l.Repository.Configured = true;
            return log;
        }
    }

当然可以根据需要向构造函数添加参数或创建替代。