Exemplo n.º 1
0
// path can be ""
func InitLog(path string, debug bool) {

	config := `
<seelog type="sync" minlevel="${minlevel}">
    <outputs formatid="main">
        <console/>
        <!-- ${extra} -->
    </outputs>
    <formats>
        <format id="main" format="[EQ-%LEV] %Date(15:04:05.00): %Msg (at %File:%Line) %n"/>
    </formats>
</seelog>`

	if path != "" {
		extra := fmt.Sprintf("<file path=\"%s\"/>", path)
		config = strings.Replace(config, "<!-- ${extra} -->",
			extra, -1)
	}

	Debug = debug
	if debug {
		config = strings.Replace(config, "${minlevel}", "debug", -1)
	} else {
		config = strings.Replace(config, "${minlevel}", "info", -1)
	}

	logger, err := seelog.LoggerFromConfigAsBytes([]byte(config))
	if err != nil {
		panic(err)
	}
	seelog.ReplaceLogger(logger)
	if path != "" {
		seelog.Debugf("Initialized the logger for %s", path)
	}
}
Exemplo n.º 2
0
func setInitLogging(logLevel string) {

	logLevel = strings.ToLower(logLevel)

	testConfig := `
	<seelog  type="sync" minlevel="`
	testConfig = testConfig + logLevel
	testConfig = testConfig + `">
		<outputs formatid="main">
			<filter levels="error">
				<file path="./log/gopa.log"/>
			</filter>
			<console formatid="main" />
		</outputs>
		<formats>
			<format id="main" format="[%Date(01-02) %Time] [%LEV] [%File:%Line,%FuncShort] %Msg%n"/>
		</formats>
	</seelog>`

	logger, err := log.LoggerFromConfigAsString(testConfig)
	if err != nil {
		log.Error("init config error,", err)
	}
	err = log.ReplaceLogger(logger)
	if err != nil {
		log.Error("init config error,", err)
	}
}
Exemplo n.º 3
0
func SetupTestLogging() {
	var appConfig = `
  <seelog type="sync" minlevel='%s'>
  <outputs formatid="scanner">
    <filter levels="critical,error,warn,info">
      <console formatid="scanner" />
    </filter>
    <filter levels="debug,trace">
      <console formatid="debug" />
    </filter>
  </outputs>
  <formats>
  <format id="scanner" format="test: [%%LEV] %%Msg%%n" />
  <format id="debug" format="test: [%%LEV] %%Func :: %%Msg%%n" />
  </formats>
  </seelog>
`

	var config string
	if testing.Verbose() {
		config = fmt.Sprintf(appConfig, "trace")
	} else {
		config = fmt.Sprintf(appConfig, "info")
	}

	logger, err := log.LoggerFromConfigAsBytes([]byte(config))

	if err != nil {
		fmt.Println(err)
		return
	}

	log.ReplaceLogger(logger)
}
Exemplo n.º 4
0
func initLogger() {
	var err error

	// 初始化raven
	if cfg.Sentry != "" {
		Raven, err = raven.NewClient(cfg.Sentry, nil)
		if err != nil {
			log.Error("Init Sentry Error:", err)
		}
	}

	// 初始化logger
	if cfg.Logger != "" {
		// 自定义一个seelog raven receiver
		receiver := &RavenReciver{Client: Raven}
		parseParams := &log.CfgParseParams{
			CustomReceiverProducers: map[string]log.CustomReceiverProducer{
				"sentry": func(log.CustomReceiverInitArgs) (log.CustomReceiver, error) {
					return receiver, nil
				},
			},
		}
		if logger, err := log.LoggerFromParamConfigAsFile(cfg.Logger, parseParams); err == nil {
			log.ReplaceLogger(logger)
		} else {
			log.Error("Parse Logger Error: ", err)
		}

	}

}
Exemplo n.º 5
0
func DisableLogs() {
	logger, err := log.LoggerFromConfigAsString(DEFAULT_DISABLE_LOGS_CONFIG)
	if err != nil {
		panic(err)
	}
	log.ReplaceLogger(logger)
}
Exemplo n.º 6
0
func testFuncException() {
	fmt.Println("testFuncException")
	testConfig := `
<seelog type="sync" minlevel="info">
	<exceptions>
		<exception funcpattern="*main.test*Except*" minlevel="error"/>
	</exceptions>
	<outputs>
		<console/>
	</outputs>
</seelog>`

	logger, _ := log.LoggerFromConfigAsBytes([]byte(testConfig))
	log.ReplaceLogger(logger)

	log.Trace("NOT Printed")
	log.Debug("NOT Printed")
	log.Info("NOT Printed")
	log.Warn("NOT Printed")
	log.Error("Printed")
	log.Critical("Printed")

	log.Current.Trace("NOT Printed")
	log.Current.Debug("NOT Printed")
	log.Current.Info("NOT Printed")
	log.Current.Warn("NOT Printed")
	log.Current.Error("Printed")
	log.Current.Critical("Printed")
}
Exemplo n.º 7
0
func NewLogs() {
	logger, err := log.LoggerFromConfigAsBytes([]byte(default_template))
	if err != nil {
		log.Criticalf("log config err: %v", err)
	}
	log.ReplaceLogger(logger)
}
Exemplo n.º 8
0
func main() {
	defer log.Flush()
	flag.Parse()
	args := flag.Args()

	if len(args) == 0 {
		usage(actions(nil))
		os.Exit(1)
	}

	logger, err := log.LoggerFromConfigAsString(config.Logger())
	if err != nil {
		die(err)
	}
	log.ReplaceLogger(logger)

	init, err := engine.New()
	if err != nil {
		die(err)
	}
	log.Info(args[0])
	actions := actions(init)
	action, ok := actions[args[0]]
	if !ok {
		usage(actions)
		os.Exit(1)
	}
	err = action.function()
	if err != nil {
		die(err)
	}
}
Exemplo n.º 9
0
func main() {
	//err := LoadConfig("/system/etc/conf.json")
	err := LoadConfig("./conf.json")
	if err != nil {
		fmt.Printf("LoadConfig failed: (%s)", err)
		os.Exit(1)
	}

	//logger, err := log.LoggerFromConfigAsFile("/system/etc/log.xml")
	logger, err := log.LoggerFromConfigAsFile("./log.xml")
	if err != nil {
		fmt.Printf("Load log config failed: (%s)\n", err)
		os.Exit(1)
	}
	log.ReplaceLogger(logger)

	//wg := &sync.WaitGroup{}
	agent := NewAgent()
	c := make(chan os.Signal, 1)
	signal.Notify(c, os.Interrupt, syscall.SIGTERM, syscall.SIGQUIT)

	wg := sync.WaitGroup{}
	wg.Add(1)
	go func() {
		agent.Run()
		log.Infof("agent quited")
		wg.Done()
	}()
	sig := <-c
	log.Infof("Received signal '%v', exiting\n", sig)
	agent.Stop()
	wg.Wait()
}
Exemplo n.º 10
0
Arquivo: log.go Projeto: unikk/cuto
// ロガーの初期化処理を行う
//
// param ; dir       ログファイルの出力先ディレクトリ。
//
// param : name      ログファイルの種別(例:master、servant)。
//
// param : identifer ロック用ファイルに(付与する識別ID(例:servantはListePort)。
//
// param : level     出力ログレベル(trace,debug,info,warn,error,criticalのいずれかを指定)
//
// param : maxSizeKB ログファイルの最大サイズ。この値を超えるとログローテーションが発生する。
//
// param : maxRolls  ログファイルの最大世代数
//
// param : timeoutSec  ロックのタイムアウト秒
//
// return : エラー情報を返す。
func Init(dir string, name string, identifer string, level string, maxSizeKB int, maxRolls int, timeoutSec int) error {
	var lockErr error
	lockName := lockHeader + name
	if identifer != "" {
		lockName = lockName + "_" + identifer
	}
	lockName = lockName + ".lock"
	locker, lockErr = util.InitLock(lockName)
	if lockErr != nil {
		return lockErr
	}
	if timeoutSec > 0 {
		lockTimeout = timeoutSec * 1000
	}

	logfile := fmt.Sprintf("%s%c%s.log", dir, os.PathSeparator, name)
	if err := makeFileIfNotExist(logfile); err != nil {
		Term()
		return err
	}

	config := generateConfigString(logfile, level, maxSizeKB, maxRolls)
	logger, err := seelog.LoggerFromConfigAsString(config)
	if err != nil {
		Term()
		return err
	}

	seelog.ReplaceLogger(logger)
	valid = true

	return nil
}
Exemplo n.º 11
0
func InitDefaultSyncLogConfig() {
	logger, err := log.LoggerFromConfigAsString(DEFAULT_SYNC_LOG_CONFIG)
	if err != nil {
		panic(err)
	}
	log.ReplaceLogger(logger)
}
Exemplo n.º 12
0
func dateTimeFormat() {
	fmt.Println("Date time format")

	testConfig := `
<seelog type="sync">
	<outputs formatid="main">
		<console/>
	</outputs>
	<formats>
		<format id="main" format="%Date/%Time [%LEV] %Msg%n"/>
	</formats>
</seelog>`

	logger, err := log.LoggerFromConfigAsBytes([]byte(testConfig))

	if err != nil {
		fmt.Println(err)
	}

	loggerErr := log.ReplaceLogger(logger)

	if loggerErr != nil {
		fmt.Println(loggerErr)
	}

	log.Trace("Test message!")
}
Exemplo n.º 13
0
func configLogger() {
	config := `
<seelog type="sync">
	<outputs>
		<filter levels="trace">
			<console formatid="skipped"/>
		</filter>
		<filter levels="debug">
			<console formatid="unchanged"/>
		</filter>
		<filter levels="info">
			<console formatid="plain"/>
		</filter>
		<filter levels="warn,error,critical">
			<console formatid="error"/>
		</filter>
	</outputs>
	<formats>
		<format id="error" format="%EscM(31)%Msg%EscM(0)%n"/>
		<format id="plain" format="%Msg%n"/>
		<format id="unchanged" format="%EscM(32)%Msg%EscM(0)%n"/>
		<format id="skipped" format="%EscM(34)%Msg%EscM(0)%n"/>
	</formats>
</seelog>`

	logger, err := log.LoggerFromConfigAsBytes([]byte(config))
	if err != nil {
		panic(err)
	}
	log.ReplaceLogger(logger)
}
Exemplo n.º 14
0
func setup_logging() {
	level := "info"
	if *g_debug == true {
		level = "debug"
	}
	config := fmt.Sprintf(`
<seelog type="sync" minlevel="%s">
	<outputs formatid="main">
		<console/>
	</outputs>
	<formats>
		<format id="main" format="%%Date %%Time [%%LEVEL] %%File|%%FuncShort|%%Line: %%Msg%%n"/>
	</formats>
</seelog>`, level)

	logger, err := log.LoggerFromConfigAsBytes([]byte(config))

	if err != nil {
		fmt.Println("Failed to config logging:", err)
		os.Exit(1)
	}

	log.ReplaceLogger(logger)

	log.Info("Logging config is successful")
}
Exemplo n.º 15
0
func configureLogging(verbose bool) {
	minLevel := "info"

	if verbose {
		minLevel = "trace"
	}

	logger, err := log.LoggerFromConfigAsString(fmt.Sprintf(`
<seelog minlevel="%s">
    <outputs formatid="out">
        <console />
    </outputs>

    <formats>
        <format id="out" format="%%Date %%Time [%%LEVEL] %%Msg%%n" />
    </formats>
</seelog>
`, minLevel))

	if err != nil {
		panic(err)
	}

	log.ReplaceLogger(logger)
}
Exemplo n.º 16
0
func init() {
	logger, err := log.LoggerFromConfigAsFile("seelog.xml")
	if err != nil {
		panic(err)
	}
	log.ReplaceLogger(logger)
}
Exemplo n.º 17
0
func InitSeeLog(seeLogCfgFile string) {
	logger, err := log.LoggerFromConfigAsFile(seeLogCfgFile)
	if err != nil {
		log.Errorf("Parse seelog config file error: %s", err.Error)
		os.Exit(1)
	}
	log.ReplaceLogger(logger)
}
Exemplo n.º 18
0
func InitLogger(configPath string) {
	logger, err := seelog.LoggerFromConfigAsFile(configPath)
	if err != nil {
		fmt.Println(err)
		os.Exit(-1)
	}
	seelog.ReplaceLogger(logger)
}
Exemplo n.º 19
0
func setLogLevel(level string) {
	if level != "error" && level != "warn" {
		log.Infof("Setting log level '%s'.", level)
	}
	logConfig := fmt.Sprintf("<seelog minlevel='%s'>", level)
	logger, _ := log.LoggerFromConfigAsBytes([]byte(logConfig))
	log.ReplaceLogger(logger)
}
Exemplo n.º 20
0
func SetupLogger() {
	logger, err := log.LoggerFromConfigAsString(loggerConfig())
	if err == nil {
		log.ReplaceLogger(logger)
	} else {
		log.Error(err)
	}
}
Exemplo n.º 21
0
func updateLogger() error {
	logger, err := log.LoggerFromConfigAsFile(LOGGER_CONFIG)
	if err != nil {
		return err
	}

	return log.ReplaceLogger(logger)
}
Exemplo n.º 22
0
func main() {
	defer log.Flush()
	logger, err := log.LoggerFromConfigAsFile("seelog.xml")

	if nil != err {
		log.Warn("Failed to load config", err)
	}
	log.ReplaceLogger(logger)
	flag.Parse()
	statsTransformChannel := make(chan *diskStat.DiskStat, 10)
	statsOutputChannel := make(chan *diskStat.ExtendedIoStats, 10)

	var output outputInterface.Output
	proto := PStdOut

	switch *protocolType {
	case "protobuffers":
		{
			proto = PProtoBuffers
		}
	case "json":
		{
			proto = PJson
		}
	default:
		{
			if *outputType == "zmq" {
				proto = PProtoBuffers
			} else if *outputType == "stdout" {
				proto = PStdOut
			}
		}
	}

	switch *outputType {
	case "zmq":
		output, err = zmqOutput.NewZmqOutput(queueUrl, proto)
	case "nano":
		output, err = nanoMsgOutput.NewNanoMsgOutput(queueUrl, proto)
	default:
		output = &logOutput.LogOutput{proto}
	}
	if nil != err {
		log.Error("Failed to setup output ", err)
	}

	go ioStatTransform.TransformStat(statsTransformChannel, statsOutputChannel)

	go statsOutput.Output(statsOutputChannel, output)

	for {
		readAndSendStats(statsTransformChannel)
		time.Sleep(time.Second * time.Duration(*interval))

	}
	close(statsTransformChannel)
	close(statsOutputChannel)
}
Exemplo n.º 23
0
func NewLogger(cfgfile string) *BurrowLogger {
	logger, err := log.LoggerFromConfigAsFile(cfgfile)
	if err != nil {
		log.Criticalf("Cannot start logger: %v", err)
		os.Exit(1)
	}
	log.ReplaceLogger(logger)
	return &BurrowLogger{logger}
}
Exemplo n.º 24
0
func main() {
	cfgfile := "conf.json"
	begin := 0
	count := 1
	if len(os.Args) >= 3 {
		begin, _ = strconv.Atoi(os.Args[1])
		count, _ = strconv.Atoi(os.Args[2])
	}
	r, err := os.Open(cfgfile)
	if err != nil {
		fmt.Printf("failed to open config file %s", cfgfile)
		os.Exit(1)
	}

	var config Config
	decoder := json.NewDecoder(r)
	err = decoder.Decode(&config)
	if err != nil {
		fmt.Printf("invalid config file")
		os.Exit(1)
	}
	if config.ReadTimeout <= 0 {
		config.ReadTimeout = time.Duration(20)
	}

	logger, err := log.LoggerFromConfigAsFile("log.xml")
	if err != nil {
		fmt.Printf("Load log config failed: (%s)\n", err)
		os.Exit(1)
	}
	log.ReplaceLogger(logger)

	server, _ := net.ResolveTCPAddr("tcp4", config.Server)
	wg := &sync.WaitGroup{}
	c := make(chan os.Signal, 1)
	ctrl := make(chan bool, 1)
	signal.Notify(c, os.Interrupt, syscall.SIGTERM, syscall.SIGQUIT)

	running := true
	wg.Add(1)
	go func() {
		sig := <-c
		log.Infof("Received signal '%v', exiting\n", sig)
		running = false
		close(ctrl)
		wg.Done()
	}()

	for n := begin; n < begin+count; n++ {
		if !running {
			break
		}
		go runClient(n, &config, wg, ctrl, nil, server)
		time.Sleep(config.Interval * time.Millisecond)
	}
	wg.Wait()
}
Exemplo n.º 25
0
func log_init() {
	defer log.Flush()
	logger, e := log.LoggerFromConfigAsFile(GetConfigDir() + "/log.conf")
	if e != nil {
		log.Criticalf("Error %v", e)
	}
	log.ReplaceLogger(logger)
	//TODO timer watch config file
}
Exemplo n.º 26
0
func reloadLogConfig() {
	logger, err := seelog.LoggerFromConfigAsString(loggerConfig())

	if err == nil {
		seelog.ReplaceLogger(logger)
	} else {
		seelog.Error(err)
	}
}
Exemplo n.º 27
0
func main() {
	configFile := flag.String("cfg", "", "The config file")
	testSummary := flag.Bool("testSummary", false, "Test summary mode")
	flag.Parse()
	file, err := os.Open(*configFile)
	errHndlr(err, FATAL)
	decoder := json.NewDecoder(file)
	config := &StartupConfig{}
	err = decoder.Decode(&config)
	errHndlr(err, FATAL)

	if config.RedisInterval == 0 {
		config.RedisInterval = defaultRedisInterval
	}

	logger, err := log.LoggerFromConfigAsFile(config.SeelogConfig)
	defer log.Flush()

	if err != nil {
		panic("error reading " + config.SeelogConfig)
	}

	fmt.Println("Replacing logger, see log file according to " + config.SeelogConfig)
	if *testSummary {
		fmt.Println("WARNING: testSummary is on!")
	}
	log.ReplaceLogger(logger)

	runtime.GOMAXPROCS(runtime.NumCPU())

	runningConfig, nil := getTmData(config, true)
	go houseKeeping(runningConfig, *testSummary)

	freeList := NewPool(16, config.RedisString)
	<-time.NewTimer(time.Now().Truncate(time.Duration(config.RedisInterval) * time.Second).Add(time.Duration(config.RedisInterval) * time.Second).Sub(time.Now())).C
	tickerChan := time.Tick(time.Duration(config.RedisInterval) * time.Second)
	for now := range tickerChan {
		if now.Second() == 30 {
			trc, err := getTmData(config, false)

			if err == nil {
				runningConfig = trc
			}
		}
		for cdnName, urls := range runningConfig.HealthUrls {
			for _, url := range urls {
				// log.Info(cdnName, "   ", statName, " -> ", url)
				if *testSummary {
					fmt.Println("Skipping stat write - testSummary mode is ON!")
					continue
				}
				go rascalToRedis(cdnName, url, runningConfig.CacheGroupMap, freeList, config)
			}
		}
	}
}
Exemplo n.º 28
0
func init() {
	logger, err := log.LoggerFromConfigAsString(logConfig)

	if err != nil {
		fmt.Printf("Could not load seelog configuration: %s\n", err)
		return
	}

	log.ReplaceLogger(logger)
}
Exemplo n.º 29
0
func initializeLogging() {
	logger, err := log.LoggerFromConfigAsFile("config/logconfig.xml")

	if err != nil {
		log.Criticalf("An error occurred whilst initializing logging\n", err.Error())
		panic(err)
	}

	log.ReplaceLogger(logger)
}
Exemplo n.º 30
-1
Arquivo: notify.go Projeto: houcy/push
func main() {
	logConfigFile := flag.String("l", "./conf/log.xml", "Log config file")
	configFile := flag.String("c", "./conf/conf.json", "Config file")

	flag.Parse()

	logger, err := log.LoggerFromConfigAsFile(*logConfigFile)
	if err != nil {
		fmt.Printf("Load log config failed: (%s)\n", err)
		os.Exit(1)
	}

	log.ReplaceLogger(logger)

	err = conf.LoadConfig(*configFile)
	if err != nil {
		log.Warnf("LoadConfig (%s) failed: (%s)\n", *configFile, err)
		os.Exit(1)
	}

	http.HandleFunc("/api/v1/notify", postNotify)
	err = http.ListenAndServe(conf.Config.Notify.Addr, nil)
	if err != nil {
		log.Warnf("failed to ListenAndServe: ", err)
		os.Exit(1)
	}
}