C# 代码 手工 配置 Log4Net 2种方法

这个初始化要在 获取 ILog 接口的代码之前完成, 之后按通常方式使用 log4net 就行了.

不用携带 config 配置文件.

方法1:

        /// <summary>
        /// 使用文本记录异常日志
        /// </summary>
        /// <Author>Ryanding</Author>
        /// <date>2011-05-01</date>
        public void LoadFileAppender()
        {
            string currentPath = AppDomain.CurrentDomain.BaseDirectory;
            currentPath = Path.Combine(currentPath, @"Log");

            string txtLogPath = Path.Combine(currentPath, "ErrorLog.txt");

            log4net.Repository.Hierarchy.Hierarchy hier =
                (log4net.Repository.Hierarchy.Hierarchy)log4net.LogManager.GetRepository();

            if (hier != null)
            {
                FileAppender fileAppender = new FileAppender();
                fileAppender.Name = "LogFileAppender";
                fileAppender.File = txtLogPath;
                fileAppender.AppendToFile = true;

                PatternLayout patternLayout = new PatternLayout
                {
                    ConversionPattern =
                        "记录时间:%date 线程ID:[%thread] 日志级别:%-5level 出错类:%logger property:[%property{NDC}] - 错误描述:%message%newline"
                };
                patternLayout.ActivateOptions();
                fileAppender.Layout = patternLayout;

                //选择UTF8编码,确保中文不乱码。
                fileAppender.Encoding = Encoding.UTF8;

                fileAppender.ActivateOptions();
                BasicConfigurator.Configure(fileAppender);
            }
        }

 

方法2:

    static bool InitializeLogSystem()
    {
      // 通过配置文件偷来的配置项
      //<appender name="RollingLogFileAppender" type="log4net.Appender.RollingFileAppender">
      //  <file value="Data/RollingLogFile.log" />
      //  <appendToFile value="true" />
      //  <maxSizeRollBackups value="3" />
      //  <maximumFileSize value="1MB" />
      //  <rollingStyle value="Size" />
      //  <staticLogFileName value="true" />
      //  <layout type="log4net.Layout.PatternLayout">
      //    <conversionPattern value="%date [%thread] %-5level %logger [%property{url}] - %message%newline" />
      //  </layout>
      //</appender>
      log4net.Appender.RollingFileAppender appender = new log4net.Appender.RollingFileAppender();
      // winform 的取路径方式呢
      appender.File = System.IO.Path.Combine(Application.StartupPath, "RollingLogFile.log");
      appender.AppendToFile = true;
      appender.MaxSizeRollBackups = 3;
      appender.MaximumFileSize = "1MB";
      appender.RollingStyle = log4net.Appender.RollingFileAppender.RollingMode.Size;
      appender.StaticLogFileName = true;
      appender.Layout = new log4net.Layout.PatternLayout("%date [%thread] %-5level - %message%newline");
      appender.ActivateOptions();// 这个要调用一下呢
      log4net.Config.BasicConfigurator.Configure(appender);
      return true;
    }

 

C# 代码 手工 配置 Log4Net 2种方法

上一篇:C# 反射 设置实体属性


下一篇:C#获取程序路径