本文整理汇总了Golang中logd/loglib.Info函数的典型用法代码示例。如果您正苦于以下问题:Golang Info函数的具体用法?Golang Info怎么用?Golang Info使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了Info函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。
示例1: reConnMongoDb
//用于检验session可用性并适时重连的routine func
//用于重连main session
func (this *MongoDbOutputer) reConnMongoDb() {
nPingFail := 0 //ping失败次数
reDial := false
for {
reDial = false
if this.session == nil {
//session未初始化
reDial = true
}else if(this.session.Ping() != nil) {
//session连接丢失
nPingFail++
if nPingFail == 3 {
reDial = true
}
}
if reDial {
nPingFail = 0
this.session = initMongoDbSession(this.mongosAddr)
if this.session == nil {
loglib.Info("session re-dial failed!")
}else{
loglib.Info("session re-dial success!")
}
}
time.Sleep(time.Second)
}
}
示例2: runParse
func (this *MongoDbOutputer) runParse( routineId int, wg *sync.WaitGroup) {
var session *mgo.Session
//routine一般都要copy或clone session,clone能保证一致性
if this.session != nil {
session = this.session.Clone()
}
defer func(){
if session != nil {
session.Close()
}
wg.Done()
loglib.Info(fmt.Sprintf("mongodb outputer parse routine %d quit", routineId))
}()
loglib.Info(fmt.Sprintf("mongodb outputer parse routine %d start", routineId))
for b := range this.buffer {
r, packId, date, err := this.extract(&b)
if err == nil {
if !this.isUpsert {
this.bulkSave(&session, r, packId, date, routineId)
}else{
this.upsert(&session, r, packId, date, routineId)
}
r.Close()
}
}
}
示例3: saveBufferInChan
func (s *Sender) saveBufferInChan() {
loglib.Info(fmt.Sprintf("sender%d begin to save pack in chan", s.id))
i := 0
for b := range s.memBuffer {
s.writeToFile(b)
i++
}
loglib.Info(fmt.Sprintf("sender%d saved num of pack in chan: %d", s.id, i))
}
示例4: sendData
func (s Sender) sendData(data []byte, conn *net.TCPConn) bool {
if len(data) == 0 {
return true
}
if conn == nil {
return false
}
/*
lenBuf := make([]byte, 4)
nData := len(data)
binary.PutUvarint(lenBuf, uint64(nData))
data = append(lenBuf, data...)
*/
st := time.Now()
packId := tcp_pack.GetPackId(data)
conn.SetDeadline(time.Now().Add(5 * time.Minute)) //设置超时
loglib.Info(fmt.Sprintf("sender%d start sending pack:%s length:%d", s.id, packId, len(data)))
n, err := conn.Write(data)
ed := time.Now()
loglib.Info(fmt.Sprintf("sender%d end sending pack:%s length:%d elapse:%s", s.id, packId, n, ed.Sub(st)))
lib.CheckError(err)
//写失败了就不用等应答了,肯定拿不到
if err == nil {
conn.SetReadDeadline(time.Now().Add(8 * time.Minute)) //设置超时
time1 := time.Now()
var temp []byte = make([]byte, 128)
count, err := conn.Read(temp)
if err == nil {
loglib.Info(fmt.Sprintf("sender%d get anwser data len:%d for pack:%s elapse:%s", s.id, count, packId, time.Now().Sub(time1)))
} else {
loglib.Info(fmt.Sprintf("sender%d get anwser data len:%d for pack:%s elapse:%s, error:%s", s.id, count, packId, time.Now().Sub(time1), err.Error()))
}
temp = temp[:count]
if string(temp) == "ok" { //发送成功
return true
} else if string(temp) == "wrong header" {
//包头错误,丢弃
loglib.Info(packId + " has wrong header, retry later!")
return false
} else { //发送失败
//报警
return false
}
} else {
loglib.Warning(fmt.Sprintf("write pack %s error:%s", packId, err.Error()))
}
return false
}
示例5: handleRegister
//处理注册请求
func (lr *LogReceiver) handleRegister(registerInfo map[string]string) map[string]string {
req, ok := registerInfo["req"]
m := map[string]string{"err": "-1", "msg": "unkown request <" + req + ">"}
ip, _ := registerInfo["ip"]
port, _ := registerInfo["port"]
hostname, _ := registerInfo["hostname"]
role, _ := registerInfo["role"]
addr := ip
loglib.Info(ip + ":" + port + " " + req)
if ok && (req == "register" || req == "unregister") {
if port != "" {
addr = ip + ":" + port
}
if req == "register" {
ret, err := lr.register(ip, port, role, hostname)
if ret {
lr.mutex.Lock()
lr.ipRoleMap[addr] = role
lr.mutex.Unlock()
m["err"] = "0"
m["msg"] = "success"
} else {
m["err"] = "1"
if err != nil {
m["msg"] = err.Error()
} else {
m["msg"] = "done"
}
}
} else if req == "unregister" {
ret, err := lr.unRegister(ip, port)
if ret {
lr.mutex.Lock()
delete(lr.ipRoleMap, addr)
lr.mutex.Unlock()
m["err"] = "0"
m["msg"] = "success"
} else {
m["err"] = "1"
if err != nil {
m["msg"] = err.Error()
} else {
m["msg"] = "done"
}
}
}
}
loglib.Info("[monitor] " + ip + ":" + port + " " + role + " " + req + ": " + m["msg"])
return m
}
示例6: doEtl
func (e *etlOutputer) doEtl(fkeyChan chan string, logDataDir string, etlDir string, etlDoneDir string, etlFailDir string, spiderList string, colsFile string, hostsList string, ipBlackList string, wg *sync.WaitGroup) {
defer func() {
if err := recover(); err != nil {
loglib.Error(fmt.Sprintf("doEtl() panic:%v", err))
}
wg.Done()
}()
loglib.Info("etl routine start")
for fkey := range fkeyChan {
sv := etl.NewFileSaver(colsFile, etlDir, fkey)
d := etl.NewDispatcher(sv, 6, hostsList, ipBlackList)
g := etl.NewGlobalHao123(spiderList, 100, 200, 8, d)
go g.Start(false)
fname := filepath.Join(logDataDir, fkey)
loglib.Info("start etl for " + fname)
err := g.ParseFile(fname)
g.Wait()
// etl success
// mark success
if err == nil {
//采用循环,增加打tag的成功率
for i := 0; i < 5; i++ {
fd, err := os.Create(filepath.Join(etlDoneDir, fkey))
if err == nil {
fd.Close()
loglib.Info("finish etl for " + fname)
break
} else {
loglib.Warning("mark etl done for " + fname + " failed! error: " + err.Error())
}
}
} else {
//采用循环,增加打tag的成功率
for i := 0; i < 5; i++ {
fd, err := os.Create(filepath.Join(etlFailDir, fkey))
if err == nil {
fd.Close()
loglib.Info("failed etl for " + fname)
break
} else {
loglib.Warning("mark etl fail for " + fname + " failed! error: " + err.Error())
}
}
}
}
loglib.Info("etl routine finish")
}
示例7: clearFootPrint
func (t *TcpReceiver) clearFootPrint(wg *sync.WaitGroup) {
defer wg.Done()
ch1 := make(chan bool) //用于安全退出
ch2 := time.After(time.Hour) //用于定时任务
go lib.HandleQuitSignal(func() {
ch1 <- true
})
loop:
for {
select {
//监听一个chan以便安全退出
case <-ch1:
break loop
case <-ch2:
//若这个case未执行完,而ch1已可读,select会保证这个case执行完
now := time.Now().Unix()
t.mutex.Lock()
for code, appear := range t.footPrint {
if now-appear.Time >= 86400 {
delete(t.footPrint, code)
}
}
t.saveFootPrint()
t.mutex.Unlock()
ch2 = time.After(time.Hour) //用于定时任务
}
}
loglib.Info("clear footprint quit!")
}
示例8: reloadFileCache
//载入cache文件列表
func (this *MongoDbOutputer) reloadFileCache() {
list := lib.GetFilelist(this.file_mem_folder_name)
for _,filename := range list {
loglib.Info("reloading:" + filename)
this.fileList.PushBack(filename)
}
}
示例9: Quit
func (this *WaitQuit) Quit() bool {
ret := false
select {
case <-this.ch:
loglib.Info(this.name + " safe quit.")
ret = true
case <-time.After(2 * time.Second):
loglib.Info(this.name + " quit timeout")
this.nTimeout++
if this.allowTimeout > 0 && this.nTimeout >= this.allowTimeout {
ret = true
}
}
return ret
}
示例10: reloadFileCache
//should be run by once
func (s *Sender) reloadFileCache() {
list := lib.GetFilelist(s.file_mem_folder_name)
for _, filename := range list {
// s.fileCacheList.PushBack(filename)
loglib.Info("reloading:" + filename)
fileList.PushBack(filename)
}
}
示例11: Start
func (t *TcpReceiver) Start() {
tcpAddr, err := net.ResolveTCPAddr("tcp4", t.receiveFromAddress)
lib.CheckError(err)
listener, err := net.ListenTCP("tcp", tcpAddr)
lib.CheckError(err)
wg := &sync.WaitGroup{}
wg.Add(1)
go t.clearFootPrint(wg)
//主routine信号处理
go lib.HandleQuitSignal(func() {
//接收到信号关闭listenner,此时Accept会马上返回一个nil 的conn
listener.Close()
loglib.Info("close tcp receiver's listener.")
})
defer func() {
if err := recover(); err != nil {
loglib.Error(fmt.Sprintf("tcp receiver panic:%v", err))
}
loglib.Info("wait connections finish...")
wg.Wait()
loglib.Info("all connections have been processed. quit.")
close(t.buffer) //关闭chan
t.saveFootPrint()
t.wq.AllDone()
}()
for {
conn, err := listener.Accept()
if conn == nil {
break
}
lib.CheckError(err)
wg.Add(1)
go t.handleConnnection(conn, wg)
}
}
示例12: extract
func (f *fileOutputer) extract(bp *bytes.Buffer) {
buf := make([]byte, 4)
bp.Read(buf)
l, _ := binary.Uvarint(buf)
headerLen := int(l)
//get pack header
buf = make([]byte, headerLen)
bp.Read(buf)
header := tcp_pack.ParseHeader(buf)
r, err := zlib.NewReader(bp)
if err != nil {
loglib.Error("zlib reader Error: " + err.Error())
} else {
lines, _ := strconv.Atoi(header["lines"])
done := false
if header["done"] == "1" {
done = true
}
f.ic.Add(header["ip"], header["hour"], header["id"], lines, done)
writerKey := header["ip"] + "_" + header["hour"]
fout := f.getWriter(f.writers, f.dataDir, writerKey)
//一头一尾写头信息,节省硬盘
buf = append(buf, '\n')
//fout.Write(buf)
nn, err := io.Copy(fout, r)
if err != nil {
loglib.Warning(fmt.Sprintf("save %s_%s_%s error:%s, saved:%d", header["ip"], header["hour"], header["id"], err, nn))
}
//fout.Write(buf)
//单独存一份header便于查数
fout = f.getWriter(f.headerWriters, f.headerDir, writerKey)
n, err := fout.Write(buf)
if err != nil {
loglib.Info(fmt.Sprintf("writer header %s %d %s", writerKey, n, err.Error()))
}
if done || time.Now().Unix() > f.checkTime.Unix() {
hourFinish, _ := f.ic.Check()
for ip, hours := range hourFinish {
for _, hour := range hours {
writerKey = ip + "_" + hour
}
}
f.closeWriters(f.writers)
f.closeWriters(f.headerWriters)
f.checkTime.Add(2 * time.Minute)
}
r.Close()
}
}
示例13: sendData2
func (s *Sender) sendData2(data []byte) bool {
result := s.sendData(data, s.connection.getConn())
//发送失败,tcp连接可能已经失效,重新建立tcp连接
if result == false {
s.connection.reconnect(s.connection.getConn())
*s.status = -1
loglib.Info(fmt.Sprintf("sender%d reconnected by sendData2(),status:%d", s.id, *s.status))
}
return result
}
示例14: pickPacks
//从公用的chan读pack到私有的chan,若私有chan已满则写入文件缓存
//保证公用chan不会阻塞
func (s *Sender) pickPacks() {
for buf := range s.sBuffer {
select {
case s.memBuffer <- buf:
break
default:
loglib.Info(fmt.Sprintf("sender%d mem buffer is full, total %d, pub chan:%d", s.id, len(s.memBuffer), len(s.sBuffer)))
s.writeToFile(buf)
}
}
close(s.memBuffer)
}
示例15: upsert
//更新插入,按字段更新
func (this *MongoDbOutputer) upsert(psession **mgo.Session, r io.Reader, packId string, date string, routineId int) {
nDiscard := 0
nCached := 0
nUpdated := 0
nInserted := 0
var coll *mgo.Collection = nil
if *psession != nil {
coll = (*psession).DB(this.db + date).C(this.collection) //按天分库
}
scanner := bufio.NewScanner(r)
for scanner.Scan() {
line := scanner.Text()
m := this.parseLogLine(line)
if len(m) > 0 {
selector := bson.M{ this.transactionIdKey: m[ this.transactionIdKey ] }
up := bson.M{"$set" : m}
info, err := this.upsertBson(coll, selector, up)
if err != nil {
this.cacheData(m, "upsert", date, routineId)
nCached++
//ping fail, re-connect, clone main session
if (*psession).Ping() != nil {
//refresh go-routine's session if possible
this.reCloneRoutineSession(psession)
if (*psession).Ping() == nil {
loglib.Info(fmt.Sprintf("parse routine %d re-conn", routineId))
}
}
}else{
nInserted++
nUpdated += info.Updated
}
}else{
nDiscard++
}
}
loglib.Info(fmt.Sprintf("save pack %s: inserted:%d, updated:%d, cached:%d, discard %d items", packId, nInserted, nUpdated, nCached, nDiscard))
}