How should I log from a non-root Debian Linux daem

2019-04-17 21:51发布

问题:

I'm writing a new daemon, which will be hosted on Debian Linux.

I've found that /var/log has root only write permissions, so my daemon cannot write log files there.

However, if it writes there, it appears it will gain automatic log rotation, and also work as a user might expect.

What is the recommended way for a daemon to write log entries that appear in /var/log, without having to be run as root?

The daemon is a webserver, so the log traffic will be similar to Apache.

回答1:

You should create a subdirectory like /var/log/mydaemon having the daemon's user ownership



回答2:

As root, create a logfile there and change the files owner to the webserver user:

# touch /var/log/myserver.log
# chown wwwuser /var/log/myserver.log

Then the server can write to the files if run as user wwwuser. It will not gain automatic log rotation, though. You have to add the logfile to /etc/logrotate.conf or /etc/logrotate.d/... and make your server reopen the logfile when logrotate signals it should.

You might also use syslog for logging, if that fit's your scenario better.



回答3:

Two options:

  1. Start as root, open the file, then drop permissions with setuid. (I don't remember the exact system calls for dropping permissions.) You'll have to do this anyway if you want to bind to TCP port 80 or any port below 1024.
  2. Create a subdirectory like /var/log/mydaemon having the daemon's user ownership, as WiseTechi said.

Files under /var/log aren't automatically rotated; instead, rotation is controlled by /etc/logrotate.conf and files under /etc/logrotate.d.



回答4:

use the "logger" command

http://linux.die.net/man/1/logger