donglong7338 2016-10-19 15:13
浏览 48

将结果堆栈跟踪默认写入文件

I use logger in my program defined from pattern as below

var (
    logFile *os.File
    Info    *log.Logger
)

func init() {
    var err error
    logFile, err = os.OpenFile("/my/file/with.log", os.O_CREATE|os.O_APPEND|os.O_WRONLY, 0666)
    if err != nil {
        fmt.Printf("Cannot open log file error:%s. Program was terminated.", err)
        os.Exit(1)
    }
    Info = log.New(logFile,
        "INFO: ", log.Ldate|log.Ltime|log.Lshortfile)
 }

Now I would like write all information from stackTrace if these occured for example from panic() to my log file. Now if some gone was wrong all this information are print to console in my IDE, but if porgram works on server, I lose information if occured some null pointer, wrong pass argument to function, that's why I want write this information to log file. It is possible ?

  • 写回答

1条回答 默认 最新

  • donglin7383 2016-10-19 15:39
    关注

    Use syscall.Dup2 to link the opened file to the standard stream

    func main() {
       syscall.Dup2(int(logFile.Fd()), 2)
    }
    

    or create panic handler

    defer func() {
            err := recover()
            if err != nil {
                //...
            }
        }()
    
    评论

报告相同问题?

悬赏问题

  • ¥15 delta降尺度计算的一些细节,有偿
  • ¥15 Arduino红外遥控代码有问题
  • ¥15 数值计算离散正交多项式
  • ¥30 数值计算均差系数编程
  • ¥15 redis-full-check比较 两个集群的数据出错
  • ¥15 Matlab编程问题
  • ¥15 训练的多模态特征融合模型准确度很低怎么办
  • ¥15 kylin启动报错log4j类冲突
  • ¥15 超声波模块测距控制点灯,灯的闪烁很不稳定,经过调试发现测的距离偏大
  • ¥15 import arcpy出现importing _arcgisscripting 找不到相关程序