go-logging

nxlog4go

log4go

[log4go](go get github.com/jeanphorn/log4go)

  • Log to console
  • Log to file, support rotate by size or time
  • log to network, support tcp and udp
  • Support Json style configuration
  • Add Category for log
  • Classify your logs for different output and different usage.
  • Compatible with the old
  1. 安装 go get github.com/jeanphorn/log4go

  2. import log "github.com/jeanphorn/log4go"

  3. 配置文件样例

    {
    "console": {
    "enable": true, // wether output the log
    "level": "FINE" // log level: FINE, DEBUG, TRACE, INFO, WARNING,ERROR, CRITICAL
    },
    "files": [{
    "enable": true,
    "level": "DEBUG",
    "filename":"./test.log",
    "category": "Test", // different category log to different files
    "pattern": "[%D %T] [%C] [%L] (%S) %M" // log output formmat
    },{
    "enable": false,
    "level": "DEBUG",
    "filename":"rotate_test.log",
    "category": "TestRotate",
    "pattern": "[%D %T] [%C] [%L] (%S) %M",
    "rotate": true, // wether rotate the log
    "maxsize": "500M",
    "maxlines": "10K",
    "daily": true
    }],
    "sockets": [{
    "enable": false,
    "level": "DEBUG",
    "category": "TestSocket",
    "pattern": "[%D %T] [%C] [%L] (%S) %M",
    "addr": "127.0.0.1:12124",
    "protocol":"udp"
    }]
    }
  4. 使用样例

package main

import (
log "github.com/jeanphorn/log4go"
)

func main() {
// load config file, it's optional
// or log.LoadConfiguration("./example.json", "json")
// config file could be json or xml
log.LoadConfiguration("./example.json")

// 这里的 Test 是配置文件里面的 category 定义的
log.LOGGER("Test").Info("category Test info test ...")
log.LOGGER("Test").Info("category Test info test ... %d", 123)
log.LOGGER("Test").Info("category Test info test message: %s", "new test msg")
log.LOGGER("Test").Debug("category Test debug test ...")

// Other category not exist, test
log.LOGGER("Other").Debug("category Other debug test ...")

// socket log test
log.LOGGER("TestSocket").Debug("category TestSocket debug test ...")

// original log4go test
log.Info("nomal info test ...")
log.Debug("nomal debug test ...")

log.Close()
}
  1. 输出样例
    [2017/11/15 14:35:11 CST] [Test] [INFO] (main.main:15) category Test info test ...
    [2017/11/15 14:35:11 CST] [Test] [INFO] (main.main:16) category Test info test message: new test msg
    [2017/11/15 14:35:11 CST] [Test] [DEBG] (main.main:17) category Test debug test ...
    [2017/11/15 14:35:11 CST] [DEFAULT] [INFO] (main.main:26) nomal info test ...
    [2017/11/15 14:35:11 CST] [DEFAULT] [DEBG] (main.main:27) nomal debug test ...

logrus

logrus
不支持分割,配置也麻烦。想要同时输出到文件和控制台,不方便。

安装logrus

go get "github.com/Sirupsen/logrus"

使用样例

var logger = logrus.New()
logger.Error("Error accepting:" + err.Error())
logger.Fatal("Error listening: " + err.Error())

func initLog(path string) {

if val, err := PathExists(path + "/logs/"); err != nil {
logger.Error("log path not exist exception")
} else {
if val == false {
//0755->即用户具有读/写/执行权限,组用户和其它用户具有读写权限;
//0644->即用户具有读写权限,组用户和其它用户具有只读权限;
err := os.MkdirAll(path+"/logs/", 0755)
if err != nil {
fmt.Printf("%s", err)
} else {
fmt.Print("Create Directory OK!")
}
}
}

logFileName = path + "/logs/" + time.Now().Format("2006-01-02") + ".log"
// Create the logger file if doesn't exist. And append to it if it already exists.
// per-log should be less than 4k
f, err := os.OpenFile(logFileName, os.O_WRONLY|os.O_APPEND|os.O_CREATE, 0644)

//Logging to file
Formatter := new(logrus.TextFormatter)
Formatter.TimestampFormat = "2006-01-02 15:04:05"
Formatter.FullTimestamp = true
logrus.SetFormatter(Formatter)
if err != nil {
// Cannot open logger file. Logging to stderr
fmt.Println(err)
} else {
logger.Out = f
}
logger.Info("logger setup ok. gisHelper app started.")

// Fatal handlers
handler := func() {
// gracefully shutdown something...
logger.Error("FOUND a fatal error, app will exit.")
Email(logFileName)
}
logrus.RegisterExitHandler(handler)

}

func PathExists(path string) (bool, error) {
_, err := os.Stat(path)
if err == nil {
return true, nil
}
if os.IsNotExist(err) {
return false, nil
}
return false, err
}

发送邮件通知

func Email(logFileName string) error {
//logger:= logger.New()
//parameter"APPLICATION_NAME", "HOST", PORT, "FROM", "TO"
//首先开启smtp服务,最后两个参数是smtp的用户名和密码
hook, err := logrus_mail.NewMailAuthHook("xx server", "smtp.126.com", 25, "xx@126.com", "xx@126.com", "xxx", "xxx")
if err == nil {
logger.Hooks.Add(hook)
}
//生成*Entry
contextLogger := logger.WithFields(logrus.Fields{
"file": logFileName,
"content": "logfile.logger.zip www",
})
//设置时间戳和message
contextLogger.Time = time.Now()
contextLogger.Message = "gisHelper has error! " + logFileName
//只能发送Error,Fatal,Panic级别的log
contextLogger.Level = logrus.ErrorLevel

//使用Fire发送,包含时间戳,message
err = hook.Fire(contextLogger)
if err == nil {
logger.Error("发送错误日志邮件成功")
return nil
} else {
logger.Error("发送错误日志邮件失败")
fmt.Println("发送邮件失败:")
fmt.Println(err)
return errors.New("发送错误日志邮件失败")
}
}

遇到问题: unrecognized import path “golang.org/x/crypto/ssh/terminal
go get被墙了造成的。

解决方法:
引用
使用了shadowsock代理翻墙。

brew install polipo
首先要修改自动启动的配置文件
/usr/local/opt/polipo/homebrew.mxcl.polipo.plist,需要给polipo命令加上命令行参数 socksParentProxy=localhost:1080
<array>
<string>/usr/local/opt/polipo/bin/polipo</string>
<string>socksParentProxy=localhost:1080</string>
</array>

执行下面命令
ln -sfv /usr/local/opt/polipo/*.plist ~/Library/LaunchAgents
launchctl load ~/Library/LaunchAgents

polipo进程默认监听8123端口,在命令行执行下面命令,就可以使用代理了。
export http_proxy=http://localhost:8123
export https_proxy=http://localhost:8123
export ftp_proxy=http://localhost:8123

git config --globle http.proxy 127.0.0.1:8123
git config --globle https.proxy 127.0.0.1:8123