Golang os.Create 权限被拒绝

huangapple go评论106阅读模式
英文:

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权限问题。鉴于该目录的特殊性,你有三个选项:

  1. 将该目录的权限更改为更宽松的权限。这个主意不好,因为从安全角度来看,它会引发一系列麻烦。
  2. 使用sysV、upstart或systemd运行go程序,以便程序以具有该目录权限的用户(通常是root用户)运行。这个方法更好,因为只有一个进程会获得升级,并且你可以使用upstart或systemd提供的良好的启动/停止/监控例程和基本的自愈功能。如果你还没有使用其中之一,确实可以考虑使用它们。
  3. 使用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:

  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.

huangapple
  • 本文由 发表于 2017年4月11日 12:51:41
  • 转载请务必保留本文链接:https://go.coder-hub.com/43337019.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定