简体   繁体   中英

Is there a way to hide the main file from log4net c#?

Is there a way to hide the main file used for log4net c#? When you use log4net, you set in the config file the path where to create the log file and to log there. The name of the file from the Path is where logging is happening and based on that I create a file each hour when I log something.

I can set the file to hidden but than I don't have access to it.

Can you please help me with a solution where I can still create log files each hour based on the config file, but the main File which is accessed by the process to be hidden? I have looked for something like this but I haven't found nothing.

Here is the code I use:

<appender name="ExampleLog" type="RollingFileAppender">
    <file value="Logs/Log.txt" />
    <appendToFile value="true" />
    <rollingStyle value="Composite" />
    <datePattern value="yyyyMMddHH" />
    <maxSizeRollBackups value="240" />
    <maximumFileSize value="20MB" />
    <CountDirection value="1" />
    <PreserveLogFileNameExtension value="true" />
    <layout type="log4net.Layout.PatternLayout">
      <conversionPattern value="%date{yyy/MM/dd    HH:mm:ss:fff} %message%newline" />
    </layout>
  </appender>

public override void OpenFile(string fileName, bool append)
{
      fileName = File;
      FileInfo fileInfo = new FileInfo(fileName);
      fileInfo.Attributes = FileAttributes.Hidden;
      base.OpenFile(fileName, append);
}

In short: place the current log file in a hidden subfolder and the rolled files in the root folder. No need to override the appender in the code.

Details: Your log4net config should look like this:

  <appender name="ExampleLog" type="log4net.Appender.RollingFileAppender">
    <file value="Log\\Current\\.log" />
    <appendToFile value="true" />
    <rollingStyle value="Composite" />
    <datePattern value="'..\\'yyyyMMddHH" />
    <maxSizeRollBackups value="240" />
    <maximumFileSize value="20MB" />
    <CountDirection value="1" />
    <PreserveLogFileNameExtension value="true" />
    <layout type="log4net.Layout.PatternLayout">
      <conversionPattern value="%date{yyy/MM/dd    HH:mm:ss:fff} %message%newline" />
    </layout>
  </appender>

Note that file value doesn't have a filename and the dataPattern has a leading '..\\'. Also, PreserveLogFileNameExtension should be set to true.

You can create the subfolder (Current) and make it hidden once programmatically.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM