Exemple #1
0
func WriteToFile(FileName, Content string) {

	var outputFile *os.File

	OpenedFileLocker.RLock()
	for key, value := range OpenedFile {
		if key == FileName {
			outputFile = value
			break
		}
	}
	OpenedFileLocker.RUnlock()

	if outputFile == nil {
		tmpFileName := fmt.Sprintf("../UserId/%s.%d", FileName, time.Now().Unix())
		tmpoutputFile, outputError := os.OpenFile(tmpFileName, os.O_RDWR|os.O_APPEND|os.O_CREATE, 0)
		if outputError != nil {
			fmt.Println("An error occurred on opening the outputFile : ", outputError)
			return
		}
		outputFile = tmpoutputFile

		//outputFile.WriteString("\n\n" + time.Now().String() + "\n")

		OpenedFileLocker.Lock()
		OpenedFile[FileName] = outputFile
		OpenedFileLocker.Unlock()
	}
	outputFile.WriteString(Content + "\n")
	//defer outputFile.Close()
}
Exemple #2
0
func write(where *os.File, what string) {
	_, err := where.WriteString(what + "\n")
	if err != nil {
		fmt.Println(err)
		os.Exit(1)
	}
}
func writeLines(lines []string, path string) (err error) {
	var (
		file *os.File
	)

	if file, err = os.Create(path); err != nil {
		return
	}
	defer file.Close()

	//writer := bufio.NewWriter(file)
	for _, item := range lines {
		//fmt.Println(item)
		_, err := file.WriteString(strings.TrimSpace(item) + "\n")
		//file.Write([]byte(item));
		if err != nil {
			//fmt.Println("debug")
			fmt.Println(err)
			break
		}
	}
	/*content := strings.Join(lines, "\n")
	  _, err = writer.WriteString(content)*/
	return
}
Exemple #4
0
//
// Generate Header of html and write to the @fo
// @prespace mean how many upper to the resource of css and js
//
func generateHtmlHeader(fo *os.File, title string, prespace int) error {
	if fo == nil {
		return errors.New("No File Out Handle")
	}

	fo.WriteString("<!-- This file is generated by jkparsedoc -->\n")
	html_header := "<!DOCTYPE html>\n" +
		"<html lang='zh'>\n" +
		"<head>\n" +
		"\t<meta http-equiv='Content-Type' content='text/html; charset=utf-8'>\n" +
		"\t<title>" + title + "</title>\n" +
		"\t<link rel='shortcut icon' href='/static/imgs/favicon.ico' />\n" +
		"\t<link rel='icon' href='/static/imgs/favicon.png' type='image/png'>\n" +
		"\t<meta name='viewport' content='width=device-width, initial-scale=1.0'>\n" +
		"\t<meta name='description' content=''>\n" +
		"\t<meta name='author' content='jmdvirus'>\n" +
		"\t<!--[if lt IE 9]>\n" +
		"\t\t<script src='http://html5shim.googlecode.com/svn/trunk/html5.js'></script>\n" +
		"\t<![endif]-->\n" +
		"\n" +
		"\t<!-- bootstrap css -->\n" +
		"\t<link href='/static/css/bootstrap.min.css' rel='stylesheet'>\n" +
		"\t<link href='/static/css/bootstrap-theme.min.css' rel='stylesheet'>\n" +
		"</head>\n" +
		"<body>\n" +
		"<div class='container'>\n"
	fo.WriteString(html_header)

	return nil
}
Exemple #5
0
func setupTerminal(file *os.File) (*sys.Termios, error) {
	fd := int(file.Fd())
	term, err := sys.NewTermiosFromFd(fd)
	if err != nil {
		return nil, fmt.Errorf("can't get terminal attribute: %s", err)
	}

	savedTermios := term.Copy()

	term.SetICanon(false)
	term.SetEcho(false)
	term.SetVMin(1)
	term.SetVTime(0)

	err = term.ApplyToFd(fd)
	if err != nil {
		return nil, fmt.Errorf("can't set up terminal attribute: %s", err)
	}

	// Set autowrap off
	file.WriteString("\033[?7l")

	err = sys.FlushInput(fd)
	if err != nil {
		return nil, fmt.Errorf("can't flush input: %s", err)
	}

	return savedTermios, nil
}
Exemple #6
0
func (t *FileConfigTest) TestRulesFileDoesNotExist(c *C) {
	var fconf, rconf *os.File
	var err error
	var conf Config

	fconf, err = ioutil.TempFile("", "")
	if err != nil {
		panic(err)
	}
	rconf, err = ioutil.TempFile("", "")
	if err != nil {
		panic(err)
	}
	defer (func() {
		fconf.Close()
		rconf.Close()
	})()

	// Trailing \n is required by go-config issue #3.
	fconf.WriteString("[Settings]\nloglevel=debug\nrules=\n")
	fconf.Sync()

	conf, err = NewFileConfig(fconf.Name())
	c.Check(conf, Equals, (*FileConfig)(nil))
	c.Check(err, Not(Equals), nil)
}
Exemple #7
0
func AlgorithmRunOnDataSet(classifier algo.Classifier, train_dataset, test_dataset *core.DataSet, pred_path string, params map[string]string) (float64, []*eval.LabelPrediction) {

	if train_dataset != nil {
		classifier.Train(train_dataset)
	}

	predictions := []*eval.LabelPrediction{}
	var pred_file *os.File
	if pred_path != "" {
		pred_file, _ = os.Create(pred_path)
	}
	for _, sample := range test_dataset.Samples {
		prediction := classifier.Predict(sample)
		if pred_file != nil {
			pred_file.WriteString(strconv.FormatFloat(prediction, 'g', 5, 64) + "\n")
		}
		predictions = append(predictions, &(eval.LabelPrediction{Label: sample.Label, Prediction: prediction}))
	}
	if pred_path != "" {
		defer pred_file.Close()
	}

	auc := eval.AUC(predictions)
	return auc, predictions
}
Exemple #8
0
// writePlainIteratorOnFile puts on a file, the list of all the lemmas known.
// Instead of printing one word per line (alphabetically ordered), there is a
// soft-wrap at 80 characters.
func writePlainIteratorOnFile(i *mgo.Iter, f *os.File) (c int) {
	var err error
	var s struct {
		Lemma string
	}
	var ll int
	for i.Next(&s) {

		ss := s.Lemma
		ll += len(ss) + 1 // spaces counts...
		format := "%s "

		if ll > 80 {
			format = "\n%s "
			ll = len(ss)
		}
		if _, err = f.WriteString(fmt.Sprintf(format, ss)); err != nil {
			log.Fatalf("Error dumping: %s\n", err.Error())
		}
		c++
	}

	defer func() {
		if err = i.Close(); err != nil {
			return
		}
	}()
	return
}
Exemple #9
0
func WriteTextToFile(filePath string, data string, append bool) error {
	var f *os.File
	var err error
	if append == true {
		if _, err := os.Stat(filePath); os.IsNotExist(err) {
			f, err = os.Create(filePath)
			if err != nil {
				return err
			}
			f.Close()
		}

		// open files r and w
		f, err = os.OpenFile(filePath, os.O_APPEND|os.O_WRONLY, 0600)
		if err != nil {
			return err
		}
	} else {
		f, err = os.Create(filePath)
		if err != nil {
			return err
		}
	}

	defer f.Close()

	_, err = f.WriteString(data)
	return err
}
Exemple #10
0
func (c *cmdSetData) SaveCmdSet(cmdsetName string, cmdset []string) {
	var f *os.File

	fp := getFilePath()
	_, err := os.Stat(fp)
	if err != nil && !os.IsExist(err) {
		f, err = os.Create(fp)
	} else {
		f, err = os.OpenFile(fp, os.O_RDWR|os.O_APPEND, 0660)
	}
	if err != nil {
		quitWithError("Error writing to file: ", err)
	}
	defer f.Close()

	if _, err = f.WriteString("--" + cmdsetName + "\n"); err != nil {
		quitWithError("Error writing to file: ", err)
	}

	for _, str := range cmdset {
		if _, err = f.WriteString("  " + str + "\n"); err != nil {
			quitWithError("Error writing to file: ", err)
		}
	}

}
Exemple #11
0
// dumps a specific chunk, reading chunk info from the cchunk channel
func dumpChunk(cc string) {
	var out *os.File
	dbcon := autorc.New("tcp", "", host+":"+port, user, password, schema)
	defer func() {
		out.Close()
		if err := recover(); err != nil {
			die(err.(error).Error())
		}
		wg.Done()
	}()

	for {
		cr := <-cchunks
		out, _ = os.Create(path + "/" + schema + "." + table + "." + strconv.Itoa(cr.lower) + "." + strconv.Itoa(cr.upper) + ".csv")
		rows, _, _ := dbcon.Query("select * from " + schema + "." + table + " where " + cc + " between " + strconv.Itoa(cr.lower) + " and " + strconv.Itoa(cr.upper))
		for _, row := range rows {
			line := ""

			for idx, _ := range row {
				comma := ","
				if idx == len(row)-1 {
					comma = ""
				}
				line += row.Str(idx) + comma
			}

			out.WriteString(line + "\n")
		}
		if done {
			return
		}
	}
}
Exemple #12
0
// 写入文件
// filePath:文件夹路径
// fileName:文件名称
// ifAppend:是否追加内容
// args:可变参数
func WriteFile(filePath, fileName string, ifAppend bool, args ...string) {
	// 得到最终的fileName
	fileName = filepath.Join(filePath, fileName)

	// 判断文件夹是否存在,如果不存在则创建
	mutex.Lock()
	if !IsDirExists(filePath) {
		os.MkdirAll(filePath, os.ModePerm|os.ModeTemporary)
	}
	mutex.Unlock()

	// 打开文件(如果文件存在就以读写模式打开,并追加写入;如果文件不存在就创建,然后以读写模式打开。)
	var f *os.File
	var err error
	if ifAppend == false {
		f, err = os.OpenFile(fileName, os.O_CREATE|os.O_RDWR|os.O_TRUNC, os.ModePerm|os.ModeTemporary)
	} else {
		f, err = os.OpenFile(fileName, os.O_CREATE|os.O_RDWR|os.O_APPEND, os.ModePerm|os.ModeTemporary)
	}

	if err != nil {
		fmt.Println("打开文件错误:", err)
		return
	}
	defer f.Close()

	// 写入内容
	for _, arg := range args {
		f.WriteString(arg)
	}
}
Exemple #13
0
func httpRequest(lines []string, stats *HttpStats, errorFile *os.File, mutex *sync.Mutex) {
	for {
		offset := atomic.AddInt64(&stats.doneRequests, 1)
		if int(offset) > len(lines) {
			break
		}
		line := lines[offset-1]

		// format: [Method URL BodyParameters(for POST)]
		items := strings.Split(line, " ")
		var body io.Reader
		if len(items) > 2 {
			body = strings.NewReader(items[2])
		}

		req, _ := http.NewRequest(items[0], items[1], body)
		client := new(http.Client)

		start := time.Now()
		resp, err := client.Do(req)
		end := time.Now()

		interval := int64(end.Sub(start).Nanoseconds())
		atomic.AddInt64(&stats.accumLatencies, interval)
		if err != nil {
			atomic.AddInt64(&stats.numFailed, 1)
			mutex.Lock()
			errorFile.WriteString(err.Error() + "\n")
			mutex.Unlock()
		} else {
			atomic.AddInt64(&stats.numSucceeded, 1)
		}
		resp.Body.Close()
	}
}
Exemple #14
0
func LogProcessor(in chan gears.RFMessage) {
	os.Mkdir(logDir, 0775)
	go func() {
		var log_fd *os.File
		log_name := ""
		for m := range in {
			// Format the string
			t := time.Now().Format("2006-01-02 15:04:05")
			str := fmt.Sprintf("%s %02x %02d %02x %02d: % x\n",
				t, m.Group, m.Node, m.Kind, len(m.Data)+1, m.Data)
			// Open log file if necessary
			name := fmt.Sprintf("%s/%s.wd", logDir, time.Now().Format("2006-01-02"))
			if name != log_name {
				if log_fd != nil {
					log_fd.Close()
				}
				log_name = name
				var err error
				log_fd, err = os.OpenFile(log_name,
					os.O_WRONLY+os.O_APPEND+os.O_CREATE, 0664)
				if err != nil {
					glog.Errorf("Cannot open %s: %s", log_name, err.Error())
					log_name = ""
				}
			}
			// Write data
			_, err := log_fd.WriteString(str)
			if err != nil {
				glog.Errorf("Error writing %s: %s", log_name, err.Error())
				log_name = ""
			}
		}
	}()
}
Exemple #15
0
func load_config(
	config string,
	rules string,
	c *C) (conf *FileConfig, cleanup func()) {
	var fconf, rconf *os.File
	var err error

	fconf, err = ioutil.TempFile("", "")
	if err != nil {
		panic(err)
	}
	rconf, err = ioutil.TempFile("", "")
	if err != nil {
		panic(err)
	}
	cleanup = func() {
		fconf.Close()
		rconf.Close()
	}

	// Trailing \n is required by go-config issue #3.
	fconf.WriteString(
		"[Settings]\n" + config + "\n" + "rules=" + rconf.Name() + "\n")
	fconf.Sync()
	rconf.WriteString(rules + "\n")
	rconf.Sync()

	conf, err = NewFileConfig(fconf.Name())
	c.Assert(conf, Not(Equals), nil)
	c.Assert(err, Equals, nil)
	return
}
Exemple #16
0
func getPage(code string, f *os.File) {
	var url string = fmt.Sprintf("http://stocks.finance.yahoo.co.jp/stocks/detail/?code=%s", code)
	var b *Basis = &Basis{}
	var i *Index = &Index{}
	var m *Margin = &Margin{}

	doc, _ := goquery.NewDocument(url)

	textMap := func(q string, vars ...*string) {
		for i, v := range vars {
			*v = doc.Find(q).Eq(i).Text()
		}
	}

	b.title = doc.Find("table.stocksTable th.symbol h1").Text()
	b.market = doc.Find("div#ddMarketSelect span.stockMainTabName").Text()
	b.industry = doc.Find("div.stocksDtl dd.category a").Text()
	i.price = doc.Find("table.stocksTable td.stoksPrice").Last().Text()

	textMap("div.innerDate dd strong", &i.previousprice, &i.opening, &i.high, &i.low, &i.turnover, &i.trading_volume, &b.price_limit)
	textMap("div.ymuiDotLine div.yjMS dd.ymuiEditLink strong", &m.margin_buying, &m.d_margin_buying, &m.margin_rate, &m.margin_selling, &m.d_margin_selling)
	textMap("div#main div.main2colR div.chartFinance div.lineFi dl dd strong", &b.capitalization, &b.shares_outstanding, &b.dividend_yield, &i.dps, &i.per, &i.pbr, &i.eps, &i.bps, &b.minimum_purchase, &b.share_unit, &b.yearly_high, &b.yearly_low)

	mapB, _ := json.Marshal(map[string]string{"name": b.title, "price": i.price})
	fmt.Println(string(mapB))

	row := fmt.Sprint(string(mapB), ",")

	_, err := f.WriteString(row)
	check(err)
}
Exemple #17
0
func (t *FileConfigTest) TestLoadsRelativeRulesPath(c *C) {
	var fconf, rconf *os.File
	var err error
	var conf Config

	fconf, err = ioutil.TempFile("", "")
	if err != nil {
		panic(err)
	}
	rconf, err = ioutil.TempFile("", "")
	if err != nil {
		panic(err)
	}
	defer (func() {
		fconf.Close()
		rconf.Close()
	})()

	path, _ := filepath.Rel(filepath.Dir(fconf.Name()), rconf.Name())

	// Trailing \n is required by go-config issue #3.
	fconf.WriteString("[Settings]\nloglevel=debug\nrules=" + path + "\n")
	fconf.Sync()

	conf, err = NewFileConfig(fconf.Name())
	c.Assert(conf, Not(Equals), nil)
	c.Assert(err, Equals, nil)
}
Exemple #18
0
// writeModelFiles generates model files
func writeModelFiles(tables []*Table, mPath string, selectedTables map[string]bool) {
	w := NewColorWriter(os.Stdout)

	for _, tb := range tables {
		// if selectedTables map is not nil and this table is not selected, ignore it
		if selectedTables != nil {
			if _, selected := selectedTables[tb.Name]; !selected {
				continue
			}
		}
		filename := getFileName(tb.Name)
		fpath := path.Join(mPath, filename+".go")
		var f *os.File
		var err error
		if isExist(fpath) {
			ColorLog("[WARN] '%v' already exists. Do you want to overwrite it? [Yes|No] ", fpath)
			if askForConfirmation() {
				f, err = os.OpenFile(fpath, os.O_RDWR|os.O_TRUNC, 0666)
				if err != nil {
					ColorLog("[WARN] %v\n", err)
					continue
				}
			} else {
				ColorLog("[WARN] Skipped create file '%s'\n", fpath)
				continue
			}
		} else {
			f, err = os.OpenFile(fpath, os.O_CREATE|os.O_RDWR, 0666)
			if err != nil {
				ColorLog("[WARN] %v\n", err)
				continue
			}
		}
		template := ""
		if tb.Pk == "" {
			template = StructModelTPL
		} else {
			template = ModelTPL
		}
		fileStr := strings.Replace(template, "{{modelStruct}}", tb.String(), 1)
		fileStr = strings.Replace(fileStr, "{{modelName}}", camelCase(tb.Name), -1)
		fileStr = strings.Replace(fileStr, "{{tableName}}", tb.Name, -1)
		// if table contains time field, import time.Time package
		timePkg := ""
		importTimePkg := ""
		if tb.ImportTimePkg {
			timePkg = "\"time\"\n"
			importTimePkg = "import \"time\"\n"
		}
		fileStr = strings.Replace(fileStr, "{{timePkg}}", timePkg, -1)
		fileStr = strings.Replace(fileStr, "{{importTimePkg}}", importTimePkg, -1)
		if _, err := f.WriteString(fileStr); err != nil {
			ColorLog("[ERRO] Could not write model file to %s\n", fpath)
			os.Exit(2)
		}
		CloseFile(f)
		fmt.Fprintf(w, "\t%s%screate%s\t %s%s\n", "\x1b[32m", "\x1b[1m", "\x1b[21m", fpath, "\x1b[0m")
		formatSourceCode(fpath)
	}
}
Exemple #19
0
func RegAlgorithmRunOnDataSet(regressor algo.Regressor, train_dataset, test_dataset *core.RealDataSet, pred_path string, params map[string]string) (float64, []*eval.RealPrediction) {

	if train_dataset != nil {
		regressor.Train(train_dataset)
	}

	predictions := []*eval.RealPrediction{}
	var pred_file *os.File
	if pred_path != "" {
		pred_file, _ = os.Create(pred_path)
	}
	for _, sample := range test_dataset.Samples {
		prediction := regressor.Predict(sample)
		if pred_file != nil {
			pred_file.WriteString(strconv.FormatFloat(prediction, 'g', 5, 64) + "\n")
		}
		predictions = append(predictions, &eval.RealPrediction{Value: sample.Value, Prediction: prediction})
	}
	if pred_path != "" {
		defer pred_file.Close()
	}

	rmse := eval.RegRMSE(predictions)
	return rmse, predictions
}
Exemple #20
0
func WriteStringFile(category string, windows []gologme.SEventT, dir string) {
	err := os.MkdirAll(dir, 0777)
	if err != nil {
		log.Fatal(err)
	}
	var (
		f            *os.File
		lastUlogTime int64
		init         bool = false
	)

	for _, wl := range windows {
		ult := gologme.Ulogme7amTime(wl.RealTime)
		if !init || ult != lastUlogTime {
			_ = f.Close()
			fn := fmt.Sprintf("%s/%s_%d.txt", dir, category, ult)
			fmt.Printf("Writing to %s\n", fn)
			f, err = os.Create(fn)
			if err != nil {
				log.Fatal(err)
			}
			lastUlogTime = ult
			init = true
		}
		f.WriteString(fmt.Sprintf("%d %s\n", wl.RealTime.Unix(), wl.Title))
	}
}
Exemple #21
0
func MultiClassRunOnDataSet(classifier algo.MultiClassClassifier, train_dataset, test_dataset *core.DataSet, pred_path string, params map[string]string) float64 {

	if train_dataset != nil {
		classifier.Train(train_dataset)
	}

	var pred_file *os.File
	if pred_path != "" {
		pred_file, _ = os.Create(pred_path)
	}
	accuracy := 0.0
	total := 0.0
	for _, sample := range test_dataset.Samples {
		prediction := classifier.PredictMultiClass(sample)
		label, _ := prediction.KeyWithMaxValue()
		if int(label) == sample.Label {
			accuracy += 1.0
		}
		total += 1.0
		if pred_file != nil {
			pred_file.WriteString(strconv.Itoa(label) + "\n")
		}
	}
	if pred_path != "" {
		defer pred_file.Close()
	}

	return accuracy / total
}
Exemple #22
0
func FindAndReplaceFd(fd *os.File, oldPattern, newPattern string) error {
	fbuf, err := ioutil.ReadAll(fd)
	if err != nil {
		return err
	}
	fd.Seek(0, -1)
	fd.Truncate(0)
	expr, err := regexp.Compile(oldPattern)
	if err != nil {
		return err
	}
	buffer := bytes.NewBuffer(fbuf)
	for {
		line, err := buffer.ReadString('\n')
		if err != nil {
			if err == io.EOF {
				break
			}
			return err
		}
		if expr.MatchString(line) {
			line = expr.ReplaceAllString(line, newPattern)
		}
		if _, err := fd.WriteString(line); err != nil {
			return err
		}
	}
	return nil
}
Exemple #23
0
func (fm *FileMonitor) updateJournal(bytes_read int64) (ok bool) {
	var msg string
	var seekJournal *os.File
	var file_err error

	if bytes_read == 0 || fm.seekJournalPath == "." {
		return true
	}

	if seekJournal, file_err = os.OpenFile(fm.seekJournalPath,
		os.O_CREATE|os.O_RDWR|os.O_APPEND,
		0660); file_err != nil {
		msg = fmt.Sprintf("Error opening seek recovery log for append: %s", file_err.Error())
		fm.LogError(msg)
		return false
	}
	defer seekJournal.Close()
	seekJournal.Seek(0, os.SEEK_END)

	var filemon_bytes []byte
	filemon_bytes, _ = json.Marshal(fm)

	msg = string(filemon_bytes) + "\n"
	seekJournal.WriteString(msg)

	return true
}
Exemple #24
0
func (ui *stdUI) fprint(f *os.File, args []interface{}) {
	text := fmt.Sprint(args...)
	if !strings.HasSuffix(text, "\n") {
		text += "\n"
	}
	f.WriteString(text)
}
Exemple #25
0
func build_config(
	rules string,
	c *C) (conf string, cleanup func()) {
	var fconf, rconf *os.File
	var err error
	var conf_test Config

	fconf, err = ioutil.TempFile("", "")
	if err != nil {
		panic(err)
	}
	rconf, err = ioutil.TempFile("", "")
	if err != nil {
		panic(err)
	}
	cleanup = func() {
		fconf.Close()
		rconf.Close()
	}

	// Trailing \n is required by go-config issue #3.
	fconf.WriteString(
		"[Settings]\nloglevel=debug\nrules=" + rconf.Name() + "\n")
	fconf.Sync()
	rconf.WriteString(rules + "\n")
	rconf.Sync()

	conf_test, err = NewFileConfig(fconf.Name())
	c.Assert(conf_test, Not(Equals), nil)
	c.Assert(err, Equals, nil)

	conf = fconf.Name()
	return
}
Exemple #26
0
// Logging events logger itself
// Each room's events are written to separate file in logdir
// Events include messages, topic and keys changes, joining and leaving
func Logger(logdir string, events <-chan LogEvent) {
	mode := os.O_CREATE | os.O_WRONLY | os.O_APPEND
	perm := os.FileMode(0660)
	var format string
	var logfile string
	var fd *os.File
	var err error
	for event := range events {
		logfile = path.Join(logdir, event.where+".log")
		fd, err = os.OpenFile(logfile, mode, perm)
		if err != nil {
			log.Println("Can not open logfile", logfile, err)
			continue
		}
		if event.meta {
			format = FormatMeta
		} else {
			format = FormatMsg
		}
		_, err = fd.WriteString(fmt.Sprintf(format, time.Now(), event.who, event.what))
		fd.Close()
		if err != nil {
			log.Println("Error writing to logfile", logfile, err)
		}
	}
}
Exemple #27
0
// Open the file, write to the file, close the file.
// Whichever user is running the function needs write permissions to the file or directory if the file does not yet exist.
func (hook *lfsHook) Fire(entry *logrus.Entry) error {
	var (
		fd   *os.File
		path string
		msg  string
		err  error
		ok   bool
	)
	if path, ok = hook.paths[entry.Level]; !ok {
		err = fmt.Errorf("no file provided for loglevel: %d", entry.Level)
		log.Println(err.Error())
		return err
	}
	fd, err = os.OpenFile(path, os.O_WRONLY|os.O_APPEND|os.O_CREATE, 0666)
	if err != nil {
		log.Println("failed to open logfile:", path, err)
		return err
	}
	defer fd.Close()
	msg, err = entry.String()
	if err != nil {
		log.Println("failed to generate string for entry:", err)
		return err
	}
	fd.WriteString(msg)
	return nil
}
Exemple #28
0
func writeAnsiImage(img image.Image, file *os.File, width int) {
	m := resize.Resize(uint(width), uint(float32(width)*PROPORTION), img, resize.Lanczos3)
	var current, previous string
	bounds := m.Bounds()
	for y := bounds.Min.Y; y < bounds.Max.Y; y++ {
		for x := bounds.Min.X; x < bounds.Max.X; x++ {
			current = toAnsiCode(m.At(x, y))
			if current != previous {
				fmt.Print(current)
				file.WriteString(current)
			}
			if ANSI_RESET != current {
				char := string(CHARACTERS[rand.Int()%len(CHARACTERS)])
				fmt.Print(char)
				file.WriteString(char)
			} else {
				fmt.Print(" ")
				file.WriteString(" ")
			}
		}
		fmt.Print("\n")
		file.WriteString("\n")
	}
	fmt.Print(ANSI_RESET)
	file.WriteString(ANSI_RESET)
}
func fileWriter(t *testing.T, file *os.File, logs []string) {
	filename := file.Name()
	time.Sleep(1 * time.Second) // wait for start Tail...

	for _, line := range logs {
		if strings.Index(line, RotateMarker) != -1 {
			log.Println("fileWriter: rename file => file.old")
			os.Rename(filename, filename+".old")
			file.Close()
			file, _ = os.OpenFile(filename, os.O_CREATE|os.O_WRONLY, 0644)
			log.Println("fileWriter: re-opened file")
		} else if strings.Index(line, TruncateMarker) != -1 {
			time.Sleep(1 * time.Second)
			log.Println("fileWriter: truncate(file, 0)")
			os.Truncate(filename, 0)
			file.Seek(int64(0), os.SEEK_SET)
		}
		_, err := file.WriteString(line)
		log.Print("fileWriter: wrote ", line)
		if err != nil {
			log.Println("write failed", err)
		}
		time.Sleep(1 * time.Millisecond)
	}
	file.Close()
}
Exemple #30
0
func (fi FileStorage) Store(str string) {
	if fi.Size == 0 || fi.Path == "" {
		return
	}

	// Init variables
	var file *os.File
	name := fi.Path + "/" + LogName

	// Check file size
	stat, err := os.Stat(name)
	if err == nil {
		if stat.Size() > fi.Size {
			curtime := time.Now()
			os.Rename(name, fmt.Sprintf("%s_%d_%d.txt", name, curtime.Unix(), curtime.UnixNano()))
		} else {
			file, err = os.OpenFile(name, os.O_WRONLY|os.O_APPEND, 0666)
		}
	}

	if file == nil {
		file, err = os.Create(name)
	}

	if err != nil {
		panic(err)
	}

	file.WriteString(str + "\r\n")

	// Never forget to close file.
	file.Close()
}