golang 杂记

用于记录golang开发中的常见示例。

Golang获得执行文件的当前路径

go使用logrus同时输出屏幕和文件日志

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
func InitLog() {
//设置输出样式,自带的只有两种样式logrus.JSONFormatter{}和logrus.TextFormatter{}
log.SetFormatter(&log.TextFormatter{})
log.SetOutput(os.Stdout)
//设置output,默认为stderr,可以为任何io.Writer,比如文件*os.File
file, err := os.OpenFile("checkemstools.log", os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0666)
writers := []io.Writer{
file,
os.Stdout}
//同时写文件和屏幕
fileAndStdoutWriter := io.MultiWriter(writers...)
if err == nil {
log.SetOutput(fileAndStdoutWriter)
} else {
log.Info("failed to log to file.")
}
//设置最低loglevel
log.SetLevel(log.InfoLevel)
}

gin自定义请求响应日志格式

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
func main() {
router := gin.New()

// LoggerWithFormatter 中间件会将日志写入 gin.DefaultWriter
// By default gin.DefaultWriter = os.Stdout
router.Use(gin.LoggerWithFormatter(func(param gin.LogFormatterParams) string {

// 你的自定义格式
return fmt.Sprintf("%s - [%s] \"%s %s %s %d %s \"%s\" %s\"\n",
param.ClientIP,
param.TimeStamp.Format(time.RFC1123),
param.Method,
param.Path,
param.Request.Proto,
param.StatusCode,
param.Latency,
param.Request.UserAgent(),
param.ErrorMessage,
)
}))
router.Use(gin.Recovery())

router.GET("/ping", func(c *gin.Context) {
c.String(200, "pong")
})
router.Run(":8080")
}

实现了接口方法的结构体可以赋值给该接口

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
type Formatter interface {
Format(*Entry) ([]byte, error)
}

type Entry struct {
// err may contain a field formatting error
err string
}

type myFormat struct {}

func (m *myFormat) Format(*Entry) ([]byte, error){
return []byte{'a'}, nil
}

func main(){
var mf Formatter = new(myFormat)
}

获取运行是文件路劲,行号,函数名

1
2
3
4
5
6
7
8
9
10
func(frame *runtime.Frame) string {
funcInfo := runtime.FuncForPC(frame.PC)
if funcInfo == nil {
return "error during runtime.FuncForPC"
}
fullPath, line := funcInfo.FileLine(frame.PC)
funcNamePath := funcInfo.Name()
_, funcName := filepath.Split(funcNamePath)
return fmt.Sprintf(" [%v:%v:%v]", filepath.Base(fullPath), funcName, line)
}
-------------本文结束感谢您的阅读-------------