简体   繁体   中英

log4net delete file at runtime is it possible c#

Is it possible to delete a log at runtime? What I would like to do before the application starts is deleting all logs; if that is not possible I would like to clear all logs at runtime.

Any suggestion/code snippet?

Yes, is it possible to clear the log files. The log file will be created by starting the program, if it doesn't exist. To clear the files, look here: Clearing content of text file using C#

Yet another alternative is to use the processid in the log file name - then everytime you start the app, you get a new log file:

<appender name="LogFileAppender" type="log4net.Appender.RollingFileAppender, log4net">
  <file type="log4net.Util.PatternString" value="D:\Logs\MyApp.log-[%processid].txt"/>

It is not supported "out of the box" from log4net. However, you could using the RollingFileAppender and create a manual class/method to clean up/delete the log file. Please refer to this answer: https://stackoverflow.com/a/2916628/3016125

Instead of trying to delete the log file programmatically, I prefer to combine a RollingFlatFileWriter and a scheduled task that executes something like the following recurring daily: forfiles -p "C:\\path to logd" -s -m *.log -d -5 -c "cmd /c del @path"

The above delete any file ending in .log that is older than 5 days. This gives more than enough time to make sure there are copies of each day's log available in your backup archive.

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