Why most services use non-root account could create logfile in /var/log?
If you want service to be able to create log files on the fly, while creating the service, you can create a directory under /var/log
and set the owner to service account
mkdir /var/log/myservice/
chown myservice:myservice /var/log/myservice/
chmod 755 /var/log/myservice/
For instance this is the case for nginx. After the first creation, logrotate can take care of file ownership. In centos8, /etc/logrotate.d/nginx
looks like: (see second line)
/var/log/nginx/*log {
create 0664 nginx root
daily
rotate 10
missingok
notifempty
compress
sharedscripts
postrotate
/bin/kill -USR1 `cat /run/nginx.pid 2>/dev/null` 2>/dev/null || true
endscript
}
When you look at logfiles, you'll see only the actual log file is owned by nginx, and rotated ones by root.
$ ls -l /var/log/nginx/
total 8
-rw-rw-r--. 1 nginx root 0 Aug 29 2020 access.log
-rw-r--r--. 1 root root 3441 Aug 27 2020 access.log-20200829.gz
-rw-rw-r--. 1 nginx root 0 Aug 29 2020 error.log
-rw-r--r--. 1 root root 658 Aug 27 2020 error.log-20200829.gz
If you want files to be directly in /var/log
, again you'd have to create them once as root and set owner.