msgpack代替json防止丢失类型
nats-server系统服务只能使用sc命令注册

zap日志写入通道被覆盖

妙音 posted @ 2021年8月17日 20:00 in golang , 969 阅读
 

描述

 
实现了一个io.Writer接口,允许zap日志写入,传递给界面,出现了日志被覆盖、重复的情况。
 

原因

 
io.Writer的接口Write传入的[]byte真实类型是slice。通道传递slice时,用的是引用传递,所以真实数据有被覆盖的情况 
 

示例

 
* zap初始化
 
...
out = COut()
zapcore.NewCore(encoder, zapcore.AddSync(out), clevel),
...
 
* 自定义日志写入Channel
 
package logs

var _GlobalChanOutput = &ChanOutput{
outs: make([]chan *[]byte, 0),
}

/*---------------------------------------
全局函数
示例
logs.COut().AddOut(xx)
---------------------------------------*/

//全局ChanOutput
func COut() *ChanOutput{
return _GlobalChanOutput
}

/*---------------------------------------
log to channel
---------------------------------------*/

type ChanOutput struct{
outs []chan *[]byte
}

//io.Writer接口
func (c *ChanOutput) Write(p []byte) (n int, err error) {
count :=0

//数据复制(防止被覆盖)
_p := make([]byte, len(p))
copy(_p, p)

for _, out :=range c.outs{
select{
case out <- &_p:
count += 1
default:
}
}
return count, nil
}

func (c *ChanOutput) AddOut(out chan *[]byte) {
c.outs = append(c.outs, out)
}
 
* 读取日志
 
logOut := make(chan *[]byte, 1024)
logs.COut().AddOut(logOut)

pctx, pctxCancel := context.WithCancel(context.Background())
go func(ctx context.Context){
    select {
    case msg := <- logOut:
        fmt.Println(string(*msg))
    case <-ctx.Done():
        break
    }
}(pctx)
 
 
Avatar_small
Imamia Quran Academy 说:
2023年7月31日 05:11

Your blog provided us with valuable information to work with. Thanks a lot for sharing. I am from Imamia Quran Academy. Online Shia Quran Center provides you Shia Quranic education by the best scholars. Also, authentic Shia Quran translation and Shia Quran commentary are available for online users. Online users will be provided with the authentic experience of a regular Shia Quran Center without being physically present in certain premises. Join our Online Shia Quran Academy now, and Start your free 3 days Trial.


登录 *


loading captcha image...
(输入验证码)
or Ctrl+Enter