2

I'm working with a system where I would like to use the dateext function of logrotate (or some other way) to add the date to a logfile when it is rotated. However in this system it is important that no logging is missing and dateext will overwrite any existing files (which will happen if logrotate is called twice on a day).

Is there a reliable way to prevent dateext to overwrite existing files, but instead make another file?. It is acceptable that either no rotate happens or a file is created with a less predictable name (date with an extra number, or the time or something).

Thirler
  • 156
  • 1
  • 5

2 Answers2

4

dateext supports the %s format specifier - the Unix epoch time in seconds.

If you set the dateformat as .%Y-%m-%d.%s, it will look like this:

logfilename.2012-12-11.13572638495

This changes every second, so the chances of two identical files are very remote.

adaptr
  • 16,479
  • 21
  • 33
  • 1
    Absolutely good enough for most people - logrotate is normally invoked via a crontab, so it'll be firing once per minute at most. Besides, I have my logrotate set up to rotate logs every gigabyte, and if that's happening more than once per second, *I have a problem*. :) – Mark Amery Oct 23 '14 at 10:12
0

You could use prerotate/endscript to make sure that there is no file with the name you are about to use, but if you are concerned with rotations happening at any odd time this could be tricky. The worst case is you have two rotates of the same file running at the same time (2nd started before 1st completed), and if both determine that there is no name conflict, then one will overwrite another.

An easier approach could be changing the rotated file name to include more exact date, e.g. including nanoseconds in the timestamp. This should make it very unlikely for names to conflict. If you want to be sure that there's no name conflict use mktemp, but then you will get "ugly" names. Logic of such name change should go to prerotate|postrotate/endscript section of logrotate config.

Paweł Brodacki
  • 6,451
  • 19
  • 23