Search code examples
linuxfilegopermission-denied

Golang os.Create permission denied


I'm trying to create a log file on linux /var/log directory, but got permission denied. Any best practices without having to change the ownership of the directory?

f, _ := os.Create("/var/log/go_server.log")
defer f.Close()
log.SetOutput(f)

Solution

  • What you have there is a standard UNIX permissions issue. Given the special nature of that directory, you've got three options:

    1. Change the permissions of that directory to be more promiscuous. Bad idea, as it opens up a nasty can of worms security-wise.
    2. Run the go program using sysV, upstart, or systemd such that the program runs with a user with permissions there (usually root). Better because only one process gets the upgrade and you get nice start/stop/monitor routines and rudimentary self-healing with upstart or systemd. Indeed, you may want to explore using one of those if you're not already.
    3. Use go's built-in interface to syslog and configure your local syslogd to save its logs to that file. Best, because you're just sending logs to a socket and letting the service deal with it for you.

    Note also that systemd can save your stdout/err to files if you configure it right and you can then browse with journalctl. Indeed, leaving your program to stupidly print diags to stdout/err and not forking itself is the smartest thing to do now that systemd does all that stuff for you (that way, you can focus on what your program does and not reinventing the wheel wrt daemonization and logging).

    For all the grief systemd gets, it's actually pretty good at this use case.