java项目中,经常使用log4j类库来记录项目的日志。
在golang中也找到个非常好用的日志组件,用起来和log4j一样。
配置log4jgo.xml进行日志配置
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<appender enabled="true" name="console">
<type>console</type>
<pattern>[%D %T] [%L] (%S) %M</pattern>
<!-- level is (:?FINEST|FINE|DEBUG|TRACE|INFO|WARNING|ERROR) -->
</appender>
<!-- 输出级别是info级别及以上的日志,下面的ref关联的两个appender没有filter设置,
所以,info及以上的日志都是会输出到这2个appender的 -->
<root>
<level>info</level>
<appender-ref ref="testfile" />
<appender-ref ref="logstash" />
</root>
</configuration>
import (
"github.com/gohutool/log4go"
"testing"
"time"
)
var logger = log4go.LoggerManager.GetLogger("com.hello")
func TestLoggerExample(t *testing.T) {
log4go.LoggerManager.InitWithXML("./example.xml")
logger.Info("hello")
logger.Info("hello")
time.Sleep(1 * time.Second)
logger.Error("hello")
time.Sleep(3 * time.Second)
}
控制台日志输出
=== RUN TestLoggerExample
[2022/04/06 15:17:59 CST 299] [INFO][com.hello] (github.com/gohutool/log4go/examples.TestLoggerExample:73) hello
[2022/04/06 15:17:59 CST 299] [INFO][com.hello] (github.com/gohutool/log4go/examples.TestLoggerExample:72) hello
[2022/04/06 15:18:00 CST 299] [EROR][com.hello] (github.com/gohutool/log4go/examples.TestLoggerExample:75) hello
--- PASS: TestLoggerExample (4.00s)
PASS
Debugger finished with the exit code 0
文件日志输出
可以支持console,file,socket
UDP日志支持
相关配置
<appender enabled="true" name="logstash"><!-- enabled=false means this logger won't actually be created -->
<type>socket</type>
<pattern>[%D %T %m] [%L][%l] (%S) %M</pattern>
<property name="endpoint">192.168.56.1:12124</property> <!-- recommend UDP broadcast -->
<property name="protocol">udp</property> <!-- tcp or udp -->
</appender>
TCP日志支持
相关配置
<appender enabled="true" name="logstash"><!-- enabled=false means this logger won't actually be created -->
<type>socket</type>
<pattern>[%D %T %m] [%L][%l] (%S) %M</pattern>
<property name="endpoint">192.168.56.1:12124</property> <!-- recommend UDP broadcast -->
<property name="protocol">tcp</property> <!-- tcp or udp -->
<property name="retry">-1</property> <!-- 断线重连,设置为负数,反复重连,设置为正数,重连测试后失败 -->
<property name="interval">30</property> <!-- 失败重连的间隔时间,默认30秒 -->
<property name="check">false</property> <!-- 启动日志是否检查连接成功,如果检查,不成功会失败 -->
</appender>
项目地址