当前位置: 首页>>代码示例>>Golang>>正文


Golang tail.TailFile函数代码示例

本文整理汇总了Golang中github.com/ActiveState/tail.TailFile函数的典型用法代码示例。如果您正苦于以下问题:Golang TailFile函数的具体用法?Golang TailFile怎么用?Golang TailFile使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。


在下文中一共展示了TailFile函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。

示例1: ReadFile

func ReadFile(filename string, stream chan<- string) {
	seekinfo := tail.SeekInfo{Whence: os.SEEK_END}
	t, _ := tail.TailFile(filename, tail.Config{Follow: true, Location: &seekinfo})
	for line := range t.Lines {
		stream <- line.Text + "\n"
	}
}
开发者ID:way-2-go,项目名称:gostream,代码行数:7,代码来源:gostream.go

示例2: runAgent

func runAgent(aSender sender, fileToTail string) {
	// prepare filter
	compileFilters()

	if len(fileToTail) > 0 {
		// keep watching for the file
		for {
			if t, err := tail.TailFile(fileToTail, tail.Config{Follow: true, MustExist: true}); err != nil {
				fmt.Printf("Error in receive: %v\n", err)
			} else {
				//filterAndSend(zmqSender, t.Lines)
				filterAndBulkSend(aSender, t.Lines)
			}

			// the reopen option is not working in the TailFile config. Let's reopen after 1s in case of file lost
			timer := time.NewTimer(time.Second * 1)
			<-timer.C
		}
	} else { //read from stdin
		fmt.Printf("Reading from STDIN")
		lines := make(chan *tail.Line)
		go func(lines chan *tail.Line) {
			bio := bufio.NewReader(os.Stdin)
			for {
				line, _, err := bio.ReadLine()
				lines <- &(tail.Line{string(line), time.Now(), err})
			}
		}(lines)

		filterAndBulkSend(aSender, lines)
	}

}
开发者ID:dbenque,项目名称:maglogparser,代码行数:33,代码来源:magLogParserAgent.go

示例3: NewFile

func NewFile(fpath string) (*File, error) {
	seekInfo := &tail.SeekInfo{Offset: 0, Whence: 2}
	file := &File{}
	var err error
	file.Tail, err = tail.TailFile(fpath, tail.Config{Follow: true, ReOpen: true, Location: seekInfo})
	return file, err
}
开发者ID:pronix,项目名称:logsend,代码行数:7,代码来源:files.go

示例4: tailLog

func tailLog(cs chan []byte, filePath string, w io.Writer, closechan chan bool) {
	t, _ := tail.TailFile(filePath, tail.Config{Follow: true})
	for line := range t.Lines {
		fmt.Fprintf(w, line.Text)
	}
	closechan <- true
}
开发者ID:rajthilakmca,项目名称:gulp,代码行数:7,代码来源:actions.go

示例5: main

func main() {
	var token = flag.String("token", "nil", "log token")
	var logfile = flag.String("logfile", "/tmp/foo.txt", "log file to follow")
	var seekInfoOnStart = &tail.SeekInfo{Offset: 0, Whence: os.SEEK_END}

	flag.Parse()

	fmt.Println("using token: ", *token)

	if _, err := os.Stat(*logfile); os.IsNotExist(err) {
		fmt.Printf("no such file or directory: %s\n", *logfile)
		return
	}

	le, err := le_go.Connect(*token) // replace with token
	if err != nil {
		panic(err)
	}

	defer le.Close()
	t, err := tail.TailFile(*logfile, tail.Config{Follow: true, ReOpen: true, Location: seekInfoOnStart, Logger: tail.DiscardingLogger})
	if err == nil {
		for line := range t.Lines {
			le.Println(line.Text)
		}
	}
}
开发者ID:jcftang,项目名称:logentries-go,代码行数:27,代码来源:follower-single-token.go

示例6: tailFile

func tailFile(ctx context.Context, file string, dest *os.File) {
	defer wg.Done()
	t, err := tail.TailFile(file, tail.Config{
		Follow: true,
		ReOpen: true,
		//Poll:   true,
		Logger: tail.DiscardingLogger,
	})
	if err != nil {
		log.Fatalf("unable to tail %s: %s", "foo", err)
	}

	// main loop
	for {
		select {
		// if the channel is done, then exit the loop
		case <-ctx.Done():
			t.Stop()
			tail.Cleanup()
			return
		// get the next log line and echo it out
		case line := <-t.Lines:
			fmt.Fprintln(dest, line.Text)
		}
	}
}
开发者ID:dockware,项目名称:dockerize,代码行数:26,代码来源:tail.go

示例7: tailOne

// Tails a single file
func tailOne(file string, excludePatterns []*regexp.Regexp, logger *syslog.Logger, wr *WorkerRegistry, severity syslog.Priority, facility syslog.Priority, poll bool) {
	defer wr.Remove(file)
	wr.Add(file)
	tailConfig := tail.Config{ReOpen: true, Follow: true, MustExist: true, Poll: poll, Location: &tail.SeekInfo{0, os.SEEK_END}}

	t, err := tail.TailFile(file, tailConfig)

	if err != nil {
		log.Errorf("%s", err)
		return
	}

	for line := range t.Lines {
		if !matchExps(line.Text, excludePatterns) {
			logger.Packets <- syslog.Packet{
				Severity: severity,
				Facility: facility,
				Time:     time.Now(),
				Hostname: logger.ClientHostname,
				Tag:      path.Base(file),
				Message:  line.Text,
			}
			log.Tracef("Forwarding: %s", line.Text)
		} else {
			log.Tracef("Not Forwarding: %s", line.Text)
		}

	}

	log.Errorf("Tail worker executed abnormally")
}
开发者ID:BrendanThompson,项目名称:remote_syslog2,代码行数:32,代码来源:remote_syslog.go

示例8: main

func main() {
	flag.Parse()
	config := loadConfig()

	// Determine the parsing function for this log file
	parserFn, err := parsingFunctionForType(config.Parser)
	if err != nil {
		log.Fatal(err)
	}

	// Connect to BigQuery & create tables
	tabledataService := connectToBigquery(&config)

	// Start tailing the log file & parsing the entries
	seek := tail.SeekInfo{Offset: 0, Whence: 2}
	t, _ := tail.TailFile(config.LogFilename, tail.Config{
		Location: &seek,
		Follow:   true,
		Logger:   tail.DiscardingLogger,
	})

	for line := range t.Lines {
		parsed, err := parserFn(config.Host, strings.Replace(line.Text, "\\", "", -1))
		if err == nil {
			go stream(&config, tabledataService, parsed)
		}
	}
}
开发者ID:mjp,项目名称:logstalker,代码行数:28,代码来源:main.go

示例9: main

// MAIN
func main() {
	parseCommandLine()

	t, err := tail.TailFile(accessLog, tail.Config{Follow: true, ReOpen: true, MustExist: false})
	if err != nil {
		panic(err)
	}

	hits := make(chan *loghit.LogHit)
	defer close(hits)
	errors := make(chan error)
	defer close(errors)

	for i := 0; i < *parserRoutines; i++ {
		go parseLines(t.Lines, hits, errors)
	}

	for i := 0; i < *posterRoutines; i++ {
		go postStats(*statPrefix, ezKey, hits)
	}

	logWriter, err := syslog.New(syslog.LOG_ERR, "nginx2stathat")
	if err != nil {
		panic(err)
	}

	for err := range errors {
		logWriter.Err(err.Error())
	}
}
开发者ID:hgfischer,项目名称:nginx2stathat,代码行数:31,代码来源:nginx2stathat.go

示例10: tailFile

func tailFile(path string) {
	mkfifo(path)
	t, _ := tail.TailFile(path, tail.Config{Follow: true})

	for line := range t.Lines {
		log.Info(line.Text)
	}
}
开发者ID:CloudSide,项目名称:deis,代码行数:8,代码来源:boot.go

示例11: main

func main() {
	hsLogFile := flag.String("log", "no-log-file-specified", "The file path to the Hearthstone log file.")
	hsUsername := flag.String("username", "no-username-specified", "Your battlenet ID (without the #1234).")

	flag.Parse()

	createManaUpdateParser(*hsUsername)
	log, _ := tail.TailFile(*hsLogFile, tail.Config{Follow: true})

	gs := GameState{}
	gs.resetGameState()
	solutionChan := make(chan *DecisionTreeNode)
	seenUsername := false
	var deepestSolution, shortestSolution *DecisionTreeNode
	var abortChan *chan time.Time
	for {
		select {
		case line := <-log.Lines:
			if !seenUsername && strings.Contains(line.Text, *hsUsername) {
				seenUsername = true
			}
			if turnStart, somethingHappened := ParseHearthstoneLogLine(line.Text, &gs); turnStart || somethingHappened {
				if !seenUsername {
					fmt.Println("WARN: Waiting to see --username before looking for solutions.")
					continue
				}
				//fmt.Println("It is the start of turn for:", gs.LastManaAdjustPlayer)
				if abortChan != nil {
					*abortChan <- time.Now()
					abortChan = nil
					deepestSolution = nil
					shortestSolution = nil
				}
				newAbortChan := make(chan time.Time, 1)
				abortChan = &newAbortChan
				go WalkDecisionTree(gs.DeepCopy(), solutionChan, newAbortChan)
			}
		case solution := <-solutionChan:
			if deepestSolution == nil {
				deepestSolution = solution
				shortestSolution = solution
				fmt.Println("INFO: Solution found")
				prettyPrintDecisionTreeNode(solution)
			}
			if len(deepestSolution.Moves) < len(solution.Moves) {
				deepestSolution = solution
				fmt.Println("INFO: Another solution with more BM:")
				prettyPrintDecisionTreeNode(solution)
			}
			if len(shortestSolution.Moves) > len(solution.Moves) {
				shortestSolution = solution
				fmt.Println("INFO: Another solution with fewer steps:")
				prettyPrintDecisionTreeNode(solution)
			}
		}
	}
}
开发者ID:DrTall,项目名称:hearthstone-helper,代码行数:57,代码来源:hearthstone.go

示例12: fileToTail

func fileToTail(fileName string) *tail.Tail {
	tail, err := tail.TailFile(fileName, tail.Config{
		Follow: true,
		ReOpen: true,
	})
	if err != nil {
		log.Fatal(err)
	}
	return tail
}
开发者ID:kf8a,项目名称:raingauge-loader,代码行数:10,代码来源:main.go

示例13: liveStatus

func liveStatus(c web.C, w http.ResponseWriter, r *http.Request) {
	log.Printf("Running Task Id => %s\n", c.URLParams["id"])
	id, err := strconv.ParseInt(c.URLParams["id"], 10, 32)
	if err != nil {
		http.Error(w, "Invalid id", http.StatusInternalServerError)
		return
	}

	runningTask := gSubakoCtx.RunningTasks.Get(int(id))
	if runningTask == nil {
		http.Error(w, "task is nil", http.StatusInternalServerError)
		return
	}

	w.Header().Set("Content-Type", "text/plain; charset=utf-8")
	w.Header().Set("X-Content-Type-Options", "nosniff") // important

	w.WriteHeader(http.StatusOK)

	flusher, ok := w.(http.Flusher)
	if !ok {
		// ERROR
		http.Error(w, "Failed to cast to http.Flusher", http.StatusInternalServerError)
	}

	t, err := tail.TailFile(runningTask.LogFilePath, tail.Config{Follow: true})
	if err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}

	// finish when timeout
	go func() {
		time.Sleep(time.Duration(60) * time.Second) // timeout: 60sec
		t.Stop()
	}()
	// finish when task finished
	go func() {
		for {
			if !runningTask.IsActive() {
				t.Stop()
				break
			}
			time.Sleep(time.Duration(1) * time.Second)
		}
	}()
	// show logs
	for line := range t.Lines {
		fmt.Fprintln(w, line.Text)
		flusher.Flush() // Trigger "chunked" encoding and send a chunk...
	}

	fmt.Fprintf(w, "Current Status => %s\n", runningTask.Status)
	log.Printf("Task %d has been finished!!!!", runningTask.Id)
}
开发者ID:yutopp,项目名称:subako,代码行数:55,代码来源:app.go

示例14: readLogsFromFile

// readLogsFromFile reads log lines from file and send them to `queue`
// notify `shutdown` when file is completely read
func readLogsFromFile(fname string, queue chan<- Logline, shutdown chan<- string, savestate <-chan bool) {
	var statefile string
	var offset int64
	var inode uint64
	var doFollowFile bool = !*options.nofollow

	if *options.verbose {
		log.Printf("readLogsFromFile: dofollow=%v", doFollowFile)
	}

	if doFollowFile {
		statefile = fname + ".state"
		inode = readFileInode(fname)
		offset = readStateFile(fname, statefile, inode)
	}

	// setup
	config := tail.Config{
		Follow:    doFollowFile,
		ReOpen:    doFollowFile,
		MustExist: true,
		Logger:    tail.DiscardingLogger,
		Location: &tail.SeekInfo{
			Offset: offset,
			Whence: 0,
		},
	}
	t, err := tail.TailFile(fname, config)
	if err != nil {
		shutdown <- fmt.Sprintf("cannot tail file %s: %v", fname, err)
	} else if *options.verbose {
		log.Printf("opened log file %s", fname)
	}

	// now just sleep and wait for input and control channel
	for {
		select {
		case line := <-t.Lines:
			if line != nil {
				queue <- Logline(line.Text)
			} else {
				shutdown <- "Logfile closed"
				return
			}
		case <-savestate:
			offset, _ := t.Tell()
			if doFollowFile {
				writeStateFile(statefile, inode, offset)
			}
			if *options.verbose {
				log.Printf("reading %s, now at offset %d", fname, offset)
			}
		}
	}
}
开发者ID:mschuett,项目名称:go-log2gelf,代码行数:57,代码来源:main.go

示例15: TailServiceLog

func TailServiceLog(service *services.Service, wg *sync.WaitGroup) {
	defer wg.Done()
	spacingLength := services.MaxServiceNameLength + 2 - len(service.Name)
	t, err := tail.TailFile(service.LogFilePath, tail.Config{Follow: true})
	if err != nil {
		log.Error(err.Error())
	}
	for line := range t.Lines {
		logReceiver <- fmt.Sprintf("@{%s}%[email protected]{|}%s|  %s\n", service.Color, service.Name, strings.Repeat(" ", spacingLength), line.Text)
	}
}
开发者ID:danielchatfield,项目名称:orchestra,代码行数:11,代码来源:logs.go


注:本文中的github.com/ActiveState/tail.TailFile函数示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。