Linux 如何使用 logrotate 在文件名中插入日期

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9555769/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-06 04:59:38  来源:igfitidea点击:

How to insert a date inside the filename with logrotate

linuxlogrotate

提问by Bernard Sfez

I need to set logrotate to rotate logs files from an application running on the server. I need the date inside the filename.

我需要设置 logrotate 以从服务器上运行的应用程序中旋转日志文件。我需要文件名中的日期。

I set dateext and also dateformat to add a - in the date. The result filename is:whatever.csv_2012-03-03

我设置了 dateext 和 dateformat 以在日期中添加 - 。结果文件名是:whatever.csv_2012-03-03

I would like the timestamp to be part of the filename keeping safe the extension; Whatever_2012-03-03.csv.

我希望时间戳成为文件名的一部分,以确保扩展名的安全;随便_2012-03-03.csv。

采纳答案by Bernard Sfez

To insert the date within the filename (and not as extension) of a file under Linux while rotating a file it is correct to use:

要在 Linux 下的文件的文件名(而不是作为扩展名)中插入日期,同时旋转文件,正确使用:

# Daily rotation
    daily

# We keep original file live
    copytruncate

# Rotation is 1 so we have always .1 as extension
    rotate 1

# If file is missing keep working
    missingok

    sharedscripts
    postrotate
            day=$(date +%Y-%m-%d)
            mv blabla.csv.1 /var/www/gamelogs/dir/blabla$day.csv
    endscript
}

This is simple and works fine.

这很简单并且工作正常。

回答by Stéphane

You should be able to keep the extension apart, e.g. whatever.2012-03-03.csv, with the following configuration:

您应该能够将扩展分开,例如whatever.2012-03-03.csv,使用以下配置:

whatever.csv {
  dateext
  dateformat .%Y-%m-%d
  extension .csv
  ...
}

Note the dateextis deliberately empty.

注意dateext是故意空的。