Commit 49627f30 authored by Tsaiilin's avatar Tsaiilin

logger: 日志文件及日志级别功能修改

1. 日志文件只保留run、error、trace三种,去除的类型除error外都会输入到run中
2. 日志级别从数字指定改变为使用 debug info error
   等指定,兼容之前的配置文件,如果无法识别的字符串会默认为 info 级别
3. debug 模式下日志会同时输出到控制台和文件,其他模式只输出到文件
parent aefd6aa8
...@@ -24,7 +24,7 @@ import ( ...@@ -24,7 +24,7 @@ import (
var ( var (
configure string configure string
logLevel int logLevel string
pprofPort int pprofPort int
natServer string natServer string
account string account string
...@@ -45,7 +45,7 @@ var ( ...@@ -45,7 +45,7 @@ var (
func init() { func init() {
rand.Seed(time.Now().UnixNano()) rand.Seed(time.Now().UnixNano())
flag.StringVar(&configure, "conf", "", "./majora -c path/to/your/majora.ini") flag.StringVar(&configure, "conf", "", "./majora -c path/to/your/majora.ini")
flag.IntVar(&logLevel, "log", 1, "log logLevel") flag.StringVar(&logLevel, "log", "info", "log logLevel")
flag.IntVar(&pprofPort, "pprof", 0, "enable pprof") flag.IntVar(&pprofPort, "pprof", 0, "enable pprof")
flag.StringVar(&natServer, "natServer", common.DefNatAddr, "natServer") flag.StringVar(&natServer, "natServer", common.DefNatAddr, "natServer")
flag.StringVar(&account, "account", "unknown", "account") flag.StringVar(&account, "account", "unknown", "account")
...@@ -57,7 +57,7 @@ func init() { ...@@ -57,7 +57,7 @@ func init() {
} }
func initial(cfg *model.Configure) { func initial(cfg *model.Configure) {
log.Init(cfg.LogLevel - 1) log.Init(cfg.LogLevel)
if cfg.PprofPort > 0 { if cfg.PprofPort > 0 {
go func() { go func() {
addr := fmt.Sprintf("127.0.0.1:%d", cfg.PprofPort) addr := fmt.Sprintf("127.0.0.1:%d", cfg.PprofPort)
......
...@@ -22,9 +22,9 @@ var ( ...@@ -22,9 +22,9 @@ var (
func (client *Client) handleHeartbeat(session getty.Session) { func (client *Client) handleHeartbeat(session getty.Session) {
go func() { go func() {
if _, _, err := session.WritePkg(HeartbeatPacket, common.HeartBeatTimeout); err != nil { if _, _, err := session.WritePkg(HeartbeatPacket, common.HeartBeatTimeout); err != nil {
log.Heart().Errorf("handleHeartbeat error %+v %v", err, session.IsClosed()) log.Error().Errorf("handleHeartbeat error %+v %v", err, session.IsClosed())
} else { } else {
log.Heart().Infof("handleHeartbeat success") log.Run().Infof("handleHeartbeat success")
} }
}() }()
} }
...@@ -49,7 +49,7 @@ func (client *Client) handleConnect(packet *protocol.MajoraPacket, session getty ...@@ -49,7 +49,7 @@ func (client *Client) handleConnect(packet *protocol.MajoraPacket, session getty
} }
hostPort := strings.Split(packet.Extra, ":") hostPort := strings.Split(packet.Extra, ":")
if len(packet.Extra) == 0 || len(hostPort) != 2 { if len(packet.Extra) == 0 || len(hostPort) != 2 {
log.Event().Errorf("[handleConnect] invalid extra %s", packet.Extra) log.Error().Errorf("[handleConnect] invalid extra %s", packet.Extra)
client.closeVirtualConnection(session, packet.SerialNumber) client.closeVirtualConnection(session, packet.SerialNumber)
return return
} }
...@@ -61,7 +61,7 @@ func (client *Client) handleConnect(packet *protocol.MajoraPacket, session getty ...@@ -61,7 +61,7 @@ func (client *Client) handleConnect(packet *protocol.MajoraPacket, session getty
conn, err := dialer.Dial(common.TCP, packet.Extra) conn, err := dialer.Dial(common.TCP, packet.Extra)
if err != nil { if err != nil {
log.Event().Errorf("[handleConnect] %d->connect to %s->%s", packet.SerialNumber, packet.Extra, err.Error()) log.Error().Errorf("[handleConnect] %d->connect to %s->%s", packet.SerialNumber, packet.Extra, err.Error())
client.closeVirtualConnection(session, packet.SerialNumber) client.closeVirtualConnection(session, packet.SerialNumber)
return return
} }
...@@ -74,17 +74,17 @@ func (client *Client) handleConnect(packet *protocol.MajoraPacket, session getty ...@@ -74,17 +74,17 @@ func (client *Client) handleConnect(packet *protocol.MajoraPacket, session getty
majoraPacket.SerialNumber = packet.SerialNumber majoraPacket.SerialNumber = packet.SerialNumber
majoraPacket.Extra = client.config.ClientID majoraPacket.Extra = client.config.ClientID
if session.IsClosed() { if session.IsClosed() {
log.Event().Warnf("[handleConnect] %d -> nat server is closed", packet.SerialNumber) log.Run().Warnf("[handleConnect] %d -> nat server is closed", packet.SerialNumber)
client.closeVirtualConnection(session, packet.SerialNumber) client.closeVirtualConnection(session, packet.SerialNumber)
return return
} }
if _, _, err := session.WritePkg(majoraPacket, 0); err != nil { if _, _, err := session.WritePkg(majoraPacket, 0); err != nil {
log.Event().Errorf("[handleConnect] %d->write pkg to nat server with error %s", packet.SerialNumber, log.Error().Errorf("[handleConnect] %d->write pkg to nat server with error %s", packet.SerialNumber,
err.Error()) err.Error())
client.closeVirtualConnection(session, packet.SerialNumber) client.closeVirtualConnection(session, packet.SerialNumber)
return return
} else { } else {
log.Event().Debugf("[handleConnect] %d->connect success to %s ", packet.SerialNumber, packet.Extra) log.Run().Debugf("[handleConnect] %d->connect success to %s ", packet.SerialNumber, packet.Extra)
traceSession.Recorder.RecordEvent(trace.ConnectEvent, fmt.Sprintf("connect success to %s", packet.Extra)) traceSession.Recorder.RecordEvent(trace.ConnectEvent, fmt.Sprintf("connect success to %s", packet.Extra))
} }
client.handleUpStream(tcpConn, packet, session) client.handleUpStream(tcpConn, packet, session)
...@@ -132,7 +132,7 @@ func (client *Client) handleTransfer(packet *protocol.MajoraPacket, session gett ...@@ -132,7 +132,7 @@ func (client *Client) handleTransfer(packet *protocol.MajoraPacket, session gett
load, ok := client.connStore.Load(packet.SerialNumber) load, ok := client.connStore.Load(packet.SerialNumber)
if !ok { if !ok {
log.Event().Errorf("[handleTransfer] %d-> can not find connection", packet.SerialNumber) log.Error().Errorf("[handleTransfer] %d-> can not find connection", packet.SerialNumber)
traceMessage := fmt.Sprintf("SerialNumber:%d -> can not find connection", packet.SerialNumber) traceMessage := fmt.Sprintf("SerialNumber:%d -> can not find connection", packet.SerialNumber)
traceRecorder.RecordErrorEvent(trace.TransferEvent, traceMessage, nil) traceRecorder.RecordErrorEvent(trace.TransferEvent, traceMessage, nil)
client.closeVirtualConnection(session, packet.SerialNumber) client.closeVirtualConnection(session, packet.SerialNumber)
...@@ -142,7 +142,7 @@ func (client *Client) handleTransfer(packet *protocol.MajoraPacket, session gett ...@@ -142,7 +142,7 @@ func (client *Client) handleTransfer(packet *protocol.MajoraPacket, session gett
cnt, err := conn.Write(packet.Data) cnt, err := conn.Write(packet.Data)
if err != nil { if err != nil {
log.Event().Errorf("[handleTransfer] %d->write to upstream fail for %s", packet.SerialNumber, err) log.Error().Errorf("[handleTransfer] %d->write to upstream fail for %s", packet.SerialNumber, err)
traceMessage := fmt.Sprintf("SerialNumber:%d -> write to upstream fail", packet.SerialNumber) traceMessage := fmt.Sprintf("SerialNumber:%d -> write to upstream fail", packet.SerialNumber)
traceRecorder.RecordErrorEvent(trace.TransferEvent, traceMessage, nil) traceRecorder.RecordErrorEvent(trace.TransferEvent, traceMessage, nil)
client.closeVirtualConnection(session, packet.SerialNumber) client.closeVirtualConnection(session, packet.SerialNumber)
...@@ -150,14 +150,14 @@ func (client *Client) handleTransfer(packet *protocol.MajoraPacket, session gett ...@@ -150,14 +150,14 @@ func (client *Client) handleTransfer(packet *protocol.MajoraPacket, session gett
} }
if cnt != len(packet.Data) { if cnt != len(packet.Data) {
log.Event().Errorf("[handleTransfer] %d-> write not all data for expect->%d/%d", log.Error().Errorf("[handleTransfer] %d-> write not all data for expect->%d/%d",
packet.SerialNumber, len(packet.Data), cnt) packet.SerialNumber, len(packet.Data), cnt)
traceMessage := fmt.Sprintf("SerialNumber: %d -> write not all data for expect -> %d/%d", packet.SerialNumber, len(packet.Data), cnt) traceMessage := fmt.Sprintf("SerialNumber: %d -> write not all data for expect -> %d/%d", packet.SerialNumber, len(packet.Data), cnt)
traceRecorder.RecordErrorEvent(trace.TransferEvent, traceMessage, nil) traceRecorder.RecordErrorEvent(trace.TransferEvent, traceMessage, nil)
client.closeVirtualConnection(session, packet.SerialNumber) client.closeVirtualConnection(session, packet.SerialNumber)
return return
} }
log.Event().Debugf("[handleTransfer] %d-> success %+v", packet.SerialNumber, string(packet.Data)) log.Error().Debugf("[handleTransfer] %d-> success %+v", packet.SerialNumber, string(packet.Data))
traceMessage := fmt.Sprintf("SerialNumber: %d -> complete transfer", packet.SerialNumber) traceMessage := fmt.Sprintf("SerialNumber: %d -> complete transfer", packet.SerialNumber)
traceRecorder.RecordEvent(trace.TransferEvent, traceMessage) traceRecorder.RecordEvent(trace.TransferEvent, traceMessage)
}(packet, session) }(packet, session)
...@@ -170,12 +170,12 @@ func (client *Client) handleUpStream(conn *net.TCPConn, packet *protocol.MajoraP ...@@ -170,12 +170,12 @@ func (client *Client) handleUpStream(conn *net.TCPConn, packet *protocol.MajoraP
log.Run().Errorf("%s SerialNumber: %s", err.Error(), packet.SerialNumber) log.Run().Errorf("%s SerialNumber: %s", err.Error(), packet.SerialNumber)
} }
traceRecorder.RecordEvent(trace.UpStreamEvent, fmt.Sprintf("SerialNumber:%d -> handleUpStream start", packet.SerialNumber)) traceRecorder.RecordEvent(trace.UpStreamEvent, fmt.Sprintf("SerialNumber:%d -> handleUpStream start", packet.SerialNumber))
log.Event().Debugf("[handleUpStream] %d-> handleUpStream start...", packet.SerialNumber) log.Run().Debugf("[handleUpStream] %d-> handleUpStream start...", packet.SerialNumber)
for { for {
buf := make([]byte, common.BufSize) // 4k buf := make([]byte, common.BufSize) // 4k
cnt, err := conn.Read(buf) cnt, err := conn.Read(buf)
if err != nil { if err != nil {
log.Event().Debugf("[handleUpStream] %d->read with error:%+v,l:%s->r:%s", log.Run().Debugf("[handleUpStream] %d->read with error:%+v,l:%s->r:%s",
packet.SerialNumber, err, conn.LocalAddr(), conn.RemoteAddr()) packet.SerialNumber, err, conn.LocalAddr(), conn.RemoteAddr())
recorderMessage := fmt.Sprintf("SerialNumber: %d -> read with l:%s->r:%s", recorderMessage := fmt.Sprintf("SerialNumber: %d -> read with l:%s->r:%s",
packet.SerialNumber, conn.LocalAddr(), conn.RemoteAddr()) packet.SerialNumber, conn.LocalAddr(), conn.RemoteAddr())
...@@ -190,13 +190,13 @@ func (client *Client) handleUpStream(conn *net.TCPConn, packet *protocol.MajoraP ...@@ -190,13 +190,13 @@ func (client *Client) handleUpStream(conn *net.TCPConn, packet *protocol.MajoraP
pack.SerialNumber = packet.SerialNumber pack.SerialNumber = packet.SerialNumber
if _, _, err := session.WritePkg(pack, 0); err != nil { if _, _, err := session.WritePkg(pack, 0); err != nil {
log.Event().Errorf("[handleUpStream] %d-> write to server fail %+v", packet.SerialNumber, err.Error()) log.Error().Errorf("[handleUpStream] %d-> write to server fail %+v", packet.SerialNumber, err.Error())
traceRecorder.RecordErrorEvent(trace.UpStreamEvent, traceRecorder.RecordErrorEvent(trace.UpStreamEvent,
fmt.Sprintf("SerialNumber: %d -> write to natServer failed", packet.SerialNumber), err) fmt.Sprintf("SerialNumber: %d -> write to natServer failed", packet.SerialNumber), err)
client.OnClose(session, conn, packet.SerialNumber) client.OnClose(session, conn, packet.SerialNumber)
break break
} else { } else {
log.Event().Debugf("[handleUpStream] %d->success %+v", packet.SerialNumber, string(packet.Data)) log.Run().Debugf("[handleUpStream] %d->success %+v", packet.SerialNumber, string(packet.Data))
traceRecorder.RecordEvent(trace.UpStreamEvent, traceRecorder.RecordEvent(trace.UpStreamEvent,
fmt.Sprintf("SerialNumber: %d write to natServer success", packet.SerialNumber)) fmt.Sprintf("SerialNumber: %d write to natServer success", packet.SerialNumber))
} }
...@@ -212,7 +212,7 @@ func (client *Client) handleDisconnectMessage(session getty.Session, packet *pro ...@@ -212,7 +212,7 @@ func (client *Client) handleDisconnectMessage(session getty.Session, packet *pro
log.Run().Errorf("%s SerialNumber: %s", err.Error(), packet.SerialNumber) log.Run().Errorf("%s SerialNumber: %s", err.Error(), packet.SerialNumber)
} }
traceRecorder.RecordEvent(trace.DisconnectEvent, fmt.Sprintf("SN: %d start close session", packet.SerialNumber)) traceRecorder.RecordEvent(trace.DisconnectEvent, fmt.Sprintf("SN: %d start close session", packet.SerialNumber))
log.Event().Debugf("[handleDisconnectMessage] %d->session closesd %v", packet.SerialNumber, session.IsClosed()) log.Run().Debugf("[handleDisconnectMessage] %d->session closesd %v", packet.SerialNumber, session.IsClosed())
if conn, ok := client.connStore.Load(packet.SerialNumber); ok { if conn, ok := client.connStore.Load(packet.SerialNumber); ok {
client.OnClose(session, conn.(net.Conn), packet.SerialNumber) client.OnClose(session, conn.(net.Conn), packet.SerialNumber)
} }
...@@ -221,7 +221,7 @@ func (client *Client) handleDisconnectMessage(session getty.Session, packet *pro ...@@ -221,7 +221,7 @@ func (client *Client) handleDisconnectMessage(session getty.Session, packet *pro
func (client *Client) handleControlMessage(_ *protocol.MajoraPacket) { func (client *Client) handleControlMessage(_ *protocol.MajoraPacket) {
go func() { go func() {
log.Event().Debugf("handleControlMessage") log.Run().Debugf("handleControlMessage")
}() }()
} }
...@@ -234,17 +234,17 @@ func (client *Client) handleDestroyMessage() { ...@@ -234,17 +234,17 @@ func (client *Client) handleDestroyMessage() {
func (client *Client) AddConnection(packet *protocol.MajoraPacket, conn *net.TCPConn, addr string) { func (client *Client) AddConnection(packet *protocol.MajoraPacket, conn *net.TCPConn, addr string) {
if _, ok := client.connStore.Load(packet.SerialNumber); ok { if _, ok := client.connStore.Load(packet.SerialNumber); ok {
log.Event().Errorf("[AddConnection] %d->error, has one", packet.SerialNumber) log.Error().Errorf("[AddConnection] %d->error, has one", packet.SerialNumber)
} }
client.connStore.Store(packet.SerialNumber, conn) client.connStore.Store(packet.SerialNumber, conn)
log.Event().Debugf("[AddConnection] %d->%s success", packet.SerialNumber, addr) log.Run().Debugf("[AddConnection] %d->%s success", packet.SerialNumber, addr)
} }
// OnClose 1. 本地缓存删除 2. 关闭连接 3. 通知natserver // OnClose 1. 本地缓存删除 2. 关闭连接 3. 通知natserver
func (client *Client) OnClose(natSession getty.Session, upStreamSession net.Conn, serialNumber int64) { func (client *Client) OnClose(natSession getty.Session, upStreamSession net.Conn, serialNumber int64) {
defer func() { defer func() {
if err := recover(); err != nil { if err := recover(); err != nil {
log.Event().Errorf("OnClose %+v", err) log.Error().Errorf("OnClose %+v", err)
} }
}() }()
traceRecorder, err := trace.GetTraceRecorderFromSession(natSession) traceRecorder, err := trace.GetTraceRecorderFromSession(natSession)
...@@ -264,9 +264,9 @@ func (client *Client) closeVirtualConnection(session getty.Session, serialNumber ...@@ -264,9 +264,9 @@ func (client *Client) closeVirtualConnection(session getty.Session, serialNumber
log.Run().Errorf("%s SerialNumber: %s", err.Error(), serialNumber) log.Run().Errorf("%s SerialNumber: %s", err.Error(), serialNumber)
} }
log.Event().Debugf("[closeVirtualConnection] %d->session closed %v", serialNumber, session.IsClosed()) log.Run().Debugf("[closeVirtualConnection] %d->session closed %v", serialNumber, session.IsClosed())
if session.IsClosed() { if session.IsClosed() {
log.Event().Warnf("[closeVirtualConnection] %d->session is closed", serialNumber) log.Run().Warnf("[closeVirtualConnection] %d->session is closed", serialNumber)
return return
} }
...@@ -275,7 +275,7 @@ func (client *Client) closeVirtualConnection(session getty.Session, serialNumber ...@@ -275,7 +275,7 @@ func (client *Client) closeVirtualConnection(session getty.Session, serialNumber
majoraPacket.SerialNumber = serialNumber majoraPacket.SerialNumber = serialNumber
majoraPacket.Extra = client.config.ClientID majoraPacket.Extra = client.config.ClientID
if allCnt, sendCnt, err := session.WritePkg(majoraPacket, 0); err != nil { if allCnt, sendCnt, err := session.WritePkg(majoraPacket, 0); err != nil {
log.Event().Warnf("[closeVirtualConnection] ->%d error %s session closed %v allCnt %d sendCnt %d", log.Run().Warnf("[closeVirtualConnection] ->%d error %s session closed %v allCnt %d sendCnt %d",
serialNumber, err.Error(), session.IsClosed(), allCnt, sendCnt) serialNumber, err.Error(), session.IsClosed(), allCnt, sendCnt)
traceRecorder.RecordErrorEvent(trace.DisconnectEvent, traceRecorder.RecordErrorEvent(trace.DisconnectEvent,
fmt.Sprintf("SN: %d -> send disconnect failed closed:%v allCnt %d sendCnt %d", fmt.Sprintf("SN: %d -> send disconnect failed closed:%v allCnt %d sendCnt %d",
...@@ -287,13 +287,13 @@ func (client *Client) closeVirtualConnection(session getty.Session, serialNumber ...@@ -287,13 +287,13 @@ func (client *Client) closeVirtualConnection(session getty.Session, serialNumber
func (client *Client) CloseAll(session getty.Session) { func (client *Client) CloseAll(session getty.Session) {
defer func() { defer func() {
if err := recover(); err != nil { if err := recover(); err != nil {
log.Event().Errorf("OnClose %+v", err) log.Error().Errorf("OnClose %+v", err)
} }
}() }()
client.connStore.Range(func(key, value interface{}) bool { client.connStore.Range(func(key, value interface{}) bool {
serialNumber := key.(int64) serialNumber := key.(int64)
conn, _ := value.(*net.TCPConn) conn, _ := value.(*net.TCPConn)
log.Event().Debugf("[CloseAll] close serialNumber -> %d", serialNumber) log.Run().Debugf("[CloseAll] close serialNumber -> %d", serialNumber)
client.OnClose(session, conn, serialNumber) client.OnClose(session, conn, serialNumber)
return true return true
}) })
......
...@@ -21,31 +21,31 @@ func (m *MajoraEventListener) OnOpen(session getty.Session) error { ...@@ -21,31 +21,31 @@ func (m *MajoraEventListener) OnOpen(session getty.Session) error {
extraMap[common.ExtrakeyUser] = m.client.config.Extra.Account extraMap[common.ExtrakeyUser] = m.client.config.Extra.Account
packet.Data = protocol.EncodeExtra(extraMap) packet.Data = protocol.EncodeExtra(extraMap)
if _, _, err := session.WritePkg(packet, time.Second*10); err != nil { if _, _, err := session.WritePkg(packet, time.Second*10); err != nil {
log.Event().Errorf("register to server error %+v", err) log.Error().Errorf("register to server error %+v", err)
return err return err
} }
log.Event().Infof("[OnOpen] registe to %s success", m.client.config.TunnelAddr) log.Run().Infof("[OnOpen] registe to %s success", m.client.config.TunnelAddr)
return nil return nil
} }
func (m *MajoraEventListener) OnClose(session getty.Session) { func (m *MajoraEventListener) OnClose(session getty.Session) {
log.Event().Errorf("OnClose-> session closed %v", session.IsClosed()) log.Error().Errorf("OnClose-> session closed %v", session.IsClosed())
m.client.CloseAll(session) m.client.CloseAll(session)
} }
func (m *MajoraEventListener) OnError(session getty.Session, err error) { func (m *MajoraEventListener) OnError(session getty.Session, err error) {
log.Event().Errorf("OnError %s", err.Error()) log.Error().Errorf("OnError %s", err.Error())
m.client.CloseAll(session) m.client.CloseAll(session)
} }
func (m *MajoraEventListener) OnCron(session getty.Session) { func (m *MajoraEventListener) OnCron(session getty.Session) {
log.Event().Warnf("thread:%d session closed %v", runtime.NumGoroutine(), session.IsClosed()) log.Run().Warnf("thread:%d session closed %v", runtime.NumGoroutine(), session.IsClosed())
m.client.Redial(session) m.client.Redial(session)
} }
func (m *MajoraEventListener) OnMessage(session getty.Session, input interface{}) { func (m *MajoraEventListener) OnMessage(session getty.Session, input interface{}) {
majoraPacket := input.(*protocol.MajoraPacket) majoraPacket := input.(*protocol.MajoraPacket)
log.Event().Debugf("receive packet from server %d->%s", majoraPacket.SerialNumber, majoraPacket.Ttype.ToString()) log.Run().Debugf("receive packet from server %d->%s", majoraPacket.SerialNumber, majoraPacket.Ttype.ToString())
switch majoraPacket.Ttype { switch majoraPacket.Ttype {
case protocol.TypeHeartbeat: case protocol.TypeHeartbeat:
......
...@@ -62,7 +62,7 @@ const ( ...@@ -62,7 +62,7 @@ const (
const ( const (
DefNatServerHost = "majora.virjar.com" DefNatServerHost = "majora.virjar.com"
DefNatServerPort = 5879 DefNatServerPort = 5879
DefNatAddr = "127.0.0.1:5879" DefNatAddr = "majora.virjar.com:5879"
PprofAddr = "127.0.0.1:6060" PprofAddr = "127.0.0.1:6060"
) )
......
...@@ -5,12 +5,10 @@ dns_server = 114.114.114.114:53 ...@@ -5,12 +5,10 @@ dns_server = 114.114.114.114:53
;local_ip = 192.168.0.100 ;local_ip = 192.168.0.100
;for performance pprof 0 is close ;for performance pprof 0 is close
pprof_port = 16666 pprof_port = 16666
log_level = 1 log_level = debug
reconn_interval = 5s reconn_interval = 5s
net_check_interval = 5s net_check_interval = 5s
net_check_url = https://www.baidu.com net_check_url = https://www.baidu.com[extra]
[extra]
account = superman account = superman
[redial] [redial]
......
...@@ -13,7 +13,6 @@ import ( ...@@ -13,7 +13,6 @@ import (
var ( var (
runLogger getty.Logger runLogger getty.Logger
eventLogger getty.Logger eventLogger getty.Logger
heartLogger getty.Logger
traceLogger *zap.Logger traceLogger *zap.Logger
errorLogger getty.Logger errorLogger getty.Logger
) )
...@@ -21,13 +20,12 @@ var ( ...@@ -21,13 +20,12 @@ var (
const ( const (
logDir = "./output/log/" logDir = "./output/log/"
run = "run.log" run = "run.log"
event = "event.log"
heart = "heart.log"
trace = "trace.log" trace = "trace.log"
err = "error.log" error = "error.log"
) )
func getLogWriter(path string) zapcore.WriteSyncer { // debug 模式下会将日志输出到控制台和文件,其他模式只输出到文件
func getLogWriter(path string, level zapcore.Level) zapcore.WriteSyncer {
lumberJackLogger := &lumberjack.Logger{ lumberJackLogger := &lumberjack.Logger{
Filename: path, Filename: path,
MaxSize: 10, MaxSize: 10,
...@@ -35,6 +33,9 @@ func getLogWriter(path string) zapcore.WriteSyncer { ...@@ -35,6 +33,9 @@ func getLogWriter(path string) zapcore.WriteSyncer {
MaxAge: 30, MaxAge: 30,
Compress: false, Compress: false,
} }
if level == zapcore.DebugLevel {
return zapcore.NewMultiWriteSyncer(zapcore.AddSync(os.Stdout), zapcore.AddSync(lumberJackLogger))
}
return zapcore.AddSync(lumberJackLogger) return zapcore.AddSync(lumberJackLogger)
} }
...@@ -53,7 +54,7 @@ func getCurPath() string { ...@@ -53,7 +54,7 @@ func getCurPath() string {
return filepath.Dir(exePath) return filepath.Dir(exePath)
} }
func Init(level int) { func Init(level string) {
curPath := getCurPath() curPath := getCurPath()
base := filepath.Join(curPath, logDir) base := filepath.Join(curPath, logDir)
if _, err := os.Stat(base); err != nil { if _, err := os.Stat(base); err != nil {
...@@ -70,20 +71,21 @@ func Init(level int) { ...@@ -70,20 +71,21 @@ func Init(level int) {
panic("invalid current path") panic("invalid current path")
} }
runLogger = initSugaredLogger(filepath.Join(base, run)) runLogger = initSugaredLogger(filepath.Join(base, run), level)
errorLogger = initSugaredLogger(filepath.Join(base, err)) errorLogger = initSugaredLogger(filepath.Join(base, error), level)
eventLogger = initSugaredLogger(filepath.Join(base, event)) traceLogger = initLogger(filepath.Join(base, trace), false, level)
heartLogger = initSugaredLogger(filepath.Join(base, heart))
traceLogger = initLogger(filepath.Join(base, trace), false)
// 框架的日志也输入到 run.log 中 // 框架的日志也输入到 run.log 中
getty.SetLogger(runLogger) getty.SetLogger(runLogger)
} }
func initLogger(path string, caller bool) *zap.Logger { func initLogger(path string, caller bool, level string) *zap.Logger {
encoder := getEncoder() zapLevel := zapcore.InfoLevel
writeSyncer := getLogWriter(path) // 忽略错误,如果传入的字符串有误默认 info 级别
_ = zapLevel.Set(level)
core := zapcore.NewCore(encoder, writeSyncer, zapcore.InfoLevel) encoder := getEncoder()
writeSyncer := getLogWriter(path, zapLevel)
core := zapcore.NewCore(encoder, writeSyncer, zapLevel)
if caller { if caller {
return zap.New(core, zap.AddCaller()) return zap.New(core, zap.AddCaller())
} else { } else {
...@@ -91,8 +93,8 @@ func initLogger(path string, caller bool) *zap.Logger { ...@@ -91,8 +93,8 @@ func initLogger(path string, caller bool) *zap.Logger {
} }
} }
func initSugaredLogger(path string) *zap.SugaredLogger { func initSugaredLogger(path string, level string) *zap.SugaredLogger {
logger := initLogger(path, true) logger := initLogger(path, true, level)
return logger.Sugar() return logger.Sugar()
} }
...@@ -100,14 +102,6 @@ func Run() getty.Logger { ...@@ -100,14 +102,6 @@ func Run() getty.Logger {
return runLogger return runLogger
} }
func Event() getty.Logger {
return eventLogger
}
func Heart() getty.Logger {
return heartLogger
}
func Trace() *zap.Logger { func Trace() *zap.Logger {
return traceLogger return traceLogger
} }
......
...@@ -20,7 +20,7 @@ type Extra struct { ...@@ -20,7 +20,7 @@ type Extra struct {
} }
type Configure struct { type Configure struct {
LogLevel int `ini:"log_level" json:"log_level"` LogLevel string `ini:"log_level" json:"log_level"`
PprofPort int `ini:"pprof_port" json:"pprof_port"` PprofPort int `ini:"pprof_port" json:"pprof_port"`
TunnelAddr string `ini:"tunnel_addr" json:"tunnel_addr"` TunnelAddr string `ini:"tunnel_addr" json:"tunnel_addr"`
DNSServer string `ini:"dns_server" json:"dns_server"` DNSServer string `ini:"dns_server" json:"dns_server"`
...@@ -39,7 +39,7 @@ const ( ...@@ -39,7 +39,7 @@ const (
func NewDefMajoraConf() *Configure { func NewDefMajoraConf() *Configure {
return &Configure{ return &Configure{
LogLevel: 1, LogLevel: "info",
PprofPort: 0, PprofPort: 0,
TunnelAddr: common.DefNatAddr, TunnelAddr: common.DefNatAddr,
DNSServer: common.DNSServer, //nolint:typecheck DNSServer: common.DNSServer, //nolint:typecheck
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment