log4net: different logs on different file appenders at runtime

后端 未结 2 1006
时光说笑
时光说笑 2021-02-15 02:52

Good morning guys.

I wrote a single istance C# 2.0 app (call it myapp).
Myapp is called many times, and at every call generates a sort of \"task\" that will

2条回答
  •  梦如初夏
    2021-02-15 03:29

    I've done something similar, where I needed a different log for every instance of a class. You can create logs dynamically with a few steps.

    It looks like a default Logger (Line 97) is already defined, but it's internal to their assembly, so it will need to be inherited (as far as I know).

    public sealed class DynamicLogger : Logger 
    { 
        internal DynamicLogger(string name) : base(name) 
        { 
            base.Hierarchy = (log4net.Repository.Hierarchy.Hierarchy)LogManager.GetRepository();
        } 
    }
    

    Sample method to retrieve an ILog:

    public static ILog GetSample(string arg)
    {
        var logger = new DynamicLogger(arg);
        logger.Level = Level.All;
    
        var consoleAppender = new ConsoleAppender();
        consoleAppender.Name = arg;
        consoleAppender.Layout = new PatternLayout(arg + ": %m%newline");
        logger.AddAppender(consoleAppender);
    
        var newLog = new LogImpl(logger);
        if (_logs.Any(log => log.Logger.Name == newLog.Logger.Name) == false)
            _logs.Add(newLog);
    
        return newLog;
    }
    

    Basic usage:

    var foo = DynamicLog.GetSample("foo");
    var bar = DynamicLog.GetSample("bar");
    foo.Error("Test");
    bar.Error("Test");
    

    For your scenario, look at creating a RollingFileAppender, and look at the available properties on the object, since this was just an example.

    EDIT: Added the below for storing ILog's, and modified the original GetSample method above.

    Add an array of ILog's and a GetLogger method:

    private static List _logs = new List();
    
    public static ILog GetLogger(string name)
    {
        return _logs.SingleOrDefault(a => a.Logger.Name == name);
    }
    

    Sample usage:

    DynamicLog.GetSample("foo");
    var foo = DynamicLog.GetLogger("foo");
    

提交回复
热议问题