使用 Log4Net 创建只读日志文件并将日志单独记录在 2 个文件中

发布于 2024-10-19 03:20:41 字数 4068 浏览 3 评论 0原文

第一个问题是:

我正在用 C# 开发应用程序,该应用程序创建 2 个日志文件(.txt 文件):一个用于错误,另一个用于用户所做的修改。这两个文件是使用 log4net 创建的。我看到的问题是这些文件可以被编辑,因此会被错误地更改。

我想将这些文件设置为只读,并且 log4net 仍然可以写入它们。因为如果我只是更改文件中的属性,则不会写入下一个日志。

有办法做到这一点吗?

此外,应用程序的用户可以从应用程序内打开此日志文件。为此,我使用下一个代码:

System.IO.FileInfo finfo = new System.IO.FileInfo("path");
if (finfo.Exists)
{
 //finfo.Attributes = System.IO.FileAttributes.ReadOnly; 
 // I don't use the previous line at the moment, because it blocks the followings logs.
 System.Diagnostics.Process.Start("path");
}

这是创建和调用记录器的代码:

public static class CLogger
{
   private static readonly ILog logger = LogManager.GetLogger(typeof(CLogger));

   static CLogger()
   {
      XmlConfigurator.Configure(new System.IO.FileInfo("path to .config file"));
   }

   public static void WriteLog(ELogLevel logLevel, String log)
   {
      if (logLevel.Equals(ELogLevel.DEBUG))
      {
         logger.Debug(log);
      }
      else if (logLevel.Equals(ELogLevel.ERROR))
            .
            .
            .          
      else if (logLevel.Equals(ELogLevel.WARN))
      {
                logger.Warn(log);
      }
   }
}

调用记录器:

CLogger.WriteLog(ELogLevel.ERROR, ex.ToString());

我有一个相关的第二个问题

要创建这两个单独的日志文件,我使用.config 文件中的下几行:

<configuration>
  <configSections>
    <section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net" />
  </configSections>
  <log4net>
    <appender name="LogFileAppender" type="log4net.Appender.FileAppender">
      <param name="File" value="PATH...\ErrorLog.log" />
      <param name="AppendToFile" value="true" />
      <filter type="log4net.Filter.LevelRangeFilter">
        <param name="LevelMin" value="ERROR"/>
        <param name="LevelMax" value="ERROR"/>
      </filter>
      <layout type="log4net.Layout.PatternLayout">
        <param name="Header" value="" />
        <param name="Footer" value="" />
        <param name="ConversionPattern" value="%d [%t] %-5p %username %m%n" />
      </layout>
      <threshold value="ERROR" />
    </appender>
    <appender name="RollingFileAppender" type="log4net.Appender.RollingFileAppender">
      <file value="PATH...\TraceLog.log" />
      <appendToFile value="true" />
      <rollingStyle value="Size" />
      <maxSizeRollBackups value="10" />
      <maximumFileSize value="5MB" />
      <staticLogFileName value="true" />
      <filter type="log4net.Filter.LevelRangeFilter">
        <param name="LevelMin" value="INFO"/>
        <param name="LevelMax" value="INFO"/>
      </filter>
      <layout type="log4net.Layout.PatternLayout">
        <param name="Header" value="" />
        <param name="Footer" value="" />
        <param name="ConversionPattern" value="%d [%t] %-5p %username %m%n" />
      </layout>
      <threshold value="INFO" />
    </appender>
    <appender name="ConsoleAppender" type="log4net.Appender.ConsoleAppender" >
      <layout type="log4net.Layout.PatternLayout">
        <param name="Header" value="[Header]\r\n" />
        <param name="Footer" value="[Footer]\r\n" />
        <param name="ConversionPattern" value="%d [%t] %-5p %m%n" />
      </layout>
      <threshold value="ERROR" />
    </appender>
    <root>
      <level value="ERROR" />
      <appender-ref ref="LogFileAppender" />
      <appender-ref ref="ConsoleAppender" />
      <level value="INFO" />
      <appender-ref ref="RollingFileAppender" />
    </root>
  </log4net>
</configuration>

这可行,但我这样做好吗? 我怀疑是否应该使用“LogFileAppender”或“RollingFileAppender”,这就是我同时使用它们的原因。

提前致谢。

The first question is:

I'm developing application in c# that creates 2 log files (.txt files): one for errors and another for modifications made by users. This two files are created with log4net. The issue I see is that these files can be edited, and so altered by mistake.

I would like to set these files to readonly, and that log4net still could write to them. Because if I just change the property in the file, the next log won't be written.

Is there a way to do that?

Also, the user of the app can open this logs file from within the app. For that I use the next code:

System.IO.FileInfo finfo = new System.IO.FileInfo("path");
if (finfo.Exists)
{
 //finfo.Attributes = System.IO.FileAttributes.ReadOnly; 
 // I don't use the previous line at the moment, because it blocks the followings logs.
 System.Diagnostics.Process.Start("path");
}

And this is the code to create and call the logger:

public static class CLogger
{
   private static readonly ILog logger = LogManager.GetLogger(typeof(CLogger));

   static CLogger()
   {
      XmlConfigurator.Configure(new System.IO.FileInfo("path to .config file"));
   }

   public static void WriteLog(ELogLevel logLevel, String log)
   {
      if (logLevel.Equals(ELogLevel.DEBUG))
      {
         logger.Debug(log);
      }
      else if (logLevel.Equals(ELogLevel.ERROR))
            .
            .
            .          
      else if (logLevel.Equals(ELogLevel.WARN))
      {
                logger.Warn(log);
      }
   }
}

Calling to the logger:

CLogger.WriteLog(ELogLevel.ERROR, ex.ToString());

And I have a second question related:

To create this 2 separate log files I use the next lines in the .config file:

<configuration>
  <configSections>
    <section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net" />
  </configSections>
  <log4net>
    <appender name="LogFileAppender" type="log4net.Appender.FileAppender">
      <param name="File" value="PATH...\ErrorLog.log" />
      <param name="AppendToFile" value="true" />
      <filter type="log4net.Filter.LevelRangeFilter">
        <param name="LevelMin" value="ERROR"/>
        <param name="LevelMax" value="ERROR"/>
      </filter>
      <layout type="log4net.Layout.PatternLayout">
        <param name="Header" value="" />
        <param name="Footer" value="" />
        <param name="ConversionPattern" value="%d [%t] %-5p %username %m%n" />
      </layout>
      <threshold value="ERROR" />
    </appender>
    <appender name="RollingFileAppender" type="log4net.Appender.RollingFileAppender">
      <file value="PATH...\TraceLog.log" />
      <appendToFile value="true" />
      <rollingStyle value="Size" />
      <maxSizeRollBackups value="10" />
      <maximumFileSize value="5MB" />
      <staticLogFileName value="true" />
      <filter type="log4net.Filter.LevelRangeFilter">
        <param name="LevelMin" value="INFO"/>
        <param name="LevelMax" value="INFO"/>
      </filter>
      <layout type="log4net.Layout.PatternLayout">
        <param name="Header" value="" />
        <param name="Footer" value="" />
        <param name="ConversionPattern" value="%d [%t] %-5p %username %m%n" />
      </layout>
      <threshold value="INFO" />
    </appender>
    <appender name="ConsoleAppender" type="log4net.Appender.ConsoleAppender" >
      <layout type="log4net.Layout.PatternLayout">
        <param name="Header" value="[Header]\r\n" />
        <param name="Footer" value="[Footer]\r\n" />
        <param name="ConversionPattern" value="%d [%t] %-5p %m%n" />
      </layout>
      <threshold value="ERROR" />
    </appender>
    <root>
      <level value="ERROR" />
      <appender-ref ref="LogFileAppender" />
      <appender-ref ref="ConsoleAppender" />
      <level value="INFO" />
      <appender-ref ref="RollingFileAppender" />
    </root>
  </log4net>
</configuration>

That works, but am I doing that all right?
I have doubt whether I should use 'LogFileAppender' or 'RollingFileAppender', that's why I used them both.

Thanks in advance.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

梦明 2024-10-26 03:20:41

问题一:
我认为这是错误的处理方式。如果您担心他们会意外修改它,那么您有两种选择:

  • 制作日志文件的副本并显示该副本。
  • 在您控制的窗口中显示日志文件(即将文本区域设置为只读)。

问题2:
“普通”FileAppender 将始终写入同一个文件,这可能不是问题,因为您的应用程序偶尔会停止,并且您可以在日志文件变得太大时删除日志文件。对于长时间运行的应用程序,这不是一个选项:滚动的 RollingFileAppender 将每隔一段时间创建一个新文件(由特定大小或特定时间定义)。这样您就可以删除旧的日志文件并且永远不会耗尽磁盘空间。

也许您想在此处查看有关附加程序的更多信息。

Question 1:
I think that is the wrong way to approach it. If you fear they can modify it by accident, then you have two options:

  • Make a copy of the log file and display that one.
  • Display the log file in a window that you control (i.e. make the text area read-only).

Question 2:
The "normal" FileAppender will always write to the same file, this may not be an issue for your application is stopped once in a while and you can delete the log file when grows too large. For long running applications this is not an option: The rolling RollingFileAppender will create a new file every once a while (defined by certain size or certain time). This way you can delete old logfiles and never run out of disk space.

Maybe you want to check out more on appenders here.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文