Golang调试功能

时间:2018-07-17 20:21:22

标签: debugging go func

来自shell编程,我在其中使用了很多这样的功能:

log_action() {
case "${1}" in
'ERROR')
    EXIT_CODE="${3}"
    echo "[${1}] | $(date +"%T") | ${2} | Exiting (${EXIT_CODE})"
    exit ${EXIT_CODE};
;;
'WARNING')
    echo "[${1}] | $(date +"%T") | ${2} | Line: (${3})"
;;
'DEBUG')
    if [[ ${DEBUG} -eq "1" ]]; then {
    echo "[${1}] | $(date +"%T") | ${2} | ${3}"
    }; fi
;;
*)
    echo "[${1}] | $(date +"%T") | ${2} | ${3}"
;;
esac
}


log_action "WARNING" "Cannot Connect to MySQL Database" "${LINENO}")

现在,我开始学习golang,并且希望将所有bash脚本都转换为go。因此,我需要在golang中使用相同的函数,我尝试了以下操作:

func logHandler(t string, e string, l string) {
    switch t {
    case "warning":
        fmt.Println("WARNING")
    case "error":
        fmt.Println("ERROR")
    case "debug":
        fmt.Println("DEBUG |", e, l)
    }
}

logHandler("debug", "Test Function", "LineNumber")

但是我不知道如何在调用logHandler函数时获取当前的linenumber变量(LineNumber),并将其作为字符串或int传递给函数。

还有什么方法可以像在bash选项中那样在跟踪模式下运行go脚本:set -o xtrace?

我只是一个初学者,所以如果我做错了什么,请指出正确的方向。 谢谢。

1 个答案:

答案 0 :(得分:1)

这是一种优雅的方式。

我们将使用 runtime 软件包,方法如下:

package main

import (
    "fmt"
    "runtime"
)

func main() {
    logHandler("warning", "Test Function")
    logHandler("error", "Test Function")
    logHandler("debug", "Test Function")
}

func logHandler(t, e string) {
    switch t {
    case "warning":
        fmt.Println("WARNING |", e)
    case "error":
        fmt.Println("ERROR   |", e)
    case "debug":
        // 0 = This function
        // 1 = Function that called this function
        _, fn, line, _ := runtime.Caller(1)
        fmt.Printf("DEBUG   | %s:%d | %v\n", fn, line, e)
    }
}
  

输出:

WARNING | Test Function
ERROR   | Test Function
DEBUG   | /home/runner/main.go:11 | Test Function

Working example link


您基本上可以对所有人(警告和调试)

如果您有兴趣,还可以阅读有关 runtime package 的其他内容。


this great answerOneOfOne的启发。

相关问题