Blog / Linux/ How to Clear Log Files in an LNMP Environment

How to Clear Log Files in an LNMP Environment

LNMP如何清空日志文件?

How to Clear Log Files in an LNMP Environment

To clear log files on a Linux system, you can create and run a shell script. Save the following code as a file with a .sh extension, grant it execute permissions, and then run it.

Important Note: Do not directly clear important log files (e.g., those needed for troubleshooting) without first ensuring they are no longer needed or have been backed up.

#!/bin/sh

# Clear system log files
cat /dev/null > /var/log/syslog
cat /dev/null > /var/adm/sylog
cat /dev/null > /var/log/wtmp
cat /dev/null > /var/log/maillog
cat /dev/null > /var/log/messages
cat /dev/null > /var/log/openwebmail.log
cat /dev/null > /var/log/secure

# Clear Apache/Nginx (common in LNMP) log files
cat /dev/null > /var/log/httpd/error_log
cat /dev/null > /var/log/httpd/ssl_error_log
cat /dev/null > /var/log/httpd/ssl_request_log
cat /dev/null > /var/log/httpd/ssl_access_log

Explanation

  • The path /var/adm/sylog in the script is less common. Standard system log paths are typically /var/log/syslog or /var/log/messages.
  • The command cat /dev/null > file_path writes empty content to the target file, clearing it without deleting the file itself.
  • Actual paths may vary depending on the Linux distribution (e.g., CentOS, Ubuntu) and web server (e.g., Nginx, Apache). For example, Nginx logs are usually located in the /var/log/nginx/ directory.

Other System Cleanup Commands

Beyond clearing logs, you can use the following commands to clean system caches and orphaned packages:

  • sudo apt-get autoclean: Clears the cache of old versions of uninstalled software (for Debian/Ubuntu systems).
  • sudo apt-get clean: Clears the cache of all downloaded packages (for Debian/Ubuntu systems).
  • sudo apt-get autoremove: Automatically removes orphaned packages no longer used by the system (for Debian/Ubuntu systems).

For CentOS/RHEL systems using yum, the corresponding commands are sudo yum clean all and sudo package-cleanup --quiet --leaves (requires yum-utils to be installed).

Post a Comment

Your email will not be published. Required fields are marked with *.