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 (
var (
configure string
logLevel int
logLevel string
pprofPort int
natServer string
account string
......@@ -45,7 +45,7 @@ var (
func init() {
rand.Seed(time.Now().UnixNano())
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.StringVar(&natServer, "natServer", common.DefNatAddr, "natServer")
flag.StringVar(&account, "account", "unknown", "account")
......@@ -57,7 +57,7 @@ func init() {
}
func initial(cfg *model.Configure) {
log.Init(cfg.LogLevel - 1)
log.Init(cfg.LogLevel)
if cfg.PprofPort > 0 {
go func() {
addr := fmt.Sprintf("127.0.0.1:%d", cfg.PprofPort)
......
......@@ -22,9 +22,9 @@ var (
func (client *Client) handleHeartbeat(session getty.Session) {
go func() {
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 {
log.Heart().Infof("handleHeartbeat success")
log.Run().Infof("handleHeartbeat success")
}
}()
}
......@@ -49,7 +49,7 @@ func (client *Client) handleConnect(packet *protocol.MajoraPacket, session getty
}
hostPort := strings.Split(packet.Extra, ":")
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)
return
}
......@@ -61,7 +61,7 @@ func (client *Client) handleConnect(packet *protocol.MajoraPacket, session getty
conn, err := dialer.Dial(common.TCP, packet.Extra)
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)
return
}
......@@ -74,17 +74,17 @@ func (client *Client) handleConnect(packet *protocol.MajoraPacket, session getty
majoraPacket.SerialNumber = packet.SerialNumber
majoraPacket.Extra = client.config.ClientID
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)
return
}
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())
client.closeVirtualConnection(session, packet.SerialNumber)
return
} 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))
}
client.handleUpStream(tcpConn, packet, session)
......@@ -132,7 +132,7 @@ func (client *Client) handleTransfer(packet *protocol.MajoraPacket, session gett
load, ok := client.connStore.Load(packet.SerialNumber)
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)
traceRecorder.RecordErrorEvent(trace.TransferEvent, traceMessage, nil)
client.closeVirtualConnection(session, packet.SerialNumber)
......@@ -142,7 +142,7 @@ func (client *Client) handleTransfer(packet *protocol.MajoraPacket, session gett
cnt, err := conn.Write(packet.Data)
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)
traceRecorder.RecordErrorEvent(trace.TransferEvent, traceMessage, nil)
client.closeVirtualConnection(session, packet.SerialNumber)
......@@ -150,14 +150,14 @@ func (client *Client) handleTransfer(packet *protocol.MajoraPacket, session gett
}
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)
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)
client.closeVirtualConnection(session, packet.SerialNumber)
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)
traceRecorder.RecordEvent(trace.TransferEvent, traceMessage)
}(packet, session)
......@@ -170,12 +170,12 @@ func (client *Client) handleUpStream(conn *net.TCPConn, packet *protocol.MajoraP
log.Run().Errorf("%s SerialNumber: %s", err.Error(), 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 {
buf := make([]byte, common.BufSize) // 4k
cnt, err := conn.Read(buf)
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())
recorderMessage := fmt.Sprintf("SerialNumber: %d -> read with l:%s->r:%s",
packet.SerialNumber, conn.LocalAddr(), conn.RemoteAddr())
......@@ -190,13 +190,13 @@ func (client *Client) handleUpStream(conn *net.TCPConn, packet *protocol.MajoraP
pack.SerialNumber = packet.SerialNumber
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,
fmt.Sprintf("SerialNumber: %d -> write to natServer failed", packet.SerialNumber), err)
client.OnClose(session, conn, packet.SerialNumber)
break
} 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,
fmt.Sprintf("SerialNumber: %d write to natServer success", packet.SerialNumber))
}
......@@ -212,7 +212,7 @@ func (client *Client) handleDisconnectMessage(session getty.Session, packet *pro
log.Run().Errorf("%s SerialNumber: %s", err.Error(), 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 {
client.OnClose(session, conn.(net.Conn), packet.SerialNumber)
}
......@@ -221,7 +221,7 @@ func (client *Client) handleDisconnectMessage(session getty.Session, packet *pro
func (client *Client) handleControlMessage(_ *protocol.MajoraPacket) {
go func() {
log.Event().Debugf("handleControlMessage")
log.Run().Debugf("handleControlMessage")
}()
}
......@@ -234,17 +234,17 @@ func (client *Client) handleDestroyMessage() {
func (client *Client) AddConnection(packet *protocol.MajoraPacket, conn *net.TCPConn, addr string) {
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)
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
func (client *Client) OnClose(natSession getty.Session, upStreamSession net.Conn, serialNumber int64) {
defer func() {
if err := recover(); err != nil {
log.Event().Errorf("OnClose %+v", err)
log.Error().Errorf("OnClose %+v", err)
}
}()
traceRecorder, err := trace.GetTraceRecorderFromSession(natSession)
......@@ -264,9 +264,9 @@ func (client *Client) closeVirtualConnection(session getty.Session, 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() {
log.Event().Warnf("[closeVirtualConnection] %d->session is closed", serialNumber)
log.Run().Warnf("[closeVirtualConnection] %d->session is closed", serialNumber)
return
}
......@@ -275,7 +275,7 @@ func (client *Client) closeVirtualConnection(session getty.Session, serialNumber
majoraPacket.SerialNumber = serialNumber
majoraPacket.Extra = client.config.ClientID
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)
traceRecorder.RecordErrorEvent(trace.DisconnectEvent,
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
func (client *Client) CloseAll(session getty.Session) {
defer func() {
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 {
serialNumber := key.(int64)
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)
return true
})
......
......@@ -21,31 +21,31 @@ func (m *MajoraEventListener) OnOpen(session getty.Session) error {
extraMap[common.ExtrakeyUser] = m.client.config.Extra.Account
packet.Data = protocol.EncodeExtra(extraMap)
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
}
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
}
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)
}
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)
}
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)
}
func (m *MajoraEventListener) OnMessage(session getty.Session, input interface{}) {
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 {
case protocol.TypeHeartbeat:
......
......@@ -62,7 +62,7 @@ const (
const (
DefNatServerHost = "majora.virjar.com"
DefNatServerPort = 5879
DefNatAddr = "127.0.0.1:5879"
DefNatAddr = "majora.virjar.com:5879"
PprofAddr = "127.0.0.1:6060"
)
......
......@@ -5,12 +5,10 @@ dns_server = 114.114.114.114:53
;local_ip = 192.168.0.100
;for performance pprof 0 is close
pprof_port = 16666
log_level = 1
log_level = debug
reconn_interval = 5s
net_check_interval = 5s
net_check_url = https://www.baidu.com
[extra]
net_check_url = https://www.baidu.com[extra]
account = superman
[redial]
......
......@@ -13,7 +13,6 @@ import (
var (
runLogger getty.Logger
eventLogger getty.Logger
heartLogger getty.Logger
traceLogger *zap.Logger
errorLogger getty.Logger
)
......@@ -21,13 +20,12 @@ var (
const (
logDir = "./output/log/"
run = "run.log"
event = "event.log"
heart = "heart.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{
Filename: path,
MaxSize: 10,
......@@ -35,6 +33,9 @@ func getLogWriter(path string) zapcore.WriteSyncer {
MaxAge: 30,
Compress: false,
}
if level == zapcore.DebugLevel {
return zapcore.NewMultiWriteSyncer(zapcore.AddSync(os.Stdout), zapcore.AddSync(lumberJackLogger))
}
return zapcore.AddSync(lumberJackLogger)
}
......@@ -53,7 +54,7 @@ func getCurPath() string {
return filepath.Dir(exePath)
}
func Init(level int) {
func Init(level string) {
curPath := getCurPath()
base := filepath.Join(curPath, logDir)
if _, err := os.Stat(base); err != nil {
......@@ -70,20 +71,21 @@ func Init(level int) {
panic("invalid current path")
}
runLogger = initSugaredLogger(filepath.Join(base, run))
errorLogger = initSugaredLogger(filepath.Join(base, err))
eventLogger = initSugaredLogger(filepath.Join(base, event))
heartLogger = initSugaredLogger(filepath.Join(base, heart))
traceLogger = initLogger(filepath.Join(base, trace), false)
runLogger = initSugaredLogger(filepath.Join(base, run), level)
errorLogger = initSugaredLogger(filepath.Join(base, error), level)
traceLogger = initLogger(filepath.Join(base, trace), false, level)
// 框架的日志也输入到 run.log 中
getty.SetLogger(runLogger)
}
func initLogger(path string, caller bool) *zap.Logger {
encoder := getEncoder()
writeSyncer := getLogWriter(path)
func initLogger(path string, caller bool, level string) *zap.Logger {
zapLevel := zapcore.InfoLevel
// 忽略错误,如果传入的字符串有误默认 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 {
return zap.New(core, zap.AddCaller())
} else {
......@@ -91,8 +93,8 @@ func initLogger(path string, caller bool) *zap.Logger {
}
}
func initSugaredLogger(path string) *zap.SugaredLogger {
logger := initLogger(path, true)
func initSugaredLogger(path string, level string) *zap.SugaredLogger {
logger := initLogger(path, true, level)
return logger.Sugar()
}
......@@ -100,14 +102,6 @@ func Run() getty.Logger {
return runLogger
}
func Event() getty.Logger {
return eventLogger
}
func Heart() getty.Logger {
return heartLogger
}
func Trace() *zap.Logger {
return traceLogger
}
......
......@@ -20,7 +20,7 @@ type Extra 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"`
TunnelAddr string `ini:"tunnel_addr" json:"tunnel_addr"`
DNSServer string `ini:"dns_server" json:"dns_server"`
......@@ -39,7 +39,7 @@ const (
func NewDefMajoraConf() *Configure {
return &Configure{
LogLevel: 1,
LogLevel: "info",
PprofPort: 0,
TunnelAddr: common.DefNatAddr,
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