log4net更换目录

 public static void ChangeRollingFileName()
        {
            // ログファイル
            log4net.ILog iLog = log4net.LogManager.GetLogger("AppLogger");
            // パス
            string strPath = Environment.GetEnvironmentVariables()["USERPROFILE"].ToString() + "\\log\\";
            string strFilename = strPath + "log.txt";
            // 文件夹生成
            if (!Directory.Exists(strPath))
            {
                Directory.CreateDirectory(strPath);
            }
            log4net.Core.LogImpl logImpl = iLog as log4net.Core.LogImpl;
            if (logImpl != null)
            {
                log4net.Appender.AppenderCollection ac = ((log4net.Repository.Hierarchy.Logger)logImpl.Logger).Appenders;
                for (int i = 0; i < ac.Count; i++)
                {  
                    //
                    log4net.Appender.FileAppender rfa = ac[i] as log4net.Appender.FileAppender;
                    if (rfa != null)
                    {
                        rfa.File = strFilename;
                        // 写文件
                        rfa.Writer = new System.IO.StreamWriter(rfa.File, rfa.AppendToFile, rfa.Encoding);
                    }
                }
            }

如何调用:===================================================================
调用class
public static readonly log4net.ILog log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
 
private void TestChangeLog4netLogFileName()
        {
            ChangeLog4netLogFileName();
            iLog.Info("Test:info");
        }
 
configue 的配置===================================================================
<configuration>
  <log4net>
    <!-- Define some output appenders -->
    <appender name="LogFileAppender" type="log4net.Appender.FileAppender">
      <param name="File" value="ClientLog.txt"/>
      <param name="AppendToFile" value="true"/>
      <param name="MaxSizeRollBackups" value="10"/>
      <param name="MaximumFileSize" value="5MB"/>
      <param name="RollingStyle" value="Size"/>
      <param name="StaticLogFileName" value="true"/>
      <layout type="log4net.Layout.PatternLayout">
        <param name="ConversionPattern" value="%d{yyyy-MM-dd HH:mm:ss} %u %-5p [%class][%method] - %m%n"/>
      </layout>
     
      <!-- Alternate layout using XML    
    <layout type="log4net.Layout.XMLLayout" /> -->
    </appender>
    <!-- Setup the root category, add the appenders and set the default level -->
    <root>
      <level value="ALL" />
      <appender-ref ref="LogFileAppender" />
      <!-- <appender-ref ref="A" /> -->
    </root>
    <logger name="AppLogger">
      <level value="ALL" />
      <appender-ref ref="LogFileAppender" />
    </logger>
    <logger name="Form1">
      <level value="DEBUG" />
      <appender-ref ref="LogFileAppender" />
    </logger>

  </log4net>
</configuration>
 
posted @ 2012-10-25 14:52  小毛驴  阅读(375)  评论(0编辑  收藏  举报