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


Golang Logger.Fatal方法代码示例

本文整理汇总了Golang中log.Logger.Fatal方法的典型用法代码示例。如果您正苦于以下问题:Golang Logger.Fatal方法的具体用法?Golang Logger.Fatal怎么用?Golang Logger.Fatal使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在log.Logger的用法示例。


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

示例1: broadcastServer

func broadcastServer(conn *net.UDPConn, port string, sendChannel chan UDPMessage, networkLogger log.Logger) {
	networkLogger.Printf("Broadcasting to port %s", port)
	baddr, err := net.ResolveUDPAddr("udp", "255.255.255.255:"+port)
	if err != nil {
		networkLogger.Fatal(err)
	}

	for {
		message := <-sendChannel
		conn.WriteToUDP(message.Data, baddr)
	}
}
开发者ID:audunel,项目名称:TTK4145,代码行数:12,代码来源:network.go

示例2: main

func main() {
	var err error
	var stdout []byte
	var ps *exec.Cmd = exec.Command("ps", "aux")
	var log *logging.Logger = logging.New(os.Stderr, "",
		logging.LstdFlags|logging.Lshortfile)

	stdout, err = ps.Output()
	if err != nil {
		log.Fatal(err)
	}

	log.Println(string(stdout))
}
开发者ID:gophergala2016,项目名称:neht,代码行数:14,代码来源:main.go

示例3: newForwardInput

func newForwardInput(factory *ForwardInputFactory, logger *log.Logger, bind string, port ik.Port) (*ForwardInput, error) {
	_codec := codec.MsgpackHandle{}
	_codec.MapType = reflect.TypeOf(map[string]interface{}(nil))
	_codec.RawToString = false
	listener, err := net.Listen("tcp", bind)
	if err != nil {
		logger.Fatal(err.Error())
		return nil, err
	}
	return &ForwardInput{
		factory:  factory,
		port:     port,
		logger:   logger,
		bind:     bind,
		listener: listener,
		codec:    &_codec,
		running:  false,
		clients:  make(map[net.Conn]*forwardClient),
	}, nil
}
开发者ID:kiyoto,项目名称:ik,代码行数:20,代码来源:forward.go

示例4: messageListener

func messageListener(o *gomegle.Omegle, logger *log.Logger) {
	for {
		err := o.ShowTyping()
		if err != nil {
			logger.Print(err)
		}

		reader := bufio.NewReader(os.Stdin)
		text, err := reader.ReadString('\n')
		if err != nil {
			err = o.Disconnect()
			if err != nil {
				logger.Fatal(err)
			}
			fmt.Println("- Disconnected")
			ret := o.GetID()
			if ret != nil {
				logger.Fatal(ret)
			}
			continue
		}

		err = o.StopTyping()
		if err != nil {
			logger.Print(err)
		}

		err = o.SendMessage(text)
		if err != nil {
			logger.Fatal(err)
			continue
		}
	}
}
开发者ID:GiedriusS,项目名称:gomegle,代码行数:34,代码来源:client.go

示例5: InitJarvis

// Initialise a JarvisBot.
// lg is optional.
func InitJarvis(name string, bot *telebot.Bot, lg *log.Logger, config map[string]string) *JarvisBot {
	// We'll use random numbers throughout JarvisBot
	rand.Seed(time.Now().UTC().UnixNano())

	if lg == nil {
		lg = log.New(os.Stdout, "[jarvis] ", 0)
	}
	j := &JarvisBot{Name: name, bot: bot, log: lg, keys: config}

	j.fmap = j.getDefaultFuncMap()

	// Setup database
	// Get current executing folder
	pwd, err := osext.ExecutableFolder()
	if err != nil {
		lg.Fatalf("cannot retrieve present working directory: %s", err)
	}

	db, err := bolt.Open(path.Join(pwd, "jarvis.db"), 0600, nil)
	if err != nil {
		lg.Fatal(err)
	}
	j.db = db
	createAllBuckets(db)

	// Ensure temp directory is created.
	// This is used to store media temporarily.
	tmpDirPath := filepath.Join(pwd, TEMPDIR)
	if _, err := os.Stat(tmpDirPath); os.IsNotExist(err) {
		j.log.Printf("[%s] creating temporary directory", time.Now().Format(time.RFC3339))
		mkErr := os.Mkdir(tmpDirPath, 0775)
		if mkErr != nil {
			j.log.Printf("[%s] error creating temporary directory\n%s", time.Now().Format(time.RFC3339), err)
		}
	}

	return j
}
开发者ID:jin,项目名称:jarvisbot,代码行数:40,代码来源:jarvisbot.go

示例6: InitMorningBot

// Initialise a MorningBot.
// lg is optional.
func InitMorningBot(name string, bot *telebot.Bot, lg *log.Logger, config map[string]string) *MorningBot {
	if lg == nil {
		lg = log.New(os.Stdout, "[morningbot] ", 0)
	}
	m := &MorningBot{Name: name, bot: bot, log: lg, keys: config}

	m.fmap = m.getDefaultFuncMap()

	// Setup database
	// Get current executing folder
	pwd, err := osext.ExecutableFolder()
	if err != nil {
		lg.Fatalf("cannot retrieve present working directory: %s", err)
	}

	db, err := bolt.Open(path.Join(pwd, "morningbot.db"), 0600, nil)
	if err != nil {
		lg.Fatal(err)
	}
	m.db = db
	createAllBuckets(db)

	return m
}
开发者ID:nicluo,项目名称:morningbot,代码行数:26,代码来源:morningbot.go

示例7: processDIR

func processDIR(logger *log.Logger, wg *sync.WaitGroup, fullPath, relPath string, out chan<- []byte, semaphore chan struct{}) {
	defer wg.Done()

	// 1 for "test", 4 for coermode, coverprofile, outputdir, relpath
	args := make([]string, 1, 1+len(flag.Args())+4)
	args[0] = "test"
	args = append(args, flag.Args()...)
	args = append(args, "-covermode="+coverFlag, "-coverprofile="+pkgFilename, "-outputdir="+fullPath+"/", relPath)
	fmt.Printf("Test args: %+v\n", args)

	cmd := exec.Command("go", args...)
	if debugFlag {
		logger.Println("Processing:", strings.Join(cmd.Args, " "))
	}
	stdout, err := cmd.StdoutPipe()
	if err != nil {
		logger.Fatal("Unable to get process stdout")
	}
	go scanOutput(stdout, logger.Print)

	stderr, err := cmd.StderrPipe()
	if err != nil {
		logger.Fatal("Unable to get process stderr")
	}
	go scanOutput(stderr, logger.Print)

	if err := cmd.Run(); err != nil {
		logger.Fatal("ERROR:", err)
	}

	b, err := ioutil.ReadFile(relPath + "/profile.coverprofile")
	if err != nil {
		logger.Fatal("ERROR:", err)
	}

	out <- b

	if isLimited {
		<-semaphore
	}
}
开发者ID:go-playground,项目名称:overalls,代码行数:41,代码来源:overalls.go

示例8: getPort

func getPort(logger *log.Logger) int {
	configPath := os.Getenv("CONFIG_PATH")
	if configPath == "" {
		return defaultPort
	}

	configBytes, err := ioutil.ReadFile(configPath)
	if err != nil {
		logger.Fatal(err)
	}

	var config config
	err = yaml.Unmarshal(configBytes, &config)
	if err != nil {
		logger.Fatal(err)
	}

	if config.Port == 0 {
		logger.Fatal("Port must be set")
	}

	return config.Port
}
开发者ID:petertseng,项目名称:p2,代码行数:23,代码来源:server.go

示例9: testFiles

func testFiles(logger *log.Logger) {

	var semaphore chan struct{}

	if isLimited {
		semaphore = make(chan struct{}, concurrencyFlag)
	}

	out := make(chan []byte)
	wg := &sync.WaitGroup{}

	walker := func(path string, info os.FileInfo, err error) error {

		if !info.IsDir() {
			return nil
		}

		rel := strings.Replace(path, projectPath, "", 1)

		if _, ignore := ignores[rel]; ignore {
			return filepath.SkipDir
		}

		rel = "./" + rel

		if files, err := filepath.Glob(rel + "/*_test.go"); len(files) == 0 || err != nil {

			if err != nil {
				logger.Fatal("Error checking for test files")
			}

			if debugFlag {
				logger.Println("No Go Test files in DIR:", rel, "skipping")
			}

			return nil
		}

		wg.Add(1)

		if isLimited {
			semaphore <- struct{}{}
		}

		go processDIR(logger, wg, path, rel, out, semaphore)

		return nil
	}

	if err := filepath.Walk(projectPath, walker); err != nil {
		logger.Fatalf("\n**could not walk project path '%s'\n%s\n", projectPath, err)
	}

	go func() {
		wg.Wait()
		close(out)

		if isLimited {
			close(semaphore)
		}
	}()

	buff := bytes.NewBufferString("")

	for cover := range out {
		buff.Write(cover)
	}

	final := buff.String()
	final = modeRegex.ReplaceAllString(final, "")
	final = "mode: " + coverFlag + "\n" + final

	if err := ioutil.WriteFile(outFilename, []byte(final), 0644); err != nil {
		logger.Fatal("ERROR Writing \""+outFilename+"\"", err)
	}
}
开发者ID:go-playground,项目名称:overalls,代码行数:76,代码来源:overalls.go

示例10: DialKenwood

// Dial a packet node using a Kenwood (or similar) radio over serial
func DialKenwood(dev, mycall, targetcall string, config Config, logger *log.Logger) (*KenwoodConn, error) {
	if logger == nil {
		logger = log.New(os.Stderr, "", log.LstdFlags)
	}

	localAddr, remoteAddr := tncAddrFromString(mycall), tncAddrFromString(targetcall)
	conn := &KenwoodConn{Conn{
		localAddr:  AX25Addr{localAddr},
		remoteAddr: AX25Addr{remoteAddr},
	}}

	if dev == "socket" {
		c, err := net.Dial("tcp", "127.0.0.1:8081")
		if err != nil {
			panic(err)
		}
		conn.Conn.ReadWriteCloser = c
	} else {
		c := &serial.Config{Name: dev, Baud: int(B9600)}
		s, err := serial.OpenPort(c)
		if err != nil {
			return conn, err
		} else {
			conn.Conn.ReadWriteCloser = s
		}
	}

	conn.Write([]byte{3, 3, 3}) // ETX
	fmt.Fprint(conn, "\r\nrestart\r\n")
	for {
		line, _ := wl2k.ReadLine(conn)

		if strings.HasPrefix(line, "cmd:") {
			fmt.Fprint(conn, "ECHO OFF\r") // Don't echo commands
			fmt.Fprint(conn, "FLOW OFF\r")
			fmt.Fprint(conn, "XFLOW ON\r")    // Enable software flow control
			fmt.Fprint(conn, "LFIGNORE ON\r") // Ignore linefeed (\n)
			fmt.Fprint(conn, "AUTOLF OFF\r")  // Don't auto-insert linefeed
			fmt.Fprint(conn, "CR ON\r")
			fmt.Fprint(conn, "8BITCONV ON\r") // Use 8-bit characters

			// Return to command mode if station of current I/O stream disconnects.
			fmt.Fprint(conn, "NEWMODE ON\r")

			time.Sleep(500 * time.Millisecond)

			fmt.Fprintf(conn, "MYCALL %s\r", mycall)
			fmt.Fprintf(conn, "HBAUD %d\r", config.HBaud)
			fmt.Fprintf(conn, "PACLEN %d\r", config.PacketLength)
			fmt.Fprintf(conn, "TXDELAY %d\r", config.TXDelay/_CONFIG_TXDELAY_UNIT)
			fmt.Fprintf(conn, "PERSIST %d\r", config.Persist)
			time.Sleep(500 * time.Millisecond)

			fmt.Fprintf(conn, "SLOTTIME %d\r", config.SlotTime/_CONFIG_SLOT_TIME_UNIT)
			fmt.Fprint(conn, "FULLDUP OFF\r")
			fmt.Fprintf(conn, "MAXFRAME %d\r", config.MaxFrame)
			fmt.Fprintf(conn, "FRACK %d\r", config.FRACK/_CONFIG_FRACK_UNIT)
			fmt.Fprintf(conn, "RESPTIME %d\r", config.ResponseTime/_CONFIG_RESPONSE_TIME_UNIT)
			fmt.Fprintf(conn, "NOMODE ON\r")

			break
		}
	}
	time.Sleep(2 * time.Second)

	fmt.Fprintf(conn, "\rc %s\r", targetcall)
	for {
		line, _ := wl2k.ReadLine(conn)
		logger.Println(line)
		line = strings.TrimSpace(line)

		if strings.Contains(line, "*** CONNECTED to") {
			fmt.Fprint(conn, "TRANS\r\n")
			return conn, nil
		} else if strings.Contains(line, "*** DISCONNECTED") {
			logger.Fatal("got disconnect ", int(line[len(line)-1]))
		}
	}

	return conn, nil
}
开发者ID:LA3QMA,项目名称:wl2k-go,代码行数:82,代码来源:kenwood.go

示例11: main

func main() {
	useSyslog := flag.Bool("syslog", false, "use syslog")

	flag.Parse()

	var logger *log.Logger
	if *useSyslog {
		var err error
		logger, err = syslog.NewLogger(syslog.LOG_INFO|syslog.LOG_DAEMON, 0)
		if err != nil {
			fmt.Fprintf(os.Stderr, "Could not setup syslog logger: %v\n", err)
			os.Exit(1)
		}
	} else {
		logger = log.New(os.Stderr, "monsti ", log.LstdFlags)
	}

	// Load configuration
	if flag.NArg() != 1 {
		logger.Fatalf("Usage: %v <config_directory>\n",
			filepath.Base(os.Args[0]))
	}
	cfgPath := msettings.GetConfigPath(flag.Arg(0))
	var settings settings
	if err := msettings.LoadModuleSettings("daemon", cfgPath, &settings); err != nil {
		logger.Fatal("Could not load settings: ", err)
	}

	gettext.DefaultLocales.Domain = "monsti-daemon"
	gettext.DefaultLocales.LocaleDir = settings.Monsti.Directories.Locale

	var waitGroup sync.WaitGroup

	// Start service handler
	monstiPath := settings.Monsti.GetServicePath(service.MonstiService.String())
	monsti := new(MonstiService)
	monsti.Settings = &settings
	monsti.Logger = logger
	provider := service.NewProvider("Monsti", monsti)
	provider.Logger = logger
	if err := provider.Listen(monstiPath); err != nil {
		logger.Fatalf("service: Could not start service: %v", err)
	}
	waitGroup.Add(1)
	go func() {
		defer waitGroup.Done()
		if err := provider.Accept(); err != nil {
			logger.Fatalf("Could not accept at service: %v", err)
		}
	}()

	sessions := service.NewSessionPool(1, monstiPath)
	renderer := template.Renderer{Root: settings.Monsti.GetTemplatesPath()}

	// Init core functionality
	session, err := sessions.New()
	if err != nil {
		logger.Fatalf("Could not get session: %v", err)
	}
	if err := initNodeTypes(&settings, session, logger); err != nil {
		logger.Fatalf("Could not init node types: %v", err)
	}
	if err := initBlog(&settings, session, sessions, logger,
		&renderer); err != nil {
		logger.Fatalf("Could not init blog: %v", err)
	}

	// Wait for signals
	go func() {
		for {
			if err := session.Monsti().WaitSignal(); err != nil {
				logger.Fatalf("Could not wait for signal: %v", err)
			}
		}
	}()

	// Start modules
	monsti.moduleInit = make(map[string]chan bool)
	for _, module := range settings.Modules {
		monsti.moduleInit[module] = make(chan bool, 1)
	}
	for _, module := range settings.Modules {
		executable := "monsti-" + module
		cmd := exec.Command(executable, cfgPath)
		cmd.Stderr = moduleLog{module, logger}
		go func(module string) {
			if err := cmd.Run(); err != nil {
				logger.Fatalf("Module %q failed: %v", module, err)
			}
		}(module)
	}
	logger.Println("Waiting for modules to finish initialization...")
	for _, module := range settings.Modules {
		logger.Printf("Waiting for %q...", module)
		<-monsti.moduleInit[module]
	}

	// Setup up httpd
	handler := nodeHandler{
		Renderer: renderer,
//.........这里部分代码省略.........
开发者ID:yanap,项目名称:monsti,代码行数:101,代码来源:daemon.go

示例12:

	},
}

var putS3Cmd = &cobra.Command{
	Use:   "s3put",
	Short: "put a file to an S3 bucket",
	Long:  `put a file to an S3 bucket`,
	Run: func(cmd *cobra.Command, args []string) {
		config := awsConfig()
		if debug {
			Log.Printf("%+v\n", config)
		}
		svc := s3.New(config)
		data, err := ioutil.ReadFile(fileName)
		if err != nil {
			Log.Fatal(err)
		}
		params := &s3.PutObjectInput{
			Bucket:        aws.String(bucketName),
			Key:           aws.String(buildID),
			Body:          bytes.NewReader(data),
			ContentType:   aws.String(contentType),
			ContentLength: aws.Int64(int64(len(data))),
		}
		if debug {
			Log.Printf("%+v\n", params)
		}
		if resp, err := svc.PutObject(params); err != nil {
			Log.Printf("%+v\n", resp)
			Log.Fatal(err.Error())
		} else {
开发者ID:ae6rt,项目名称:decap,代码行数:31,代码来源:main.go

示例13: InitSlave

func InitSlave(
	slaveEvents com.SlaveEvent,
	masterEvents com.MasterEvent,
	elevatorEvents com.ElevatorEvent,
	slaveLogger log.Logger) {

	slaveLogger.Print("Waiting for master")
	sendTicker := time.NewTicker(sendInterval)

	orders := make([]order.Order, 0)

	for {
		select {
		case message := <-slaveEvents.FromMaster:
			if len(orders) == 0 {
				slaveLogger.Printf("Initiating slave, master %s", message.Address)
				remainingOrders := slaveLoop(slaveEvents, masterEvents, elevatorEvents, slaveLogger)

				slaveLogger.Print("Waiting for new master")
				for _, order := range remainingOrders {
					if order.TakenBy == myIP {
						orders = append(orders, order)
					}
				}
			}

		case <-slaveEvents.MissedDeadline:
			driver.SetMotorDirection(driver.DirnStop)
			slaveLogger.Fatal("Failed to complete order within deadline")

		case floor := <-slaveEvents.CompletedFloor:
			slaveLogger.Printf("Completed floor %d", floor+1)
			for i := 0; i < len(orders); i++ {
				order := orders[i]
				if order.TakenBy == myIP && order.Button.Floor == floor {
					orders = append(orders[:i], orders[i+1:]...)
				}
			}
			elevData := elevator.GetElevData()
			order.PrioritizeOrders(orders, myIP, elevData.LastPassedFloor, elevData.CurrentDirection)
			driver.ClearAllButtonLamps()
			for _, o := range orders {
				if o.Button.Type == driver.ButtonCallCommand && o.TakenBy != myIP {
					continue
				}
				driver.SetButtonLamp(o.Button.Type, o.Button.Floor, 1)
			}
			priority := order.GetPriority(orders, myIP)
			if priority != nil {
				elevatorEvents.NewTargetFloor <- priority.Button.Floor
			}

		case button := <-slaveEvents.ButtonPressed:
			if button.Type == driver.ButtonCallCommand {
				orders = append(orders, order.Order{Button: button, TakenBy: myIP})
				elevData := elevator.GetElevData()
				order.PrioritizeOrders(orders, myIP, elevData.LastPassedFloor, elevData.CurrentDirection)
				driver.ClearAllButtonLamps()
				for _, o := range orders {
					if o.Button.Type == driver.ButtonCallCommand && o.TakenBy != myIP {
						continue
					}
					driver.SetButtonLamp(o.Button.Type, o.Button.Floor, 1)
				}
				priority := order.GetPriority(orders, myIP)
				if priority != nil {
					elevatorEvents.NewTargetFloor <- priority.Button.Floor
				}
			}

		case <-sendTicker.C:
			data := com.SlaveData{
				ElevData: elevator.GetElevData(),
			}
			slaveEvents.ToMaster <- network.UDPMessage{
				Data: com.EncodeSlaveData(data),
			}
			elevData := elevator.GetElevData()
			order.PrioritizeOrders(orders, myIP, elevData.LastPassedFloor, elevData.CurrentDirection)
			driver.ClearAllButtonLamps()
			for _, o := range orders {
				if o.Button.Type == driver.ButtonCallCommand && o.TakenBy != myIP {
					continue
				}
				driver.SetButtonLamp(o.Button.Type, o.Button.Floor, 1)
			}
			priority := order.GetPriority(orders, myIP)
			if priority != nil {
				elevatorEvents.NewTargetFloor <- priority.Button.Floor
			}
		}
	}
}
开发者ID:audunel,项目名称:TTK4145,代码行数:93,代码来源:slave.go


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