douguachan2879 2015-10-30 20:17
浏览 138
已采纳

为什么Go的Logger无法关闭与syslog的连接?

I’m having trouble with a service i’m writing. I have it logging to syslog like this: http://technosophos.com/2013/09/14/using-gos-built-logger-log-syslog.html

but when i kill the service via CTRL-C something is leaving connections open to syslogd. I can’t see anyway to initiate a cleanup. What am I missing

e.g. syslog.Writer.Close() seems inaccessible to me but i can say the cleanup isn’t happening. I’m seeing connections stuck in a CLOSE_WAIT state and my syslogd starts bogging down and becoming uncooperative.

example:

package main

import (
    "github.com/davecgh/go-spew/spew" // DEBUG
    "log"
    "log/syslog"
    "os"
    "os/signal"
    "syscall"
)

func main() {
    logWriter, err := syslog.New(syslog.LOG_NOTICE, "mybrokenprog")
    spew.Dump(logWriter) // DEBUG
    spew.Dump(err)       // DEBUG
    if err == nil {
        log.SetOutput(logWriter)
    }

    chansigs := make(chan os.Signal, 1)
    signal.Notify(chansigs, os.Interrupt, syscall.SIGTERM, syscall.SIGKILL)
    log.Print("writing to syslog. waiting for shutdown signal")
    for {
        sig := <-chansigs // we just wait here for a signal to shutdown
        log.Print("signal received...shutting down")
        logWriter.Close() // but this throws the panic excerpted below
        if sig == os.Interrupt {
            os.Exit(0)
        }
        os.Exit(1)
    }
}

EDIT: the above code fixes the problem. see the comments. Rebooting to clear the stuck connections to syslog fixed the problem. Once they're there, they're persistent. Even OS X's instructions for retarting syslogd did not help. EDIT: this was the error: panic: runtime error: invalid memory address or nil pointer dereference [signal 0xb code=0x1 addr=0x0 pc=0xcb4fe]

goroutine 1 [running]: log/syslog.(*Writer).Close(0x0, 0x0, 0x0) /usr/local/Cellar/go/1.5.1/libexec/src/log/syslog/syslog.go:177 +0x10e main.main(0x3)

I've no doubt I'm doing it wrong. Just a newb who doesn't yet see where.

  • 写回答

1条回答 默认 最新

  • dongxiao0449 2016-01-22 15:24
    关注

    The problem was with the way the program was originally structured. The main() thread was exiting before the logging goroutine and thus orphaning connections. After refactoring to prevent that, the problem went away.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 微信小程序协议怎么写
  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看