英文:
Golang os.Create permission denied
问题
我正在尝试在Linux的/var/log目录下创建一个日志文件,但是遇到了权限被拒绝的问题。有没有不需要更改目录所有权的最佳实践方法?
f, _ := os.Create("/var/log/go_server.log")
defer f.Close()
log.SetOutput(f)
英文:
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)
答案1
得分: 6
你那里出现的是一个标准的UNIX权限问题。鉴于该目录的特殊性,你有三个选项:
- 将该目录的权限更改为更宽松的权限。这个主意不好,因为从安全角度来看,它会引发一系列麻烦。
- 使用sysV、upstart或systemd运行go程序,以便程序以具有该目录权限的用户(通常是root用户)运行。这个方法更好,因为只有一个进程会获得升级,并且你可以使用upstart或systemd提供的良好的启动/停止/监控例程和基本的自愈功能。如果你还没有使用其中之一,确实可以考虑使用它们。
- 使用go的内置syslog接口,并配置本地syslogd将其日志保存到该文件中。这是最好的方法,因为你只需将日志发送到一个套接字,让服务来处理。
此外,如果你正确配置了systemd,它还可以将你的标准输出/错误保存到文件中,然后你可以使用journalctl进行浏览。实际上,让你的程序愚蠢地将诊断信息打印到标准输出/错误并且不进行分叉,现在是最明智的做法,因为systemd会为你处理所有这些事情(这样,你可以专注于你的程序要做的事情,而不是重新发明关于守护进程和日志记录的轮子)。
尽管systemd备受诟病,但它在这种情况下实际上非常好用。
英文:
What you have there is a standard UNIX permissions issue. Given the special nature of that directory, you've got three options:
- Change the permissions of that directory to be more promiscuous. Bad idea, as it opens up a nasty can of worms security-wise.
- 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.
- 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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论