英文:
Implement a function which returns a pointer
问题
我已经在我的golang应用程序中实现了syslog守护进程服务。我在主包中使用了syslog.New,并且它可以正常工作,但是现在,我想将它导出到另一个包中。
package config
import (
"log/syslog"
)
func LogBook() ? {
sysLog, _ := syslog.New(syslog.LOG_LOCAL0|syslog.LOG_ERROR, "myapp") // syslog.New返回(*Writer, error)
return ?
}
我该如何实现这个函数?
然后,我该如何在其他包中使用这个变量'sysLog'?
谢谢!
英文:
I have implemented the syslog daemon service in my golang app. I used syslog.New in main package and it works but now, I want to export it to another package.
package config
import (
"log/syslog"
)
func LogBook() ? {
sysLog, _ := syslog.New(syslog.LOG_LOCAL0|syslog.LOG_ERROR, "myapp") // syslog.New returns (*Writer, error)
return ?
}
How can I implement this function?
After, how can I use this variable 'sysLog' in other packages?
Thank you!
答案1
得分: 2
答案很简单,就像@Volker所说的那样,
func LogBook() *syslog.Writer {
sysLog, _ := syslog.New(syslog.LOG_LOCAL0|syslog.LOG_ERROR, "myapp")
return sysLog
}
用法示例:
func main(){
w := LogBook()
w.Info("message")
}
请注意:
- 此包在Windows上未实现。由于syslog包已经冻结,建议Windows用户使用标准库之外的包。有关背景,请参阅https://golang.org/issue/1108。
- 此包在Plan 9上未实现。
- 此包在NaCl(Native Client)上未实现。
英文:
The answer is pretty simple as @Volker said,
func LogBook() *syslog.Writer {
sysLog, _ := syslog.New(syslog.LOG_LOCAL0|syslog.LOG_ERROR, "myapp")
return sysLog
}
Usage Example:
func main(){
w := LogBook()
w.Info("message")
}
Please notice:
- This package is not implemented on Windows. As the syslog package is frozen, Windows users are encouraged to use a package outside of the standard library. For background, see https://golang.org/issue/1108.
- This package is not implemented on Plan 9.
- This package is not implemented on NaCl (Native Client).
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论