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


Golang Logger.Print方法代码示例

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


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

示例1: DefaultFormat

// DefaultFormat returns a middleware that logs http requests
// to the given logger using the default log format.
func DefaultFormat(l *log.Logger) httpmux.MiddlewareFunc {
	return func(next http.HandlerFunc) http.HandlerFunc {
		return func(w http.ResponseWriter, r *http.Request) {
			start := time.Now()
			rw := NewResponseWriter(w)
			next(rw, r)
			b := getBuffer()
			b.WriteString(r.Proto)
			b.Write([]byte(" "))
			b.WriteString(strconv.Itoa(rw.Code()))
			b.Write([]byte(" "))
			b.WriteString(r.Method)
			b.Write([]byte(" "))
			b.WriteString(r.URL.RequestURI())
			b.Write([]byte(" from "))
			b.WriteString(r.RemoteAddr)
			b.Write([]byte(" "))
			fmt.Fprintf(b, "%q", r.Header.Get("User-Agent"))
			b.Write([]byte(" "))
			b.WriteString(strconv.Itoa(rw.Bytes()))
			b.Write([]byte(" bytes in "))
			b.WriteString(time.Since(start).String())
			if err := httpmux.Context(r).Value(ErrorID); err != nil {
				fmt.Fprintf(b, " err: %v", err)
			}
			l.Print(b.String())
			putBuffer(b)
		}
	}
}
开发者ID:fiorix,项目名称:sms-api-server,代码行数:32,代码来源:default.go

示例2: notify

func notify(config localConfig, hook hookEvent, ws, logDir string, notification grimNotification, logger *log.Logger) error {
	if hook.EventName != "push" && hook.EventName != "pull_request" {
		return nil
	}

	ghErr := setRefStatus(config.gitHubToken(), hook.Owner, hook.Repo, hook.StatusRef, notification.GithubRefStatus(), "", "")

	context := buildContext(hook, ws, logDir)
	message, color, err := notification.HipchatNotification(context, config)
	logger.Print(message)

	if config.hipChatToken() != "" && config.hipChatRoom() != "" {
		if err != nil {
			logger.Printf("Hipchat: Error while rendering message: %v", err)
			return err
		}

		err = sendMessageToRoom(config.hipChatToken(), config.hipChatRoom(), config.grimServerID(), message, color)
		if err != nil {
			logger.Printf("Hipchat: Error while sending message to room: %v", err)
			return err
		}
	} else {
		logger.Print("HipChat: config.hipChatToken and config.hitChatRoom not set")
	}

	return ghErr
}
开发者ID:jhannah,项目名称:grim,代码行数:28,代码来源:notify.go

示例3: Print

// Print calls Print on a logger or the default logger.
// Arguments are handled in the manner of fmt.Print.
func Print(l *log.Logger, v ...interface{}) {
	if l == nil {
		log.Print(v...)
	} else {
		l.Print(v...)
	}
}
开发者ID:startupit69,项目名称:go-capnproto2,代码行数:9,代码来源:logutil.go

示例4: StartWorker

func StartWorker(CacheInvalidation bool, WorkQueue chan File, log *log.Logger) {
	var err error
	for {
		select {
		case f := <-WorkQueue:
			startTime := time.Now().UTC()

			jobId := "b-" + randomString(5) + " "
			log.SetPrefix(jobId)

			log.Print("Batch process starting: " + f.Tag + ", " + f.Filename)
			// Simulate some processing time
			if f.MediaType() == "image" {
				err = f.GenerateImage(75, 75, true)
				if err != nil {
					log.Print(err)
				}
				err = f.GenerateImage(1140, 0, false)
				if err != nil {
					log.Print(err)
				}

				if CacheInvalidation {
					if err := f.Purge(); err != nil {
						log.Print(err)
					}
				}
			}
			finishTime := time.Now().UTC()
			elapsedTime := finishTime.Sub(startTime)
			log.Println("Completed in: " + elapsedTime.String())
		}
	}
}
开发者ID:denisbr,项目名称:filebin,代码行数:34,代码来源:batch.go

示例5: LoginHandler

func LoginHandler(w http.ResponseWriter, r *http.Request, session sessions.Session, log *log.Logger) string {
	c, err := config.ReadDefault("users.cfg")

	if err != nil {
		return "Can't login. Problems reading user and password."
	}

	username := r.FormValue("username")
	password := r.FormValue("password")

	allowedUsername, _ := c.RawStringDefault("user")
	allowedPassword, _ := c.RawStringDefault("password")

	if username == allowedUsername && password == allowedPassword {

		log.Print("User WAS logged in.")

		session.Set("username", username)
		session.Set("password", password)
		http.Redirect(w, r, "/home", http.StatusFound)
		return "OK"
	}

	log.Print("User wasn't logged in. User " + username + " and password " + password)

	http.Redirect(w, r, "/login", http.StatusFound)
	return "Username or password incorrect"
}
开发者ID:patrickdappollonio,项目名称:projects,代码行数:28,代码来源:handlers.go

示例6: addCategories

func addCategories(files []fileData, client *mwclient.Client, verbose *log.Logger, catFileLimit int32, allCategories map[string]bool, catCounts map[string]int32, stats *stats) {
	for i := range files {
		if files[i].processed {
			continue
		}
		// The cat size limit needs to be checked again, since adding
		// previous files in the batch may have pushed it over the
		// limit.
		if catFileLimit > 0 && catCounts[files[i].catMapped] >= catFileLimit {
			stats.populated++
			verbose.Print(files[i].title, "\n", "Already populated: ", files[i].catMapped)
		} else {
			// Identifying emtpy categories helps identify
			// when we are adding a file to a redirect page
			// for a renamed category.
			if catCounts[files[i].catMapped] == 0 {
				warn.Print(files[i].title, "\n", "Adding to empty ", files[i].catMapped)
				files[i].warning = "Added to empty category"
				stats.warnings++
			} else {
				verbose.Printf("%s\nAdding to %s (%d files)", files[i].title, files[i].catMapped, int(catCounts[files[i].catMapped]))
			}
			stats.edited++
			addCategory(files[i].title, files[i].catMapped, client)
			incCatCount(files[i].catMapped, catCounts)
		}
		files[i].processed = true
	}
}
开发者ID:garyhouston,项目名称:takenwith,代码行数:29,代码来源:takenwith.go

示例7: 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

示例8: matchCategories

// Determine if any of cats (a file's current categories) match either the
// Exif target category, any known target category, or any unknown category
// that's named like a target category.
func matchCategories(file *fileData, cats []string, mapped string, verbose *log.Logger, ignoreCurrentCats bool, allCategories map[string]bool, stats *stats) bool {
	result := false
	for _, cat := range cats {
		if mapped == cat {
			stats.inCat++
			verbose.Print(file.title, "\n", "Already in mapped: ", mapped)
			result = true
			break
		}
		if !ignoreCurrentCats {
			if allCategories[cat] {
				result = true
				stats.inCat++
				verbose.Print(file.title, "\n", "Already in known: ", cat)
				break
			}
			if strings.HasPrefix(cat, "Category:Taken ") || strings.HasPrefix(cat, "Category:Scanned ") {
				result = true
				warn.Print(file.title, "\n", "Already in unknown: ", cat)
				file.warning = "In unknown " + cat
				stats.warnings++
				break
			}
		}
	}
	return result
}
开发者ID:garyhouston,项目名称:takenwith,代码行数:30,代码来源:takenwith.go

示例9: createContainer

// createContainer initializes a struct needed to call docker.client.CreateContainer()
func createContainer(ctx *ExecContext, task *structs.Task, logger *log.Logger) docker.CreateContainerOptions {
	if task.Resources == nil {
		panic("task.Resources is nil and we can't constrain resource usage. We shouldn't have been able to schedule this in the first place.")
	}

	hostConfig := createHostConfig(task)
	logger.Printf("[DEBUG] driver.docker: using %d bytes memory for %s", hostConfig.Memory, task.Config["image"])
	logger.Printf("[DEBUG] driver.docker: using %d cpu shares for %s", hostConfig.CPUShares, task.Config["image"])

	// Setup port mapping (equivalent to -p on docker CLI). Ports must already be
	// exposed in the container.
	if len(task.Resources.Networks) == 0 {
		logger.Print("[WARN] driver.docker: No networks are available for port mapping")
	} else {
		network := task.Resources.Networks[0]
		dockerPorts := map[docker.Port][]docker.PortBinding{}

		for _, port := range network.ListStaticPorts() {
			dockerPorts[docker.Port(strconv.Itoa(port)+"/tcp")] = []docker.PortBinding{docker.PortBinding{HostIP: network.IP, HostPort: strconv.Itoa(port)}}
			dockerPorts[docker.Port(strconv.Itoa(port)+"/udp")] = []docker.PortBinding{docker.PortBinding{HostIP: network.IP, HostPort: strconv.Itoa(port)}}
			logger.Printf("[DEBUG] driver.docker: allocated port %s:%d -> %d (static) %s\n", network.IP, port, port)
		}

		for label, port := range network.MapDynamicPorts() {
			// If the label is numeric we expect that there is a service
			// listening on that port inside the container. In this case we'll
			// setup a mapping from our random host port to the label port.
			//
			// Otherwise we'll setup a direct 1:1 mapping from the host port to
			// the container, and assume that the process inside will read the
			// environment variable and bind to the correct port.
			if _, err := strconv.Atoi(label); err == nil {
				dockerPorts[docker.Port(label+"/tcp")] = []docker.PortBinding{docker.PortBinding{HostIP: network.IP, HostPort: strconv.Itoa(port)}}
				dockerPorts[docker.Port(label+"/udp")] = []docker.PortBinding{docker.PortBinding{HostIP: network.IP, HostPort: strconv.Itoa(port)}}
				logger.Printf("[DEBUG] driver.docker: allocated port %s:%d -> %s (mapped)", network.IP, port, label)
			} else {
				dockerPorts[docker.Port(strconv.Itoa(port)+"/tcp")] = []docker.PortBinding{docker.PortBinding{HostIP: network.IP, HostPort: strconv.Itoa(port)}}
				dockerPorts[docker.Port(strconv.Itoa(port)+"/udp")] = []docker.PortBinding{docker.PortBinding{HostIP: network.IP, HostPort: strconv.Itoa(port)}}
				logger.Printf("[DEBUG] driver.docker: allocated port %s:%d -> %d for label %s\n", network.IP, port, port, label)
			}
		}
		hostConfig.PortBindings = dockerPorts
	}

	config := &docker.Config{
		Env:   TaskEnvironmentVariables(ctx, task).List(),
		Image: task.Config["image"],
	}

	// If the user specified a custom command to run, we'll inject it here.
	if command, ok := task.Config["command"]; ok {
		config.Cmd = strings.Split(command, " ")
	}

	return docker.CreateContainerOptions{
		Config:     config,
		HostConfig: hostConfig,
	}
}
开发者ID:rbramwell,项目名称:nomad,代码行数:60,代码来源:docker.go

示例10: AddServiceEndpointLoggingMiddleware

func AddServiceEndpointLoggingMiddleware(logger log.Logger) endpoint.Middleware {
	return func(next endpoint.Endpoint) endpoint.Endpoint {
		return func(ctx context.Context, request interface{}) (interface{}, error) {
			logger.Print("calling endpoint")
			defer logger.Print("called endpoint")
			return next(ctx, request)
		}
	}
}
开发者ID:JosephSalisbury,项目名称:gokit-example,代码行数:9,代码来源:logging.go

示例11: NewWebServer

// Returns a new server with the given name and empty cache
// It serves the files in the directory given when is created
func NewWebServer(dir string, logger log.Logger) *Server {

	server := &Server{}
	server.pwd = dir
	server.cache = NewCache()
	// server.sessions
	server.logger = logger

	logger.Print("Server created")
	return server
}
开发者ID:kthristov,项目名称:kt-server,代码行数:13,代码来源:kt-server.go

示例12: runTriggers

func runTriggers(triggers []*triggers.Trigger, action string,
	logger *log.Logger) bool {
	hadFailures := false
	needRestart := false
	logPrefix := ""
	if *disableTriggers {
		logPrefix = "Disabled: "
	}
	// For "start" action, if there is a reboot trigger, just do that one.
	if action == "start" {
		for _, trigger := range triggers {
			if trigger.Service == "reboot" {
				logger.Print(logPrefix, "Rebooting")
				if *disableTriggers {
					return hadFailures
				}
				if !runCommand(logger, "reboot") {
					hadFailures = true
				}
				return hadFailures
			}
		}
	}
	ppid := fmt.Sprint(os.Getppid())
	for _, trigger := range triggers {
		if trigger.Service == "reboot" && action == "stop" {
			continue
		}
		if trigger.Service == "subd" {
			// Never kill myself, just restart.
			if action == "start" {
				needRestart = true
			}
			continue
		}
		logger.Printf("%sAction: service %s %s\n",
			logPrefix, trigger.Service, action)
		if *disableTriggers {
			continue
		}
		if !runCommand(logger,
			"run-in-mntns", ppid, "service", trigger.Service, action) {
			hadFailures = true
		}
	}
	if needRestart {
		logger.Printf("%sAction: service subd restart\n", logPrefix)
		if !runCommand(logger,
			"run-in-mntns", ppid, "service", "subd", "restart") {
			hadFailures = true
		}
	}
	return hadFailures
}
开发者ID:keep94,项目名称:Dominator,代码行数:54,代码来源:update.go

示例13: fwdSignal

func fwdSignal(logger *log.Logger, command *exec.Cmd, sig os.Signal) {
	switch sig {
	case os.Interrupt, syscall.SIGTERM, syscall.SIGCHLD:
		return
	}
	if err := command.Process.Signal(sig); err != nil {
		logger.Printf("glock: Error while sending signal %s: %s", sig, err.Error())
	}
	if sig == syscall.SIGTSTP {
		logger.Print("glock: SIGTSTP sent to child process, but will continue to send heartbeats for the locks")
	}
}
开发者ID:gbagnoli,项目名称:glock,代码行数:12,代码来源:manager_exec.go

示例14: ApacheCommonFormat

// ApacheCommonFormat returns a middleware that logs http requests
// to the given logger using the Apache Common log format.
func ApacheCommonFormat(l *log.Logger) httpmux.MiddlewareFunc {
	return func(next http.HandlerFunc) http.HandlerFunc {
		return func(w http.ResponseWriter, r *http.Request) {
			start := time.Now()
			rw := NewResponseWriter(w)
			next(rw, r)
			b := apacheCommonLog(rw, r, start)
			l.Print(b.String())
			putBuffer(b)
		}
	}
}
开发者ID:fiorix,项目名称:sms-api-server,代码行数:14,代码来源:apache.go

示例15: saveToFile

func saveToFile(data com.MasterData, masterLogger log.Logger) {
	file, err := os.Create("backupData.json")
	if err != nil {
		masterLogger.Print(err)
	}
	buf, err := json.Marshal(data)
	if err != nil {
		masterLogger.Print(err)
	}
	file.Write(buf)
	file.Close()
}
开发者ID:audunel,项目名称:TTK4145,代码行数:12,代码来源:master.go


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