I am using Go.
I want to create a log file called webapp.log when I run go run main.go.
However, when I run go run main.go, the message "2021/09/25 14:58:55 open : no such file or directory"
appears in the terminal and the log file is not created.
I can't tell from the message which location is causing the log file not to be created.
If anyone can help me, please let me know.
main.go
package main
import (
"fmt"
"golang_todo_app/config"
"log"
)
func main() {
fmt.Println(config.Config.Port)
fmt.Println(config.Config.SQLDriver)
fmt.Println(config.Config.DbName)
fmt.Println(config.Config.LogFile)
log.Println("test")
}
config/config.go
package config
import (
"golang_todo_app/utils"
"log"
"gopkg.in/go-ini/ini.v1"
)
type ConfigList struct {
Port string
SQLDriver string
DbName string
LogFile string
}
var Config ConfigList
func init () {
LoadConfig()
utils.LoggingSettings(Config.LogFile)
}
func LoadConfig() {
cfg, err := ini.Load("config.ini")
if err != nil {
log.Fatalln()
}
Config = ConfigList{
Port: cfg.Section("web").Key("port").MustString("8080"),
SQLDriver: cfg.Section("db").Key("driver").String(),
DbName: cfg.Section("db").Key("name").String(),
LogFile: cfg.Section("web").Key("logfile").String(),
}
}
utils/logging.go
package utils
import (
"io"
"log"
"os"
)
func LoggingSettings(logFile string) {
logfile, err := os.OpenFile(logFile, os.O_RDWR|os.O_CREATE|os.O_APPEND, 0666)
if err != nil {
log.Fatalln(err)
}
multiLogFile := io.MultiWriter(os.Stdout, logfile)
log.SetFlags(log.Ldate | log.Ltime | log.Lshortfile)
log.SetOutput(multiLogFile)
}
CodePudding user response:
"2021/09/25 14:58:55 open : no such file or directory"
Have a look of your code, the most possible place which will raise this error is next:
logfile, err := os.OpenFile(logFile, os.O_RDWR|os.O_CREATE|os.O_APPEND, 0666)
Usually if we open a file with no permission e.g. /root/log.txt, it could produce next:
2021/09/25 17:50:07 open /root/log.txt: permission denied
You could see the /root/log.txt
will be displayed to tell user which file can't be open, but for you, your error return nothing after open
. This means for next code:
LoggingSettings(Config.LogFile)
The Config.LogFile
parser returns nothing. The correct ini
setting maybe next:
config.ini:
[web]
logfile=/tmp/log.txt
You should check your ini
file to see if any mistake makes the code can't parse a valid logfile
value.
BTW, next code will happen when you import "golang_todo_app/config"
, so your print in main
function executed after next function, your print in main won't have chance to run if the error haapens in init
.
func init () {
LoadConfig()
utils.LoggingSettings(Config.LogFile)
}