Golang函数执行模板(log,耗时,panic)

         有些函数执行前后,需要加日志、记录耗时、还要处理panic,都是些重复性的东西。
 所以弄了个模板式的东西,碰到这类需求,直接把相关函数和参数,丢到run函数去就不用管了,省得浪费时间。

先上个调用例子:

//函数执行模板
//author: Xiong Chuan Liang
//date: 2015-3-19

package main

import (
	"fmt"
	"log"
	"os"

	"utils"
)

func main() {
	log.SetOutput(os.Stdout)

	w := utils.NewWorker()
	w.Run("myPrintf()", myPrintf, "aa", "bb")

}

func myPrintf(args ...interface{}) (int, error) {
	fmt.Println("myPrintf() begin.")
	for _, arg := range args {
		fmt.Println("args:", arg)
	}
	fmt.Println("myPrintf() end.")
	panic("尝试抛出panic错误")
	return 0, nil
}

/*
运行结果:

2015/03/19 13:49:30 [worker.Run()] 函数: myPrintf()
myPrintf() begin.
args: aa
args: bb
myPrintf() end.
2015/03/19 13:49:30 [worker.Run()] panic:
 myPrintf()
 尝试抛出panic错误
2015/03/19 13:49:30 [worker.Run()] 函数:myPrintf() 耗时:0.004000 秒

*/
   调用还是很方便的,传入函数和附带的参数即可.

   实现也很简单:

//函数执行模板
//author: Xiong Chuan Liang
//date: 2015-3-19

package utils

import (
	"fmt"
	"log"
	"time"
)

type workerFunc func(...interface{}) (int, error)

type worker struct {
}

func NewWorker() *worker {
	return &worker{}
}

func (w *worker) Run(name string, workerFunc workerFunc, args ...interface{}) (int, error) {

	now := time.Now()
	log.Println("[worker.Run()] 函数:", name)

	defer func() {
		if r := recover(); r != nil {
			log.Println("[worker.Run()] panic:\n", name, "\n", fmt.Sprint(r))
			w.elasped(name, now, time.Now())
		}
	}()

	ret, err := workerFunc(args...)
	w.elasped(name, now, time.Now())
	return ret, err
}

func (w *worker) elasped(name string, beginTime, endTime time.Time) {
	log.Printf("[worker.Run()] 函数:%s 耗时:%f 秒 \n",
		name, endTime.Sub(beginTime).Seconds())
}

    没多少东西,我也就处理func(...interface{}) (int, error)这类函数,其它没管了。


BLOG: http://blog.csdn.net/xcl168

MAIL: [email protected]

你可能感兴趣的:(golang,日志处理,panic,函数调用技巧,函数执行模板)