preface

The Logrotate program is a log file management tool built into CentOS. Used to rename or delete old log files and create new log files, we call this “dump”. Log dump – log dump – log dump – log dump – log dump – log dump – log dump – log dump – log dump – log dump – log dump – log dump –

The main logrotate configuration files are: /etc/logrotate.conf, and some custom configuration files are placed under the /etc/logrotate.d/ directory. For example, we can put nginx rotation logs in /etc/logrotate.d/. Logrotate performs the configuration in both directories at runtime. The following uses the nginx log rotation log as an example.

Step 1 write a configuration file

/usr/local/nginx/logs/*.log{
        # Rotate daily
        daily
        Save 20 log files
        rotate 20
        Log rotation occurs when the log file is larger than 100K
        size 100k
        # specify the permission of the new log file and its owning user and group
        create 644 root root
        # add time to log file name
        dateext
        Name the dateext implementation file
        dateformat -%Y%m%d%H-%s
        # ignore error
        missingok
        #copytruncate
        If this is not configured, the following script will execute multiple times when there are multiple logs in the log directory
        sharedscripts
        postrotate
                 if [ -f /usr/local/nginx/logs/nginx.pid ]; then
                         kill -USR1 `cat /usr/local/nginx/logs/nginx.pid`
                 fi
        endscript
}

Copy the code

Step 2. Disable SElinux. Otherwise, logs cannot be cut properly

Temporary closure:

Setenforce 0 or setenforce PermissiveCopy the code

Permanent ban

Vi /etc/selinux/config Change selinux =enforcing in the configuration file to selinux =disabled. Save the configuration file rebootRestart the system
 
Copy the code

Step 3 Customize the log rolling execution time

Since the system default logrotate is randomly selected at 3-22pm every day,

If this task does not meet our requirements, we can customize a task to perform log scrolling at 23:59 every day:

Split the nginx log once a day at 23:59 PM and put the run log into logrotate.splitlog
59 23 * * * /usr/sbin/logrotate -vf /etc/logrotate.d/nginx  >>/usr/local/nginx/logs/logrotate.splitlog 2>&1

Copy the code

The next day, see the running results as shown below:

Common commands

Check logrotate running state: cat/var/lib/logrotate/logrotate status

View the run logs of crontab: cat /var/log/cron

Refer to the link

  1. Logrotate Failed to roll logs. Procedure

  2. Do you really understand Logrotate yet?

  3. Linux crontab command

  4. Linux logrotate command

  5. Introduction to use of Logrotate

  6. Log cutting summary

  7. Linux built-in artifact Logrotate details

  8. After Logrotate cuts the log, the new log is still written to the old log file