1

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?

samy
  • 14,832
  • 2
  • 54
  • 82
developer9969
  • 4,628
  • 6
  • 40
  • 88
  • I suppose you could use a rolling file appender and have a separate process which deletes the old files. Logging libraries don't generally *delete* logs, they create them. What are you actually trying to accomplish and why? – David May 16 '15 at 13:38
  • I have a tool that perform certain operation and having a clean log whenever I start a process would help to see what's going. I know there is a timestamp etc.. but I would like to have a clean or delete the log if exists – developer9969 May 16 '15 at 14:27
  • see this http://stackoverflow.com/questions/95286/log4net-set-max-backup-files-on-rollingfileappender-with-rolling-date – Chris McKelt May 19 '15 at 14:16

4 Answers4

2

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#

Community
  • 1
  • 1
Thomas
  • 113
  • 1
  • 11
  • Hi thanks for your time and answer but that does not work."The process cannot access the file because is being used by another process" I suppose that when I start the application log4net must lock the file. – developer9969 May 16 '15 at 14:35
  • do you have write access? – Thomas May 16 '15 at 14:48
2

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"/>
freedomn-m
  • 27,664
  • 8
  • 35
  • 57
  • If you're getting %processid as a literal in your file name, be sure to add the **type="log4net.Util.PatternString"** value. – Jazimov Dec 11 '16 at 18:15
0

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

Community
  • 1
  • 1
Manoj Pedvi
  • 169
  • 8
  • 15
0

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.

Sean O'Brien
  • 183
  • 7