Log4Net C#-按日期创建日志文件夹

本文关键字:日志 文件夹 创建 日期 C#- Log4Net | 更新日期: 2023-09-27 18:30:11

是否可以每天创建一个日志路径,以以下文件夹格式写入日志。

D:'Logs'yyyyMMdd'App1'App.txt

如果Log4Net不存在,它会创建路径吗?

我尝试了以下方法,但似乎不起作用。

 <appender name="RollingFileAppender" type="log4net.Appender.RollingFileAppender">
      <file value="D:'Logs'" />
      <appendToFile value="true" />
      <datePattern value="yyyyMMdd''App1'App.txt'" />
      <rollingStyle value="Date" />
      <layout type="log4net.Layout.PatternLayout">
        <conversionPattern value="%date{ABSOLUTE} [%logger] %level - %message%newline%exception" />
      </layout>
    </appender>

提前谢谢。

Log4Net C#-按日期创建日志文件夹

您可以介绍自己的appender:

    namespace CustomLogging
    {
    public class CustomAppender : log4net.Appender.RollingFileAppender
      {
        protected override void OpenFile(string fileName, bool append)
        {
          string baseDirectory = Path.GetDirectoryName(fileName);
          string fileNameOnly = Path.GetFileName(fileName);
          string newDirectory = Path.Combine(baseDirectory, DateTime.Now.ToString("yyyyMMdd"));
          string newFileName = Path.Combine(newDirectory, fileNameOnly);
          base.OpenFile(newFileName, append);
        }
      }
}

然后

<appender name="CustomAppender" type="CustomLogging.CustomAppender">
  <file type="log4net.Util.PatternString" value="Logs'Client"/>
  <appendToFile value="true"/>
  <rollingStyle value="Composite"/>
  <datePattern value="-HHmmss"/>
  <maxSizeRollBackups value="40"/>
  <maximumFileSize value="1MB"/>
  <countDirection value="1"/>
  <encoding value="utf-8"/>
  <staticLogFileName value="false"/>
  <layout type="log4net.Layout.PatternLayout">
    <conversionPattern value="%date{HH:mm:ss.fff}|%-5level|%message%newline"/>
  </layout>
</appender>

尝试此解决方案,但仅限于XAML

<appender name="RollingLogFileAppender" type="log4net.Appender.RollingFileAppender">
      <lockingModel type="log4net.Appender.FileAppender+MinimalLock"/>
      <file value="logs'" />
      <datePattern value="dd.MM.yyyy'.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] %-5level %logger [%property{NDC}] - %message%newline" />
      </layout>
    </appender>