基于logrotate的日志管理

1. 引言

每个系统都存在日志管理的问题,主要包含两项

  • 限制日志大小
  • 对日志进行滚动更新

本文主要描述怎么使用logrotate进行日志管理

2. 日志管理

2.1. logrotate下载安装

参考github说明

2.1.1. 通过git下载代码
git clone https://github.com/logrotate/logrotate.git -b master
2.1.2. 通过wget下载

进入 tags 选择版本

然后选择.tar.gz下载,如当前版本3.19.0

wget https://github.com/logrotate/logrotate/releases/download/3.19.0/logrotate-3.19.0.tar.gz
2.1.2. 解压和编译

解压

tar -xvzf logrotate-3.19.0.tar.gz

编译

yum install autoconf automake libtool make popt-devel xz
cd logrotate-3.19.0
autoreconf -fiv
./configure
make

执行程序会生成在当前目录

也可以运行make install 默认安装到/usr/local/bin

2.2. 使用示例

2.2.1 通用日志管理

测试配置文件:

/tmp/1.log {
	su root root
	copytruncate
	size 100K
	rotate 5
}

每次执行./logrotate -v logrotate.conf时当日志大于100K时进行拆分,拷贝一份当前日志,然后将原来的日志文件清空,最多保留5个日志,加上正在写的为6个

$ ll /tmp/
total 3908
-rw-r--r--. 1 root root  110677 May 25 08:42 1.log
-rw-r--r--. 1 root root  522227 May 25 08:42 1.log.1
-rw-r--r--. 1 root root  521084 May 25 08:41 1.log.2
-rw-r--r--. 1 root root  519026 May 25 08:40 1.log.3
-rw-r--r--. 1 root root  522518 May 25 08:39 1.log.4
-rw-r--r--. 1 root root  523197 May 25 08:38 1.log.5

可放到定时任务中执行:

$ crontab -l
* * * * * /home/logrotate/logrotate /home/logrotate/logrotate.conf
2.2.2. 自研程序日志管理

自研程序可通过发送信号的方式,感应到需要切换日志文件进行写入

通过create配置,在处理完日志轮转后,发送一个信号给写入日志的程序,通知其写入程序到新的日志文件中

/tmp/1.log {
	su root root
	size 100K
	create
	rotate 5
	{
        postrotate
            /bin/kill -SIGUSR2 `cat /var/run/test.pid 2> /dev/null` 2> /dev/null || true
        endscript
    }
}

**注:**更多参数和使用方法请查看第4章节

2.3. 日志轮转处理逻辑

2.3.1. create原理

日志轮转时的处理逻辑:

  • 将test.log重命名为test.log.1
  • 创建一个新的test.log文件

在这里插入图片描述

2.3.2. copytruncate原理
  • 将test.log拷贝一份为test.log.1
  • 将test.log清空

在这里插入图片描述

2.3.3. 源码分析

参考代码

rotateSingleLog函数,轮转单个日志文件:

static int rotateSingleLog(const struct logInfo *log, unsigned logNum,
                           struct logState *state, struct logNames *rotNames)
{
    int hasErrors = 0;
    struct stat sb;
    char *savedContext = NULL;

    if (!state->doRotate)
        return 0;

    if (!hasErrors) {
		// create 方式处理:步骤1:重命名文件
        if (!(log->flags & (LOG_FLAG_COPYTRUNCATE | LOG_FLAG_COPY))) {
            if (setSecCtxByName(log->files[logNum], log, &savedContext) != 0) {
                /* error msg already printed */
                return 1;
            }
#ifdef WITH_ACL
            if ((prev_acl = acl_get_file(log->files[logNum], ACL_TYPE_ACCESS)) == NULL) {
                if (is_acl_well_supported(errno)) {
                    message(MESS_ERROR, "getting file ACL %s: %s\n",
                            log->files[logNum], strerror(errno));
                    hasErrors = 1;
                }
            }
#endif /* WITH_ACL */
            if (log->flags & LOG_FLAG_TMPFILENAME) {
                char *tmpFilename;

                if (asprintf(&tmpFilename, "%s%s", log->files[logNum], ".tmp") < 0) {
                    message_OOM();
                    restoreSecCtx(&savedContext);
                    return 1;
                }

                message(MESS_DEBUG, "renaming %s to %s\n", log->files[logNum],
                        tmpFilename);
                if (!debug && !hasErrors && rename(log->files[logNum], tmpFilename)) {
                    message(MESS_ERROR, "failed to rename %s to %s: %s\n",
                            log->files[logNum], tmpFilename,
                            strerror(errno));
                    hasErrors = 1;
                }

                free(tmpFilename);
            }
            else {
                message(MESS_DEBUG, "renaming %s to %s\n", log->files[logNum],
                        rotNames->finalName);
                if (!debug && !hasErrors &&
                        rename(log->files[logNum], rotNames->finalName)) {
                    message(MESS_ERROR, "failed to rename %s to %s: %s\n",
                            log->files[logNum], rotNames->finalName,
                            strerror(errno));
                    hasErrors = 1;
                }
            }

            if (!log->rotateCount) {
                const char *ext = "";
                if (log->compress_ext
                        && (log->flags & LOG_FLAG_COMPRESS)
                        && !(log->flags & LOG_FLAG_DELAYCOMPRESS))
                    ext = log->compress_ext;

                free(rotNames->disposeName);
                if (asprintf(&rotNames->disposeName, "%s%s", rotNames->finalName, ext) < 0) {
                    message_OOM();
                    rotNames->disposeName = NULL;
                    return 1;
                }

                message(MESS_DEBUG, "disposeName will be %s\n", rotNames->disposeName);
            }
        }
		// create 方式处理:步骤2:创建一个新文件
        if (!hasErrors && (log->flags & LOG_FLAG_CREATE) &&
                !(log->flags & (LOG_FLAG_COPYTRUNCATE | LOG_FLAG_COPY))) {
            int have_create_mode = 0;

            if (log->createUid == NO_UID)
                sb.st_uid = state->sb.st_uid;
            else
                sb.st_uid = log->createUid;

            if (log->createGid == NO_GID)
                sb.st_gid = state->sb.st_gid;
            else
                sb.st_gid = log->createGid;
            if (log->createMode == NO_MODE)
                sb.st_mode = state->sb.st_mode & 0777;
            else {
                sb.st_mode = log->createMode;
                have_create_mode = 1;
            }

            message(MESS_DEBUG, "creating new %s mode = 0%o uid = %d "
                    "gid = %d\n", log->files[logNum], (unsigned int) sb.st_mode,
                    (int) sb.st_uid, (int) sb.st_gid);

            if (!debug) {
                if (!hasErrors) {
                    int fd = createOutputFile(log->files[logNum], O_RDWR,
                            &sb, prev_acl, have_create_mode);
#ifdef WITH_ACL
                    if (prev_acl) {
                        acl_free(prev_acl);
                        prev_acl = NULL;
                    }
#endif
                    if (fd < 0)
                        hasErrors = 1;
                    else {
                        close(fd);
                    }
                }
            }
        }

        restoreSecCtx(&savedContext);
		// copytruncate 处理方式,调用copyTruncate函数
        if (!hasErrors
                && (log->flags & (LOG_FLAG_COPYTRUNCATE | LOG_FLAG_COPY))
                && !(log->flags & LOG_FLAG_TMPFILENAME)) {
            hasErrors = copyTruncate(log->files[logNum], rotNames->finalName,
                                     &state->sb, log, !log->rotateCount);
        }

#ifdef WITH_ACL
        if (prev_acl) {
            acl_free(prev_acl);
            prev_acl = NULL;
        }
#endif /* WITH_ACL */

    }
    return hasErrors;
}

copyTruncate函数,拷贝和清空文件:

static int copyTruncate(const char *currLog, const char *saveLog, const struct stat *sb,
                        const struct logInfo *log, int skip_copy)
{
    int rc = 1;
    int fdcurr = -1, fdsave = -1;

    message(MESS_DEBUG, "copying %s to %s\n", currLog, saveLog);

    if (!debug) {
        /* read access is sufficient for 'copy' but not for 'copytruncate' */
        const int read_only = (log->flags & LOG_FLAG_COPY)
            && !(log->flags & LOG_FLAG_COPYTRUNCATE);
        if ((fdcurr = open_logfile(currLog, log, !read_only)) < 0) {
            message(MESS_ERROR, "error opening %s: %s\n", currLog,
                    strerror(errno));
            goto fail;
        }

        if (!skip_copy) {
            char *prevCtx;

            if (setSecCtx(fdcurr, currLog, &prevCtx) != 0) {
                /* error msg already printed */
                goto fail;
            }
#ifdef WITH_ACL
            if ((prev_acl = acl_get_fd(fdcurr)) == NULL) {
                if (is_acl_well_supported(errno)) {
                    message(MESS_ERROR, "getting file ACL %s: %s\n",
                            currLog, strerror(errno));
                    restoreSecCtx(&prevCtx);
                    goto fail;
                }
            }
#endif /* WITH_ACL */
          	// copytruncate 处理方式,步骤1:创建新文件
            fdsave = createOutputFile(saveLog, O_WRONLY, sb, prev_acl, 0);
            restoreSecCtx(&prevCtx);
#ifdef WITH_ACL
            if (prev_acl) {
                acl_free(prev_acl);
                prev_acl = NULL;
            }
#endif
            if (fdsave < 0)
                goto fail;
			// copytruncate 处理方式,步骤2:将日志文件内容复制到新文件
            if (sparse_copy(fdcurr, fdsave, sb, saveLog, currLog) != 1) {
                message(MESS_ERROR, "error copying %s to %s: %s\n", currLog,
                        saveLog, strerror(errno));
                unlink(saveLog);
                goto fail;
            }
        }
    }

    if (log->flags & LOG_FLAG_COPYTRUNCATE) {
        message(MESS_DEBUG, "truncating %s\n", currLog);

        if (!debug) {
            if (fdsave >= 0)
                fsync(fdsave);
          	// copytruncate 处理方式,步骤3:清空日志文件
            if (ftruncate(fdcurr, 0)) {
                message(MESS_ERROR, "error truncating %s: %s\n", currLog,
                        strerror(errno));
                goto fail;
            }
        }
    } else
        message(MESS_DEBUG, "Not truncating %s\n", currLog);

    rc = 0;
fail:
    if (fdcurr >= 0) {
        close(fdcurr);
    }
    if (fdsave >= 0) {
        close(fdsave);
    }
    return rc;
}

2.4. logrotate命令参数和配置文件说明

2.4.1. 命令参数
  • -?, --help:打印帮助信息
  • -d, --debug:调试模式,不会真正的进行日志轮转操作
  • -f, --force:强制进行日志轮转,调试的时候或者配置文件修改后可使用
  • -m, --mail :设置发送邮件时的命令,该命令可设置两个参数,消息主题和收件人,默认为/bin/mail -s
  • -s, --state :设置记录状态的文件,默认为/var/lib/logrotate/logrotate.status
  • –usage: 打印简短的使用信息
  • ±v, --verbose:打印日志轮转时的详细信息
2.4.2. 配置文件说明

压缩相关配置:

  • compress:压缩轮转后的日志,默认为gzip
  • nocompress:轮转后的日志不会被压缩;默认选项
  • compresscmd:设置压缩使用的命令,默认为gzip
  • uncompresscmd:设置解压缩的命令,默认为ungzip
  • compressext:设置日志压缩后的后缀名,默认值遵循配置的压缩命令
  • compressoptions:设置压缩选项,如参数"-<1-9>“,指定压缩效率,默认为”-6",值越大,压缩率越高,但速度越慢
  • delaycompress:将前一个日志文件的压缩推迟到下一个循环周期;覆盖nodelaycompress配置
  • nodelaycompress:不将前一个日志文件的压缩推迟到下一个循环周期;覆盖delaycompress配置;默认选项

日志为空时处理方式配置:

  • ifempty:即使日志为空也进行轮转;此为默认值,覆盖notifempty配置

  • notifempty:如果日志文件为空则不进行轮转;覆盖ifempty配置

额外增加指定文件或目录名的配置:

  • include <file|directory>:读取指定文件或目录中的配置,添加到当前的配置中;如果为目录则按字母顺序读取,会忽略一些非常规的文件(如目录和管道等),以及包含禁止的扩展名的文件,参考tabooext

  • abooext [+] <list>:禁止的扩展名列表;如果扩展名前存在+号,则增加,否则覆盖默认的;包含.rpmsave、 .rpmorig、 ~、 .disabled、.dpkg-old、 .dpkg-dist、 .dpkg-new、 .cfsaved、 .ucf-old、 .ucf-dist、 .ucf-new、 .rpmnew、 .swp、 .cfsaved、 .rhn-cfg-tmp-*

日志轮转处理方式:

  • copy:复制要轮转的日志,而不是更改原始文件,此选项可用于制作当前日志的镜像,或者在其他程序需要截断和解析文件时使用;此选项会导致create配置失效,因为此时旧日志文件还存在

  • nocopy:不复制要轮转的日志;覆盖copy选项;默认选项

  • copytruncate:轮转日志时,先复制原始文件,然后将原始文件截断为0大小(相当于清空);而不是重命名原始日志文件,然后创建一个空的日志文件;当写日志的程序不支持通过信号或其他方式接收需要将日志写入到新日志文件的通知时,可使用此选项;注意在拷贝和截断之间写入的日志文件可能会丢失;使用此选项时,create配置将失效,因为此时旧日志文件还存在,只是被清空了

  • nocopytruncate:创建副本后不要在原地截断原始日志文件;覆盖copytruncate选项;默认选项

  • create <mode> <owner> <group>,create <owner> <group>:轮转日志时,将原始文件重命名,然后创建与原始文件同名的空的日志文件,这里可配置原始文件的mode、owner和group,如"create 0600 root root";当然可以省略任意日志文件属性,新文件这些属性默认与原始文件一致;可以使用nocreate选项禁用此选项;默认选项

  • nocreate:不会创建新的日志文件

  • olddir <dir>:日志移动到指定目录后进行轮转;该目录必须与正在旋转的日志文件位于同一物理设备上,除非使用了 copy、copytruncate 或 renamecopy 选项; 除非指定了绝对路径名,否则该目录为相对于轮转日志所在路径的相对路径。 使用此选项时,所有旧版本的日志都将在目录中结束

  • noolddir:轮转后的日志保存在配置的轮转日志所在目录

  • createolddir <mode> <owner> <group>:如果olddir指令配置的目录不存在,则创建它,需指定mode、owner和group;可以使用nocreateolddir选项禁用此选项

  • nocreateolddir:目录不存在时,logrotate不会创建

日志轮转周期配置:

  • daily:每天轮转日志文件(即logrotate执行时发现距离上次轮转超过一天后则轮转日志)

  • hourly:每小时轮转日志文件

  • weekly <weekday>:日志文件每个工作日轮换一次,或者如果日期距离上次轮换超过7天; 工作日解释如下:0 表示周日,1 表示周一,…,6 表示周六; 特殊值 7 表示每 7 天,与工作日无关。 如果省略 weekday 参数,则默认为 0。

  • monthly:每月第一次运行logrotate时轮转日志

  • yearly:如果当前年份与上次轮换不同,则轮换日志文件

日志不存在时处理方式:

  • missingok:日志文件不存在时,继续轮转下一个而不发出报错

  • nomissingok:如果日志文件不存在,则发出错误; 默认选项

轮转后日志扩展名配置:

  • dateext:轮转后的日志添加日期扩展名,如YYYYMMDD,而不是简单的添加数字,使用dateformat 和dateyesterday选项配置日期格式

  • nodateext:轮转后的日志不添加日期扩展名,使用简单的递增数字;覆盖dateext;默认选项

  • dateformat <format_string>:使用类似于strftime(3) 函数指定dateext的扩展名,但只允许使用%Y %m %d %H 和%s说明符,默认为默认值为"-%Y%m%d";系统时间必须是在2001年9月9日后%s才能正常工作;注意此格式生成的字符串必须是可排序的,2001/12/01可以但01/12/2001不行,因为日志轮转若设置了轮转数量,则在超过数量时需要选择一个最旧的进行删除

  • dateyesterday:使用昨天的日期来生成扩展名

  • extension <ext>:日志轮换后保留<ext>扩展名;如果使用了压缩,则压缩扩展名(一般为.gz)出现在ext之后;如存在mylog.foo的日志文件,希望轮换后的日志名为mylog.1.foo.gz而不是mylog.foo.1.gz

轮转日志大小条件配置:

  • maxage <count>:删除早于天的轮换日志;仅当要轮换日志时检查;如果配置了mail last,则将该日志文件发送到指定的邮箱地址中

  • maxsize <size>:同时考虑日志文件大小和设置的轮换时间间隔(如设置了每天轮换一次),当达到轮换时间间隔且日志文件大于时才会进行轮换

  • minsize <size>:同时考虑日志文件大小和设置的轮换时间间隔(如设置了每天轮换一次),当达到轮换时间间隔且日志文件大于时才会进行轮换

  • size <size>:当日志文件比<size>大时,才会轮转日志;单位100、100k、100M、100G有效

轮转后日志数量即起始序号配置:

  • rotate <count>:设置轮转后的日志数量,超过则删除最旧的;如果count为0,则删除旧版本日志而不是轮换

  • start <count>:轮转的起始序号,默认为1,如指定为2,则轮转后生成的日志文件为mylog.2、mylog.3、mylog.4、…

轮转日志处理中邮件配置:

  • mail <address>:当日志被轮换后不存在时,它将被发送到指定邮件地址的邮箱中;如果特定日志不应生成邮件,可以配置nomail

  • nomail:不发送任何轮换后的旧日志

  • mailfirst:使用 mail 命令时,邮寄刚刚轮换的文件,而不是即将到期的文件

  • maillast:使用 mail 命令时,邮寄即将到期的文件,而不是刚刚轮换的文件(这是默认值)

轮转日志处理中脚本配置:

  • sharedscripts:单个脚本针对匹配多个文件的日志文件条目只运行一次(例如 /var/log/* ),并将整个模式传递给它们;如果所有日志都不需要进行轮转,则不运行;脚本出现错误时会直接退出;覆盖nosharedscripts选项

  • nosharedscripts:为每个轮转的日志文件运行prerotate和postrotate脚本(这是默认设置,并覆盖 sharedscripts 选项);日志文件的绝对路径作为第一个参数传递给脚本。 如果脚本因错误退出,则不会执行该轮转日志的剩余操作

  • postrotate/endscript:在日志文件轮转后执行postrotate和 endscript之间命令(两者都必须单独出现在行上,使用 /bin/sh执行)

  • prerotate/endscript:在日志文件轮转前执行postrotate和 endscript之间命令(两者都必须单独出现在行上,使用 /bin/sh执行);必须确认当前日志需要轮转时才执行;通常,日志文件的绝对路径作为第一个参数传递给脚本;如果指定了sharedscripts,则将整个模式传递给脚本

  • firstaction/endscript:在轮换与通配符模式匹配的所有日志文件和运行prerotate脚本之前,并且存在至少一个日志需要轮转时,执行firstaction和endscript之间的脚本;整个模式作为第一个参数传递给脚本。如果脚本因错误退出;则退出轮转

  • lastaction/endscript:在所有与通配符模式匹配的日志文件被轮换后,并且存在至少一个日志需要轮转时,执行lastaction 和 endscript 之间的脚本;整个模式作为第一个参数传递给脚本。如果脚本因错误退出,则仅显示一条错误消息(因为这是最后一个操作)

  • preremove/endscript:在删除日志之前执行一次preremove和endscript之间的脚本,删除的文件名为参数

旧日志删除配置

  • shred:使用sherd -u删除旧的日志文件而不是unlink删除;确保日志在删除后不可读; 默认情况下是关闭的
  • noshred:删除旧日志文件时不使用 shred;默认选项
  • shredcycles :要求 GNU shred(1) 在删除之前覆盖日志文件次; 如果没有这个选项,将使用 shred 的默认值

使用指定user和group轮转日志

  • su <user> <group>:在设置的user、group轮换日志,而不是使用默认的,默认为root;如果在此处指定的用户/组没有足够的权限来创建轮转时需要的文件,则会导致错误

2.5. man logrotate

LOGROTATE(8)                    System Administrator's Manual                   LOGROTATE(8)

NAME
       logrotate ‐ rotates, compresses, and mails system logs

SYNOPSIS
       logrotate [-dv] [-f|--force] [-s|--state file] config_file ..

DESCRIPTION
       logrotate  is  designed to ease administration of systems that generate large numbers
       of log files.  It allows automatic rotation, compression, removal, and mailing of log
       files.   Each  log  file  may be handled daily, weekly, monthly, or when it grows too
       large.

       Normally, logrotate is run as a daily cron job.  It will not modify a log  more  than
       once  in  one  day  unless  the criterion for that log is based on the log's size and
       logrotate is being run more than once each day, or unless the -f or --force option is
       used.

       Any  number  of config files may be given on the command line. Later config files may
       override the options given in earlier files, so the order in which the logrotate con‐
       fig files are listed is important.  Normally, a single config file which includes any
       other config files which are needed should be used.  See below for  more  information
       on  how  to use the include directive to accomplish this.  If a directory is given on
       the command line, every file in that directory is used as a config file.

       If no command line arguments are given, logrotate will print  version  and  copyright
       information,  along  with  a short usage summary.  If any errors occur while rotating
       logs, logrotate will exit with non-zero status.

OPTIONS
       -?, --help
              Prints help message.

       -d, --debug
              Turns on debug mode and implies -v.  In debug mode, no changes will be made to
              the logs or to the logrotate state file.

       -f, --force
              Tells logrotate to force the rotation, even if it doesn't think this is neces‐
              sary.  Sometimes this is useful after adding new entries to a logrotate config
              file,  or if old log files have been removed by hand, as the new files will be
              created, and logging will continue correctly.

       -m, --mail <command>
              Tells logrotate which command to use when mailing logs.  This  command  should
              accept two arguments: 1) the subject of the message, and 2) the recipient. The
              command must then read a message on standard input and mail it to the  recipi‐
              ent. The default mail command is /bin/mail -s.

       -s, --state <statefile>
              Tells  logrotate  to use an alternate state file.  This is useful if logrotate
              is being run as a different user for various sets of log files.   The  default
              state file is /var/lib/logrotate/logrotate.status.

       --usage
              Prints a short usage message.

       +-v, --verbose
              Turns on verbose mode, ie. display messages during rotation.

CONFIGURATION FILE
       logrotate  reads everything about the log files it should be handling from the series
       of configuration files specified on the command line.  Each  configuration  file  can
       set  global  options  (local  definitions override global ones, and later definitions
       override earlier ones) and specify logfiles to rotate. A  simple  configuration  file
       looks like this:

       # sample logrotate configuration file
       compress

       /var/log/messages {
           rotate 5
           weekly
           postrotate
               /usr/bin/killall -HUP syslogd
           endscript
       }

       "/var/log/httpd/access.log" /var/log/httpd/error.log {
           rotate 5
           mail www@my.org
           size 100k
           sharedscripts
           postrotate
               /usr/bin/killall -HUP httpd
           endscript
       }

       /var/log/news/* {
           monthly
           rotate 2
           olddir /var/log/news/old
           missingok
           postrotate
               kill -HUP `cat /var/run/inn.pid`
           endscript
           nocompress
       }

       ~/log/*.log {}

       The  first  few  lines  set global options; in the example, logs are compressed after
       they are rotated.  Note that comments may appear anywhere in the config file as  long
       as the first non-whitespace character on the line is a #.

       The  next section of the config file defines how to handle the log file /var/log/mes‐
       sages. The log will go through five weekly rotations before being removed. After  the
       log  file  has  been  rotated  (but  before  the old version of the log has been com‐
       pressed), the command /sbin/killall -HUP syslogd will be executed.

       The next section  defines  the  parameters  for  both  /var/log/httpd/access.log  and
       /var/log/httpd/error.log.   Each  is rotated whenever it grows over 100k in size, and
       the old logs files are mailed (uncompressed) to  www@my.org  after  going  through  5
       rotations,  rather  than  being  removed. The sharedscripts means that the postrotate
       script will only be run once (after the old logs have been compressed), not once  for
       each  log  which is rotated.  Note that log file names may be enclosed in quotes (and
       that quotes are required if the name contains spaces).  Normal  shell  quoting  rules
       apply, with ', ", and \ characters supported.

       The  next  section defines the parameters for all of the files in /var/log/news. Each
       file is rotated on a monthly basis.  This is considered a single  rotation  directive
       and if errors occur for more than one file, the log files are not compressed.

       The  last  section  uses tilde expansion to rotate log files in the home directory of
       the current user. This is only available, if your glob library supports tilde  expan‐
       sion. GNU glob does support this.

       Please  use  wildcards  with  caution.   If  you specify *, logrotate will rotate all
       files, including previously rotated ones.  A way around this is  to  use  the  olddir
       directive or a more exact wildcard (such as *.log).

       Here  is more information on the directives which may be included in a logrotate con‐
       figuration file:

       compress
              Old versions of log files are compressed with gzip(1)  by  default.  See  also
              nocompress.

       compresscmd
              Specifies which command to use to compress log files.  The default is gzip(1).
              See also compress.

       uncompresscmd
              Specifies which command to use to uncompress log files.  The default  is  gun‐
              zip(1).

       compressext
              Specifies  which  extension  to  use on compressed logfiles, if compression is
              enabled.  The default follows that of the configured compression command.

       compressoptions
              Command line options may be passed to the compression program, if  one  is  in
              use.   The  default,  for gzip(1), is "-6" (biased towards high compression at
              the expense of speed).  If you use a different compression  command,  you  may
              need to change the compressoptions to match.

       copy   Make  a  copy  of  the  log  file, but don't change the original at all.  This
              option can be used, for instance, to make a snapshot of the current log  file,
              or  when  some  other  utility needs to truncate or parse the file.  When this
              option is used, the create option will have no effect, as  the  old  log  file
              stays in place.

       copytruncate
              Truncate  the  original  log file to zero size in place after creating a copy,
              instead of moving the old log file and optionally creating a new one.  It  can
              be  used  when some program cannot be told to close its logfile and thus might
              continue writing (appending) to the previous  log  file  forever.   Note  that
              there  is  a very small time slice between copying the file and truncating it,
              so some logging data might be lost.  When this  option  is  used,  the  create
              option will have no effect, as the old log file stays in place.

       create mode owner group, create owner group
              Immediately  after rotation (before the postrotate script is run) the log file
              is created (with the same name as the log file just rotated).  mode  specifies
              the mode for the log file in octal (the same as chmod(2)), owner specifies the
              user name who will own the log file, and group specifies  the  group  the  log
              file  will  belong to. Any of the log file attributes may be omitted, in which
              case those attributes for the new file will use the same values as the  origi‐
              nal log file for the omitted attributes. This option can be disabled using the
              nocreate option.

       createolddir mode owner group
              If the directory specified by olddir directive does not exist, it is  created.
              mode  specifies  the  mode  for  the  olddir  directory  in octal (the same as
              chmod(2)), owner specifies the user name who will own  the  olddir  directory,
              and group specifies the group the olddir directory will belong to. This option
              can be disabled using the nocreateolddir option.

       daily  Log files are rotated every day.

       dateext
              Archive old versions of log  files  adding  a  date  extension  like  YYYYMMDD
              instead  of  simply adding a number. The extension may be configured using the
              dateformat and dateyesterday options.

       dateformat format_string
              Specify the extension for dateext using the notation  similar  to  strftime(3)
              function.  Only  %Y %m %d %H and %s specifiers are allowed.  The default value
              is -%Y%m%d except hourly, which uses -%Y%m%d%H as default  value.   Note  that
              also the character separating log name from the extension is part of the date‐
              format string. The system clock must be set past Sep 9th 2001 for %s  to  work
              correctly.   Note  that  the datestamps generated by this format must be lexi‐
              cally sortable (i.e., first the year, then  the  month  then  the  day.  e.g.,
              2001/12/01  is  ok,  but  01/12/2001 is not, since 01/11/2002 would sort lower
              while it is later).  This is because when using the rotate  option,  logrotate
              sorts all rotated filenames to find out which logfiles are older and should be
              removed.

       dateyesterday
              Use yesterday's instead of today's date to create the  dateext  extension,  so
              that the rotated log file has a date in its name that is the same as the time‐
              stamps within it.

       delaycompress
              Postpone compression of the previous log file  to  the  next  rotation  cycle.
              This  only  has effect when used in combination with compress.  It can be used
              when some program cannot be told to close its logfile and thus might  continue
              writing to the previous log file for some time.

       extension ext
              Log  files  with ext extension can keep it after the rotation.  If compression
              is  used,  the compression extension (normally .gz)  appears  after  ext.  For
              example  you  have  a  logfile  named  mylog.foo  and  want  to  rotate  it to
              mylog.1.foo.gz instead of mylog.foo.1.gz.

       hourly Log files are rotated every hour. Note that usually logrotate is configured to
              be  run by cron daily. You have to change this configuration and run logrotate
              hourly to be able to really rotate logs hourly.

       ifempty
              Rotate the log file even if it is  empty,  overriding  the  notifempty  option
              (ifempty is the default).

       include file_or_directory
              Reads  the  file  given  as an argument as if it was included inline where the
              include directive appears. If a directory is given, most of the files in  that
              directory are read in alphabetic order before processing of the including file
              continues. The only files which are ignored are files which  are  not  regular
              files (such as directories and named pipes) and files whose names end with one
              of the taboo extensions, as specified by the tabooext directive.

       mail address
              When a log is rotated out of existence, it is mailed to address.  If  no  mail
              should be generated by a particular log, the nomail directive may be used.

       mailfirst
              When using the mail command, mail the just-rotated file, instead of the about-
              to-expire file.

       maillast
              When using the mail command, mail the about-to-expire  file,  instead  of  the
              just-rotated file (this is the default).

       maxage count
              Remove  rotated  logs  older than <count> days. The age is only checked if the
              logfile is to be rotated. The files are mailed to the  configured  address  if
              maillast and mail are configured.

       maxsize size
              Log  files  are  rotated when they grow bigger than size bytes even before the
              additionally specified time interval (daily, weekly, monthly, or yearly).  The
              related  size  option is similar except that it is mutually exclusive with the
              time interval options, and it causes log files to be  rotated  without  regard
              for the last rotation time.  When maxsize is used, both the size and timestamp
              of a log file are considered.

       minsize  size
              Log files are rotated when they grow bigger than size bytes,  but  not  before
              the  additionally specified time interval (daily, weekly, monthly, or yearly).
              The related size option is similar except that it is mutually  exclusive  with
              the  time  interval  options,  and  it  causes log files to be rotated without
              regard for the last rotation time.  When minsize is used, both  the  size  and
              timestamp of a log file are considered.

       missingok
              If  the  log  file  is missing, go on to the next one without issuing an error
              message. See also nomissingok.

       monthly
              Log files are rotated the first time logrotate is run in a month (this is nor‐
              mally on the first day of the month).

       nocompress
              Old versions of log files are not compressed. See also compress.

       nocopy Do  not copy the original log file and leave it in place.  (this overrides the
              copy option).

       nocopytruncate
              Do not truncate the original log file in place after  creating  a  copy  (this
              overrides the copytruncate option).

       nocreate
              New log files are not created (this overrides the create option).

       nocreateolddir
              olddir directory is not created by logrotate when it does not exist.

       nodelaycompress
              Do  not  postpone  compression  of  the previous log file to the next rotation
              cycle (this overrides the delaycompress option).

       nodateext
              Do not archive  old versions of log files with date extension (this  overrides
              the dateext option).

       nomail Do not mail old log files to any address.

       nomissingok
              If a log file does not exist, issue an error. This is the default.

       noolddir
              Logs  are rotated in the directory they normally reside in (this overrides the
              olddir option).

       nosharedscripts
              Run prerotate and postrotate scripts for every log file which is rotated (this
              is  the default, and overrides the sharedscripts option). The absolute path to
              the log file is passed as first argument to the script. If  the  scripts  exit
              with  error,  the  remaining actions will not be executed for the affected log
              only.

       noshred
              Do not use shred when deleting old log files. See also shred.

       notifempty
              Do not rotate the log if it is empty (this overrides the ifempty option).

       olddir directory
              Logs are moved into directory for rotation. The directory must be on the  same
              physical  device  as  the log file being rotated, unless copy, copytruncate or
              renamecopy option is used. The directory is assumed  to  be  relative  to  the
              directory holding the log file unless an absolute path name is specified. When
              this option is used all old versions of the log end  up  in  directory.   This
              option may be overridden by the noolddir option.

       postrotate/endscript
              The lines between postrotate and endscript (both of which must appear on lines
              by themselves) are executed (using /bin/sh) after the  log  file  is  rotated.
              These  directives  may only appear inside a log file definition. Normally, the
              absolute path to the log file is passed as first argument to  the  script.  If
              sharedscripts  is  specified, whole pattern is passed to the script.  See also
              prerotate. See sharedscripts and nosharedscripts for error handling.

       prerotate/endscript
              The lines between prerotate and endscript (both of which must appear on  lines
              by themselves) are executed (using /bin/sh) before the log file is rotated and
              only if the log will actually be rotated. These  directives  may  only  appear
              inside  a  log file definition. Normally, the absolute path to the log file is
              passed as first argument to the script.  If  sharedscripts is specified, whole
              pattern  is passed to the script.  See also postrotate.  See sharedscripts and
              nosharedscripts for error handling.

       firstaction/endscript
              The lines between firstaction and endscript (both  of  which  must  appear  on
              lines  by  themselves)  are executed (using /bin/sh) once before all log files
              that match the wildcarded pattern are rotated, before prerotate script is  run
              and  only  if at least one log will actually be rotated.  These directives may
              only appear inside a log file definition.  Whole  pattern  is  passed  to  the
              script  as first argument. If the script exits with error, no further process‐
              ing is done. See also lastaction.

       lastaction/endscript
              The lines between lastaction and endscript (both of which must appear on lines
              by  themselves)  are  executed  (using  /bin/sh) once after all log files that
              match the wildcarded pattern are rotated, after postrotate script is  run  and
              only if at least one log is rotated. These directives may only appear inside a
              log file definition. Whole pattern is passed to the script as first  argument.
              If the script exits with error, just an error message is shown (as this is the
              last action). See also firstaction.

       preremove/endscript
              The lines between preremove and endscript (both of which must appear on  lines
              by  themselves) are executed (using /bin/sh) once just before removal of a log
              file.  The logrotate will pass the name of file which is soon to  be  removed.
              See also firstaction.

       rotate count
              Log  files  are  rotated  count  times  before  being removed or mailed to the
              address specified in a mail directive. If count is 0, old versions are removed
              rather than rotated.

       size size
              Log  files  are  rotated  only if they grow bigger then size bytes. If size is
              followed by k, the size is assumed to be in kilobytes.  If the M is used,  the
              size is in megabytes, and if G is used, the size is in gigabytes. So size 100,
              size 100k, size 100M and size 100G are all valid.

       sharedscripts
              Normally, prerotate and postrotate scripts are  run  for  each  log  which  is
              rotated  and  the absolute path to the log file is passed as first argument to
              the script. That means a single script may be run multiple times for log  file
              entries  which  match multiple files (such as the /var/log/news/* example). If
              sharedscripts is specified, the scripts are only run once, no matter how  many
              logs  match the wildcarded pattern, and whole pattern is passed to them.  How‐
              ever, if none of the logs in the pattern require rotating,  the  scripts  will
              not  be run at all. If the scripts exit with error, the remaining actions will
              not be executed for any logs. This option overrides the nosharedscripts option
              and implies create option.

       shred  Delete  log files using shred -u instead of unlink().  This should ensure that
              logs are not readable after their scheduled deletion; this is off by  default.
              See also noshred.

       shredcycles count
              Asks GNU shred(1) to overwrite log files count times before deletion.  Without
              this option, shred's default will be used.


       start count
              This is the number to use as the base for rotation. For example, if you  spec‐
              ify  0,  the logs will be created with a .0 extension as they are rotated from
              the original log files.  If you specify 9, log files will be  created  with  a
              .9,  skipping  0-8.  Files will still be rotated the number of times specified
              with the rotate directive.

       su user group
              Rotate log files set under this  user  and  group  instead  of  using  default
              user/group  (usually root). user specifies the user name used for rotation and
              group specifies the group used for rotation. If  the  user/group  you  specify
              here  does  not  have  sufficient  privilege  to make files with the ownership
              you've specified in a create instruction, it will cause an error.

       tabooext [+] list
              The current taboo extension list is changed (see  the  include  directive  for
              information  on the taboo extensions). If a + precedes the list of extensions,
              the current taboo extension list is augmented, otherwise it  is  replaced.  At
              startup,  the  taboo extension list contains .rpmsave, .rpmorig, ~, .disabled,
              .dpkg-old, .dpkg-dist, .dpkg-new,  .cfsaved,  .ucf-old,  .ucf-dist,  .ucf-new,
              .rpmnew, .swp, .cfsaved, .rhn-cfg-tmp-*

       weekly [weekday]
              Log  files  are  rotated  once  each weekday, or if the date is advanced by at
              least 7 days since the last rotation (while ignoring  the  exact  time).   The
              weekday  intepretation  is  following:  0 means Sunday, 1 means Monday, ..., 6
              means Saturday; the special value 7 means each 7 days, irrespectively of week‐
              day.  Defaults to 0 if the weekday argument is omitted.

       yearly Log  files  are  rotated if the current year is not the same as the last rota‐
              tion.

FILES
       /var/lib/logrotate/logrotate.status
                                  Default state file.
       /etc/logrotate.conf        Configuration options.

SEE ALSO
       gzip(1)

       <https://github.com/logrotate/logrotate>

AUTHORS
       Erik Troan, Preston Brown, Jan Kaluza.

       <https://github.com/logrotate/logrotate>

Linux                                  Wed Nov 5 2002                           LOGROTATE(8)
  • 13
    点赞
  • 15
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Tomcat是一个常用的Java Web应用程序服务器,它会记录大量的日志信息,而这些日志文件会不断增大,占用大量的磁盘空间。为了解决这个问题,通常需要进行日志切割和压缩,这就需要使用到logrotate工具。 logrotate是一个Linux系统下的日志文件管理工具,可以自动切割、压缩和删除日志文件,同时可以保留一定数量的历史日志文件。通过使用logrotate,可以使得Tomcat的日志文件管理更加便捷和高效。 下面是一个简单的logrotate配置文件示例,用于对Tomcat的catalina.out日志文件进行管理: ``` /home/tomcat/logs/catalina.out { daily missingok rotate 7 compress delaycompress notifempty copytruncate } ``` 解释: - `/home/tomcat/logs/catalina.out`:表示要进行管理日志文件路径。 - `daily`:表示按照每天的时间间隔进行日志切割。 - `missingok`:表示如果日志文件不存在则忽略该文件。 - `rotate 7`:表示保留7个历史日志文件。 - `compress`:表示对切割后的日志文件进行压缩。 - `delaycompress`:表示在下一次切割时再进行压缩,避免出现压缩失败的情况。 - `notifempty`:表示如果日志文件为空则不进行切割。 - `copytruncate`:表示备份旧日志文件时,使用复制方式,同时截断原始日志文件,避免出现日志丢失的情况。 以上配置可以根据实际情况进行调整和修改。配置完成后,可以使用以下命令手动进行日志切割: ``` logrotate -f /etc/logrotate.d/tomcat ``` 其中`-f`表示强制执行,`/etc/logrotate.d/tomcat`为配置文件路径。也可以将该命令添加到定时任务中,以定期对Tomcat日志进行切割。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值