package main
import (
"bufio"
"log"
"os"
"os/exec"
"path/filepath"
"strings"
"time"
)
/*获取当前文件执行的路径*/
func GetCurrPath() string {
file, _ := exec.LookPath(os.Args[0])
path, _ := filepath.Abs(file)
splitstring := strings.Split(path, "\\")
size := len(splitstring)
splitstring = strings.Split(path, splitstring[size-1])
ret := strings.Replace(splitstring[0], "\\", "/", size-1)
return ret
}
func main() {
//创建日志文件
t := time.Now()
filepath := "./log_" + strings.Replace(t.String()[:19], ":", "_", 3) + ".txt"//2019-06-13 14_56_13.txt
//filepath := "./log_" + strings.Replace(t.String()[:10], ":", "_", 3) + ".log"//2019-06-13.log
file, err := os.OpenFile(filepath, os.O_CREATE, 0666)
if err != nil {
log.Fatal("create log file failed!")
}
defer file.Close()
wFile := bufio.NewWriter(file)
//获取当前程序执行的绝对路径
wFile.WriteString(GetCurrPath()) //写入内容
wFile.Flush()
}
本文介绍了一个使用Golang实现的日志文件创建方法,通过获取当前执行文件的路径来确定日志文件的位置。文章详细展示了如何利用标准库如os、exec、path/filepath等进行文件操作和路径解析。
659

被折叠的 条评论
为什么被折叠?



