在log4net中以编程方式更改日志级别?

有没有办法以编程方式在log4net中设置日志级别? 我假设有一个属性可以让你这样做,但我似乎无法找到一个。

我想要做的是有一个可配置选项进入调试模式。 这将导致额外的记录。

我正在使用单独的log4net配置xml文件。 目前我提出的解决方案如下:

  1. 使用dom编辑日志文件,然后调用XMLConfigurator根据文件配置日志文件。

  2. 有两个日志配置文件,并在选项更改调用xml Configurator上使用相应的日志配置文件。

我倾向于2,有什么理由不行吗?

这是我以编程方式配置log4net的方式:

//declared as a class variable private static readonly ILog logger = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); PatternLayout layout = new PatternLayout(@"%date %-5level %message%newline"); RollingFileAppender appender = new RollingFileAppender(); appender.Layout = layout; appender.File = "c:\log.txt"; appender.AppendToFile = true; appender.MaximumFileSize = "1MB"; appender.MaxSizeRollBackups = 0; //no backup files appender.Threshold = Level.Error; appender.ActivateOptions(); log4net.Config.BasicConfigurator.Configure(appender); 

我认为Appender的Threshold属性是你要找的,它将控制appender将输出的日志记录级别。

log4net 手册有很多很好的配置示例。

您可以以编程方式更改log4net记录器的日志记录级别,但是如何执行此操作并不明显。 我有一些代码可以做到这一点。 鉴于此记录器:

 private readonly log4net.ILog mylogger; 

您必须执行以下花哨的步法将其设置为Debug:

 ((log4net.Repository.Hierarchy.Logger)mylogger.Logger).Level = log4net.Core.Level.Debug; 

这是对米奇回答你的评论的后续行动。

虽然您可以设置programmaticaly级别,但为什么不设置日志级别进行调试? 这样,您的用户就不必担心将日志级别设置为调试,相信我,在您需要时永远不会打开。

然后,当发生错误时,只需让用户向您发送完整的日志文件,并使用像Apache Chainsaw这样的日志查看器来有选择地仅查看您想要查看的级别。

另一种解决方案是将不同级别记录到单独的文件中。 这样,您可以让用户仅向您发送您想要查看的级别。

您可以从此处下载示例项目或复制粘贴下面的代码。 在代码的最后是保存日志信息的表的DDL SQL。

  using System; using System.Collections.Generic; using System.Text; using log4net; using log4net.Config; using NUnit.Framework; using GenApp.Utils; namespace ExampleConsoleApplication { class TestClass { private static readonly ILog logger = LogManager.GetLogger ( typeof ( TestClass ) ); static void Main ( string[] args ) { TestClass objTestClass = new TestClass (); //log4net.Appender.ColoredConsoleAppender.Colors.HighIntensity GenApp.Bo.UserSettings us = new GenApp.Bo.UserSettings (); GenApp.Bo.User userObj = new GenApp.Bo.User () { UserSettings = us }; userObj.UserSettings.LogLevel = 4; #region SetDynamicallyLogLevel Logger.Debug ( userObj, logger, " -- Debug msg -- " ); Logger.Info ( userObj, logger, " -- Info msg -- " ); Logger.Warn ( userObj, logger, " -- Warn msg -- " ); Logger.Error ( userObj, logger, " -- Error msg -- " ); Logger.Fatal ( userObj, logger, " -- Fatal msg -- " ); #endregion SetDynamicallyLogLevel #region RemoveDynamicallyAppenders Logger.SetThreshold ( "LogFileAppender", log4net.Core.Level.Off ); //and echo again Logger.Debug ( userObj, logger, " -- Debug msg -- " ); Logger.Info ( userObj, logger, " -- Info msg -- " ); Logger.Warn ( userObj, logger, " -- Warn msg -- " ); Logger.Error ( userObj, logger, " -- Error msg -- " ); Logger.Fatal ( userObj, logger, " -- Fatal msg -- " ); #endregion RemoveDynamicallyAppenders Console.WriteLine ( " END HIT A KEY TO EXIT " ); Console.ReadLine (); } //eof method } //eof class } //eof namespace /* App.config CopyPaste    
*/ #region TheReferencesInThecsprojFile // // False // ..\..\..\Log4Net\log4net-1.2.10\bin\net\2.0\release\log4net.dll // // #endregion TheReferencesInThecsprojFile namespace GenApp.Bo { public class User { public int LogLevel { get; set; } public UserSettings UserSettings { get; set; } } //eof class public class UserSettings { public int LogLevel; } } //eof namespace namespace GenApp.Utils { /// 1.1 /// Yordan Georgiev /// Wrapper around log4net with dynamically adjustable verbosity public class Logger { private static Logger inst = new Logger (); public static Logger Inst () { inst.ConfigureLogging (); return inst; } public enum DebugLevel : int { Fatal_Msgs = 0, Fatal_Error_Msgs = 1, Fatal_Error_Warn_Msgs = 2, Fatal_Error_Warn_Info_Msgs = 3, Fatal_Error_Warn_Info_Debug_Msgs = 4 } public static void Debug ( GenApp.Bo.User userObj, ILog logger, string msg ) { DebugLevel debugLevel = (DebugLevel)userObj.UserSettings.LogLevel; string strLogLevel = Logger.GetLogTypeString ( debugLevel ); inst.SetLogingLevel ( strLogLevel ); logger.Debug ( msg ); } //eof method public static void Info ( GenApp.Bo.User userObj, ILog logger, string msg ) { DebugLevel debugLevel = (DebugLevel)userObj.UserSettings.LogLevel; string strLogLevel = Logger.GetLogTypeString ( debugLevel ); inst.SetLogingLevel ( strLogLevel ); logger.Info ( msg ); } //eof method public static void Warn ( GenApp.Bo.User userObj, ILog logger, string msg ) { DebugLevel debugLevel = (DebugLevel)userObj.UserSettings.LogLevel; string strLogLevel = Logger.GetLogTypeString ( debugLevel ); inst.SetLogingLevel ( strLogLevel ); logger.Warn ( msg ); } //eof method public static void Error ( GenApp.Bo.User userObj, ILog logger, string msg ) { DebugLevel debugLevel = (DebugLevel)userObj.UserSettings.LogLevel; string strLogLevel = Logger.GetLogTypeString ( debugLevel ); inst.SetLogingLevel ( strLogLevel ); logger.Error ( msg ); } //eof method public static void Fatal ( GenApp.Bo.User userObj, ILog logger, string msg ) { DebugLevel debugLevel = (DebugLevel)userObj.UserSettings.LogLevel; string strLogLevel = Logger.GetLogTypeString ( debugLevel ); inst.SetLogingLevel ( strLogLevel ); logger.Fatal ( msg ); } //eof method /// /// Activates debug level /// /// http://geekswithblogs.net/rakker/archive/2007/08/22/114900.aspx private void SetLogingLevel ( string strLogLevel ) { this.ConfigureLogging (); string strChecker = "WARN_INFO_DEBUG_ERROR_FATAL"; if (String.IsNullOrEmpty ( strLogLevel ) == true || strChecker.Contains ( strLogLevel ) == false) throw new ArgumentOutOfRangeException ( " The strLogLevel should be set to WARN , INFO , DEBUG ," ); log4net.Repository.ILoggerRepository[] repositories = log4net.LogManager.GetAllRepositories (); //Configure all loggers to be at the debug level. foreach (log4net.Repository.ILoggerRepository repository in repositories) { repository.Threshold = repository.LevelMap[strLogLevel]; log4net.Repository.Hierarchy.Hierarchy hier = (log4net.Repository.Hierarchy.Hierarchy)repository; log4net.Core.ILogger[] loggers = hier.GetCurrentLoggers (); foreach (log4net.Core.ILogger logger in loggers) { ( (log4net.Repository.Hierarchy.Logger)logger ).Level = hier.LevelMap[strLogLevel]; } } //Configure the root logger. log4net.Repository.Hierarchy.Hierarchy h = (log4net.Repository.Hierarchy.Hierarchy)log4net.LogManager.GetRepository (); log4net.Repository.Hierarchy.Logger rootLogger = h.Root; rootLogger.Level = h.LevelMap[strLogLevel]; } /// ///0 -- prints only FATAL messages ///1 -- prints FATAL and ERROR messages ///2 -- prints FATAL , ERROR and WARN messages ///3 -- prints FATAL , ERROR , WARN and INFO messages ///4 -- prints FATAL , ERROR , WARN , INFO and DEBUG messages /// private static string GetLogTypeString ( DebugLevel debugLevel ) { string srtLogLevel = String.Empty; switch (debugLevel) { case DebugLevel.Fatal_Msgs: srtLogLevel = "FATAL"; break; case DebugLevel.Fatal_Error_Msgs: srtLogLevel = "ERROR"; break; case DebugLevel.Fatal_Error_Warn_Msgs: srtLogLevel = "WARN"; break; case DebugLevel.Fatal_Error_Warn_Info_Msgs: srtLogLevel = "INFO"; break; case DebugLevel.Fatal_Error_Warn_Info_Debug_Msgs: srtLogLevel = "DEBUG"; break; default: srtLogLevel = "FATAL"; break; } //eof switch return srtLogLevel; } //eof GetLogTypeString /// /// The path where the configuration is read from. /// This value is set upon a call to ConfigureLogging(). /// private string configurationFilePath; public void ConfigureLogging () { lock (this) { bool configured = false; #region ConfigureByThePathOfTheEntryAssembly // Tells the logging system the correct path. Assembly a = Assembly.GetEntryAssembly (); if (a != null && a.Location != null) { string path = a.Location + ".config"; if (File.Exists ( path )) { log4net.Config.DOMConfigurator.Configure ( new FileInfo ( path ) ); configurationFilePath = path; configured = true; } else { path = FindConfigInPath ( Path.GetDirectoryName ( a.Location ) ); if (File.Exists ( path )) { log4net.Config.DOMConfigurator.Configure ( new FileInfo ( path ) ); configurationFilePath = path; configured = true; } } } #endregion ConfigureByThePathOfTheEntryAssembly #region ConfigureByWeb.config //// Also, try web.config. //if (!configured) //{ // if (HttpContext.Current != null && // HttpContext.Current.Server != null && // HttpContext.Current.Request != null) // { // string path = HttpContext.Current.Server.MapPath ( // HttpContext.Current.Request.ApplicationPath ); // path = path.TrimEnd ( '\\' ) + "\\Web.config"; // if (File.Exists ( path )) // { // log4net.Config.DOMConfigurator.Configure ( // new FileInfo ( path ) ); // configurationFilePath = path; // configured = true; // } // } //} #endregion ConfigureByWeb.config #region ConfigureByThePathOfTheExecutingAssembly if (!configured) { // Tells the logging system the correct path. a = Assembly.GetExecutingAssembly (); if (a != null && a.Location != null) { string path = a.Location + ".config"; if (File.Exists ( path )) { log4net.Config.DOMConfigurator.Configure ( new FileInfo ( path ) ); configurationFilePath = path; configured = true; } else { path = FindConfigInPath ( Path.GetDirectoryName ( a.Location ) ); if (File.Exists ( path )) { log4net.Config.DOMConfigurator.Configure ( new FileInfo ( path ) ); configurationFilePath = path; configured = true; } } } } #endregion ConfigureByThePathOfTheExecutingAssembly #region ConfigureByThePathOfTheCallingAssembly if (!configured) { // Tells the logging system the correct path. a = Assembly.GetCallingAssembly (); if (a != null && a.Location != null) { string path = a.Location + ".config"; if (File.Exists ( path )) { log4net.Config.DOMConfigurator.Configure ( new FileInfo ( path ) ); configurationFilePath = path; configured = true; } else { path = FindConfigInPath ( Path.GetDirectoryName ( a.Location ) ); if (File.Exists ( path )) { log4net.Config.DOMConfigurator.Configure ( new FileInfo ( path ) ); configurationFilePath = path; configured = true; } } } } #endregion ConfigureByThePathOfTheCallingAssembly #region ConfigureByThePathOfTheLibIsStored if (!configured) { // Look in the path where this library is stored. a = Assembly.GetAssembly ( typeof ( Logger ) ); if (a != null && a.Location != null) { string path = FindConfigInPath ( Path.GetDirectoryName ( a.Location ) ); if (File.Exists ( path )) { log4net.Config.DOMConfigurator.Configure ( new FileInfo ( path ) ); configurationFilePath = path; configured = true; } } } #endregion ConfigureByThePathOfTheLibIsStored } //eof lock } //eof method /// /// Searches for a configuration file in the given path. /// private string FindConfigInPath ( string path ) { string[] files = Directory.GetFiles ( path ); if (files != null && files.Length > 0) { foreach (string file in files) { if (Path.GetExtension ( file ).Trim ( '.' ).ToLower ( CultureInfo.CurrentCulture ) == "config") { return file; } } } // Not found. return string.Empty; } //eof method /// /// Remove dynamically appenders /// /// /// public static void SetThreshold ( string appenderName, Level threshold ) { foreach (AppenderSkeleton appender in LogManager.GetRepository ().GetAppenders ()) { if (appender.Name == appenderName) { appender.Threshold = threshold; appender.ActivateOptions (); break; } } } //eof method } //eof class } //eof namespace USE [DBGA_DEV] GO /****** Object: Table [ga].[tb_Data_Log] Script Date: 05/20/2009 12:16:01 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO SET ANSI_PADDING ON GO CREATE TABLE [ga].[tb_Data_Log]( [ID] [int] IDENTITY(1,1) NOT NULL, [Date] [datetime] NOT NULL, [Thread] [varchar](255) NOT NULL, [Level] [varchar](20) NOT NULL, [Logger] [varchar](255) NOT NULL, [Message] [varchar](4000) NOT NULL ) ON [PRIMARY] GO SET ANSI_PADDING ON GO