让log4net工作

时间:2016-01-22 20:55:20

标签: c# log4net log4net-configuration log4net-appender

我已经编写了一个使用记录器的包装器类,因为我之前从未使用过log4net(我在工作中使用log4c ++,但它已经配置好了,我从不需要弄乱它), 我不知道如何正确配置它并让它工作......

这是包装类的当前源代码:

using System.Text;
using log4net;
using log4net.Appender;
using log4net.Config;
using log4net.Layout;

namespace GotLoggingService
{
    public sealed partial class LoggerManager
    {
        private ILog Logger { get; }

        #region Info Methods

        public void Info(string message)
        {
            Logger.Info(message);
        }

        public void InfoFormat(string format, params object[] args)
        {
            Logger.InfoFormat(format, args);
        }

        #endregion

        #region Debug Methods

        public void Debug(string message)
        {
            Logger.Debug(message);
        }

        public void DebugFormat(string format, params object[] args)
        {
            Logger.DebugFormat(format, args);
        }

        #endregion

        #region Warn Methods

        public void Warn(string message)
        {
            Logger.Warn(message);
        }

        public void WarnFormat(string format, params object[] args)
        {
            Logger.WarnFormat(format, args);
        }

        #endregion

        #region Error Methods

        public void Error(string message)
        {
            Logger.Error(message);
        }

        public void ErrorFormat(string format, params object[] args)
        {
            Logger.ErrorFormat(format, args);
        }

        #endregion

        #region Fatal Methods

        public void Fatal(string message)
        {
            Logger.Fatal(message);
        }

        public void FatalFormat(string format, params object[] args)
        {
            Logger.FatalFormat(format, args);
        }

        #endregion

        #region Getters

        public static LoggerManager GetLogger(string name)
        {
            return new LoggerManager(name);
        }

        public static LoggerManager GetLogger(string name, LoggerManager parent)
        {
            return new LoggerManager(name, parent);
        }

        public static LoggerManager GetRootLogger()
        {
            return RootLooger;
        }

        #endregion
    }

    // Manage stuff here
    public sealed partial class LoggerManager
    {
        private const string FORMAT = "%timestamp  %-5level %logger %ndc - %ndc %message%newline";

        // Initializes root logger
        private LoggerManager()
        {
            Logger = LogManager.GetLogger(ROOT_LOGGER_NAME);
            BasicConfigurator.Configure(new FileAppender
            {
                AppendToFile = true,
                Encoding = Encoding.UTF8,
                File = "C:/log.txt",
                ImmediateFlush = true,
                Layout = new PatternLayout(FORMAT)
            });
        }

        private LoggerManager(string name) : this(name, GetRootLogger())
        {
        }

        private LoggerManager(string name, LoggerManager parent)
        {
            Logger = GetILog(name, parent);
        }

        private const string ROOT_LOGGER_NAME = "root";

        private static readonly LoggerManager RootLooger = new LoggerManager();

        private static ILog GetILog(string name, LoggerManager parent)
        {
            return LogManager.GetLogger(GetLoggerName(name, parent.Logger.Logger.Name));
        }

        private static string GetLoggerName(string name, string parent = ROOT_LOGGER_NAME)
        {
            StringBuilder nameBuilder = new StringBuilder();
            nameBuilder.AppendFormat("{0}.{1}", LogManager.GetLogger(parent).Logger.Name, name);
            return nameBuilder.ToString();
        }
    }
}

正如您所看到的,我尝试使用BasicConfigurator进行配置,为其提供FileAppender。我已经尝试过记录东西而且它没有向文件中添加任何东西......这是我如何使用记录器包装器的简短示例:

using GotLoggingService;

namespace trythelog
{
    class LoggerTry
    {
        private LoggerManager logger;

        public static void Main(string[] args)
        {
            LoggerTry logger = new LoggerTry();
        }

        public LoggerTry()
        {
            logger = LoggerManager.GetLogger("some-logger");
            logger.Info("this is a log message");
        }
    }
}

这基本上就是我要说的所有...感谢您的阅读,如果您能指出我搞砸的东西,我想要它。

我现在使用App.Config而不是BasicConfigurator

这是app.config:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
    <startup> 
        <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5.2" />
    </startup>

  <configSections>
    <section name="log4net"
      type="log4net.Config.Log4NetConfigurationSectionHandler, log4net"/>
  </configSections>

  <log4net>
    <root>
      <level value="DEBUG"/>
      <appender-ref ref="RollingLogFileAppender"/>
      <appender-ref ref="ConsoleAppender"/>
    </root>

    <appender name="ConsoleAppender" type="log4net.Appender.ConsoleAppender">
      <layout type="log4net.Layout.PatternLayout">
        <conversionPattern value="%date %-5level %logger %ndc - %ndc %message%newline" />
      </layout>
    </appender>

    <appender name="RollingLogFileAppender" type="log4net.Appender.RollingFileAppender">
      <lockingModel type="log4net.Appender.FileAppender+MinimalLock" />
      <file value="logs/" />
      <datePattern value="yyyyMMdd'.log'" />
      <staticLogFileName value="false" />
      <appendToFile value="true" />
      <rollingStyle value="Composite" />
      <maxSizeRollBackups value="10" />
      <maximumFileSize value="5MB" />
      <layout type="log4net.Layout.PatternLayout">
        <conversionPattern value="%date %-5level %logger %ndc - %ndc %message%newline" />
      </layout>
    </appender>

  </log4net>
</configuration>

我尝试运行时遇到此异常:http://pastebin.com/qftQAHkn

ליו להיות הצאצא הראשון של אלמנט הבסיס <configuration>. (C:\GameOfThrowsUnityRepository\GameOfThrowsU
nity\GameOfThrowsServer\trythelog\bin\Debug\trythelog.exe.Config line 7)
   ב-  System.Configuration.ConfigurationSchemaErrors.ThrowIfErrors(Boolean ignoreLocal)
   ב-  System.Configuration.BaseConfigurationRecord.ThrowIfParseErrors(ConfigurationSchemaErrors sch
emaErrors)
   ב-  System.Configuration.BaseConfigurationRecord.ThrowIfInitErrors()
   ב-  System.Configuration.ClientConfigurationSystem.EnsureInit(String configKey)
   --- סוף רכיב מעקב אחר מחסנית של מצב חריג פנימי ---
   ב-  System.Configuration.ConfigurationManager.PrepareConfigSystem()
   ב-  System.Configuration.ConfigurationManager.get_AppSettings()
   ב-  log4net.Util.SystemInfo.GetAppSetting(String key) ב- c:\log4net\tags\1.2.15RC1\src\Util\Syste
mInfo.cs:שורה 954
log4net:ERROR Failed to parse config file. Is the <configSections> specified as: <section name="log4
net" type="log4net.Config.Log4NetConfigurationSectionHandler,log4net, Version=1.2.15.0, Culture=neut
ral, PublicKeyToken=669e0ddf0bb1aa2a" />
System.Configuration.ConfigurationErrorsException: אתחול מערכת התצורה נכשל. ---> System.Configuratio
n.ConfigurationErrorsException: אלמנט <configSections> אחד בלבד מותר לכל קובץ config ואם הוא קיים, ע
ליו להיות הצאצא הראשון של אלמנט הבסיס <configuration>. (C:\GameOfThrowsUnityRepository\GameOfThrowsU
nity\GameOfThrowsServer\trythelog\bin\Debug\trythelog.exe.Config line 7)
   ב-  System.Configuration.ConfigurationSchemaErrors.ThrowIfErrors(Boolean ignoreLocal)
   ב-  System.Configuration.BaseConfigurationRecord.ThrowIfParseErrors(ConfigurationSchemaErrors sch
emaErrors)
   ב-  System.Configuration.BaseConfigurationRecord.ThrowIfInitErrors()
   ב-  System.Configuration.ClientConfigurationSystem.EnsureInit(String configKey)
   --- סוף רכיב מעקב אחר מחסנית של מצב חריג פנימי ---
   ב-  System.Configuration.ConfigurationManager.PrepareConfigSystem()
   ב-  System.Configuration.ConfigurationManager.GetSection(String sectionName)
   ב-  log4net.Config.XmlConfigurator.InternalConfigure(ILoggerRepository repository) ב- c:\log4net\
tags\1.2.15RC1\src\Config\XmlConfigurator.cs:שורה 173
Press any key to continue . . .

抱歉希伯来语:x

2 个答案:

答案 0 :(得分:1)

尝试:

<强>代码

using log4net;
...

 static void Main(string[] args)
        {
            log4net.Config.XmlConfigurator.Configure(); // Missing!!?

            ILog log = LogManager.GetLogger("MyLogger");
            log.Info("message");

App.Config或Web.Config

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <configSections>   <!-- must be the first child -->
    <section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler,log4net" />
  </configSections>

   ...

  <log4net>
    <logger name="MyLogger">
      <level value="INFO" />
      <appender-ref ref="RollingLogFileAppender" />
    </logger>


    <appender name="RollingLogFileAppender" type="log4net.Appender.RollingFileAppender">
      <lockingModel type="log4net.Appender.FileAppender+MinimalLock" />
      <file value="logs/" /> <!--YOUR PATH-->
      <datePattern value="yyyyMMdd'.log'" />
      <staticLogFileName value="false" />
      <appendToFile value="true" />
      <rollingStyle value="Composite" />
      <maxSizeRollBackups value="10" />
      <maximumFileSize value="5MB" />
      <layout type="log4net.Layout.PatternLayout">
        <conversionPattern value="%date [%thread] %level %logger - %message%newline" />
      </layout>
    </appender>

  </log4net>


</configuration>

答案 1 :(得分:0)

就我而言,问题是由文件属性复制到输出目录引起的。它设置为不复制(并且适用于Web App)但是,对于控制台应用程序,它必须设置为始终复制

(在Visual Studio中使用F4键显示“属性”窗口)