0

This might be simple, but I can't find it anywhere. How do I clear the contents of the log file using NLog? I have created the Logger object and can successfully write messages to it, but now I want to programmatically delete the contents of the file, or maybe all contents before a particular date/time. How do I do that?

Note that I'm NOT doing any kind of archiving (log files with timestamped file names). There is only one log file and messages inside that file are timestamped, so I need programmatic access to the file content to remove entries/clear entire file. Therefore the SO posts which suggest using NLog config option to handle automatic archiving/deletion do not work in my case.

dotNET
  • 33,414
  • 24
  • 162
  • 251
  • Look at this: https://stackoverflow.com/questions/5565597/delete-log-files-after-x-days – PrakashG Jul 09 '19 at 10:44
  • @pGauR: Thanks, but that doesn't address the problem at hand. Please see my edit. – dotNET Jul 09 '19 at 11:56
  • 1
    You can use the FileTarget property `deleteOldFileOnStartup` and then just assign a new config to `LogManager.Configuration`. This will cause NLog to delete file on next write-operation after having assigned new config. See also https://github.com/nlog/NLog/wiki/File-target – Rolf Kristensen Jul 09 '19 at 18:24
  • @RolfKristensen: Thanks. What if I want to delete log entries up to a specific date/time programmatically? – dotNET Jul 09 '19 at 18:32
  • @dotNET NLog can only append to files, move files or delete files. If you want to NLog to handle your file-logic then to solve your problem with these operations. Maybe create an unique file for each session, and cleanup files from previous sessions. – Rolf Kristensen Jul 09 '19 at 18:36
  • @RolfKristensen: Sounds about right (and that's what I thought could be the case). I think I can manage by creating separate daily log files. Thanks for the input. – dotNET Jul 10 '19 at 01:14

1 Answers1

0

This feature isn't built in NLog.

Most of the time I will create separate files (e.g. per level and/or per day), and let NLog or a cleanup script cleaning those old files.

Julian
  • 33,915
  • 22
  • 119
  • 174