2008-11-21 8 views

Respuesta

39

This thread at the log4net Dashboard details an approach.

Para resumir un poco, es de esperar sin necesidad de digitalizar fuera demasiado código:

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 
+0

que he tomado este enfoque para una de mis montajes, en lugar de utilizar el enfoque de configuración XML. Mientras se genera el archivo, por alguna razón, los métodos relacionados con el registro ILog no escriben nada en los archivos. ¿Hay algún método para llamar para que el nuevo apilador tenga efecto? No he encontrado nada como esto, aún ... – Dave

+7

@Dave: tuve el mismo problema y lo resolví agregando 'l.Repository.Configured = true;' a 'AddAppender'. – Stephan

+0

@Stephan gracias, creo que eso es exactamente lo que tuve que hacer para que funcione también. :) – Dave

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!"); 
     } 
    } 
} 
+0

este funciona bien, por lo menos se requiere log4jNet dll version2.0. –

1

Espero que esta ayuda, se configura un simple registrador de la consola.

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(); 
} 
Cuestiones relacionadas