Years ago, I wrote about using syslog-ng on OpenWRT for logging.
Times have change, and OpenWRT has evolved. With the current stable version (19.07.3), syslog-ng is no longer the preferred method. Instead, I have found that rsyslog works better. In this article, I describe how to install and configure rsyslog.
Before you do the steps below, make sure that you have a USB flash drive with at least 2GB of space, formatted with ext4, and that you have USB storage installed, per this detailed guide. Let us say that the USB flash drive will be mounted at /mnt/usb, and there is a directory called "logs" on it.
Installing rsyslog on OpenWRT
To install rsyslog, use the following commands from ssh:
opkg update
opkg install rsyslog
Configuring rsyslog on OpenWRT
Modify the file /etc/rsyslog.conf to look like the following. The main change is using a path to the log file that is on a directory on the USB flash device.
module(load="imuxsock")
module(load="imklog")
module(load="imudp")
input(type="imudp" port="514")
#module(load="imtcp")
#input(type="imtcp" port="514")
$ActionFileDefaultTemplate RSYSLOG_TraditionalFileFormat
*.info;mail.none;authpriv.none;cron.none /mnt/usb1/logs/syslog.log
authpriv.* /mnt/usb/logs/syslog.log
mail.* /mnt/usb/logs/syslog.log
cron.* /mnt/usb/logs/syslog.log
local7.* /mnt/usb/logs/syslog.log
Log rotation
The above file will grow indefinitely, which is not efficient, and may cause problems. To avoid this, we move the contents of the daily log to a monthly log near midnight every day. You can use the logrotate package to do the same, but in my case, since I log everything to a single file, I opted for a simple shell script that runs from cron.
#!/bin/sh
# Daily script to append log file to the monthly log file
PROG=`basename $0`
DIR=/mnt/usb/logs
LOG=$DIR/syslog.log
# Now get the year and month of this month
YEAR_MONTH=`date +%Y-%m`
START_TIME=`date +%s`
# Stop the log temporarily
/etc/init.d/rsyslog stop
# Append the contents of the rotated log to the year-month log
cat $LOG >> $DIR/syslog-$YEAR_MONTH.log
# Truncate the old log
> $LOG
/etc/init.d/rsyslog start
END_TIME=`date +%s`
# Calculate the elapsed time
SECONDS=`expr $END_TIME - $START_TIME`
sleep 2
logger -t $PROG "Log rotation completed in $SECONDS seconds."
Save this file to /etc/custom/logrotate.sh (create the /etc/custom directory), and add this to cron as:
crontab -e
Then, add this line:
# Rotate the rsyslog daily before end of day
58 23 * * * /etc/custom/logrotate.sh
What the above will do, is that the daily log will be called syslog.log, and the monthly log will be syslog-yyyy-mm.log, with yyyy and mm the year and month numbers.
Make Sure It All Works
Reboot the router to make sure that everything works as it should, and check the rotation after midnight.
Most Comments
Most commented on articles ...