-1

I want to write a service putting log in /var/log, then I edit a xxx.service under systemd.

[Service]
User=xxx
Group=xxx

But the service throw a error that open /var/log/xxx.log the permission denied. How do they implement write log in /var/log and the log owner is service account itself like nginx,mysql,httpd etc. Is it implement in program or there is some configure in os?

2 Answers2

1

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.

Cenkoloji
  • 21
  • 3
1

There are many ways to do this, I will name a few:

  • create a subdirectory (/var/log/serviceXXX ) which is being owned by the user / group in question, and put your logfiles there
  • talk to the syslog daemon, and let that daemon write the logs for you (that is what that daemon is being made for - this should be as easy as opening /dev/log for writing...)
  • you can even configure the syslog daemon to write to the custom logfile you want, all you need for this is to create a custom logging facility (f.e. a drop-in config file in /etc/rsyslog.d)
  • /var/log is owned by a specific group (syslog in my case) - add that group to the supplementary groups of your user
Martin
  • 1,869
  • 6
  • 16