當前位置: 首頁>>代碼示例>>Golang>>正文


Golang Logger.Printf方法代碼示例

本文整理匯總了Golang中log.Logger.Printf方法的典型用法代碼示例。如果您正苦於以下問題:Golang Logger.Printf方法的具體用法?Golang Logger.Printf怎麽用?Golang Logger.Printf使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在log.Logger的用法示例。


在下文中一共展示了Logger.Printf方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Golang代碼示例。

示例1: AnagramResponder

//AnagramResponder returns previous user messages with text anagramed
func AnagramResponder(e *irc.Event, con *irc.Connection, logger *log.Logger) {
	channel := e.Arguments[0]
	trimmed := strings.Trim(e.Arguments[1], " ")
	re := regexp.MustCompile("([0-9]*)*([!]+)anagram[s]*")

	if cmd := re.FindStringSubmatch(trimmed); len(cmd) == 3 {
		//Parse command
		back := -1
		if cmd[2] != "" {
			back += len(cmd[2])
		}
		if cmd[1] != "" {
			b, _ := strconv.Atoi(cmd[1])
			back += b
		}

		hh := ChannelHistory[channel]
		//Pull previous msg from history
		if back >= hh.Len() && back < 20 {
			con.Privmsg(channel, "Sorry, sheave doesn't have history recorded that far back :(")
			return
		} else if back >= hh.Len() && back > 20 {
			con.Privmsg(channel, "sheave is limited to 20 previous messages per channel")
			return
		}

		logger.Printf("Anagraming %d back in channel: %#v\n%#v\n", back, channel, hh)
		x := hh.Hist(back)

		s := AM.AnagramSentence(x)
		logger.Printf("Anagraming: %#v -> %#v\n", x, s)

		con.Privmsg(channel, "Anagramed: "+strings.Join(s, " "))
	}
}
開發者ID:Ropes,項目名稱:Sheave-Bot,代碼行數:36,代碼來源:ircbot.go

示例2: AccessLog

// Write an CLF formatted access log to 'logger'
func AccessLog(logger *log.Logger) Pipe {
	return func(conn *Conn, req *http.Request) bool {
		var remoteHost = req.RemoteAddr // FIXME
		var ident string = "-"
		var authuser string = "-"
		var now *time.Time = time.UTC()
		var timestamp string = now.Format("[07/Jan/2006:15:04:05 -0700]")
		var request string = fmt.Sprintf("%s %s %s", req.Method, req.RawURL, req.Proto)
		var status int = conn.status
		var size int64 = conn.written
		var referer string = "-"
		var userAgent string = "-"

		if len(req.Referer()) > 0 {
			referer = req.Referer()
		}

		if len(req.UserAgent()) > 0 {
			userAgent = req.UserAgent()
		}

		// Spawn a new goroutine to perform the actual print to the logfile
		// instead of making the pipeline wait.

		go func() {
			logger.Printf("%s %s %s %s \"%s\" %d %d \"%s\" \"%s\"\n",
				remoteHost, ident, authuser, timestamp, request, status, size,
				referer, userAgent)
		}()
		return true
	}
}
開發者ID:andradeandrey,項目名稱:webpipes,代碼行數:33,代碼來源:pipes.go

示例3: NewTaskRunner

// NewTaskRunner is used to create a new task context
func NewTaskRunner(logger *log.Logger, config *config.Config,
	updater TaskStateUpdater, ctx *driver.ExecContext,
	alloc *structs.Allocation, task *structs.Task,
	consulService *ConsulService) *TaskRunner {

	// Merge in the task resources
	task.Resources = alloc.TaskResources[task.Name]

	// Build the restart tracker.
	tg := alloc.Job.LookupTaskGroup(alloc.TaskGroup)
	if tg == nil {
		logger.Printf("[ERR] client: alloc '%s' for missing task group '%s'", alloc.ID, alloc.TaskGroup)
		return nil
	}
	restartTracker := newRestartTracker(tg.RestartPolicy, alloc.Job.Type)

	tc := &TaskRunner{
		config:         config,
		updater:        updater,
		logger:         logger,
		restartTracker: restartTracker,
		consulService:  consulService,
		ctx:            ctx,
		alloc:          alloc,
		task:           task,
		updateCh:       make(chan *structs.Allocation, 8),
		destroyCh:      make(chan struct{}),
		waitCh:         make(chan struct{}),
	}
	return tc
}
開發者ID:dexter-cn,項目名稱:nomad,代碼行數:32,代碼來源:task_runner.go

示例4: loadImageDataBase

func loadImageDataBase(baseDir string, objSrv objectserver.ObjectServer,
	logger *log.Logger) (*ImageDataBase, error) {
	fi, err := os.Stat(baseDir)
	if err != nil {
		return nil, errors.New(
			fmt.Sprintf("Cannot stat: %s\t%s\n", baseDir, err))
	}
	if !fi.IsDir() {
		return nil, errors.New(fmt.Sprintf("%s is not a directory\n", baseDir))
	}
	imdb := new(ImageDataBase)
	imdb.baseDir = baseDir
	imdb.imageMap = make(map[string]*image.Image)
	imdb.objectServer = objSrv
	startTime := time.Now()
	if err = imdb.scanDirectory(""); err != nil {
		return nil, err
	}
	if logger != nil {
		plural := ""
		if imdb.CountImages() != 1 {
			plural = "s"
		}
		logger.Printf("Loaded %d image%s in %s\n",
			imdb.CountImages(), plural, time.Since(startTime))
	}
	return imdb, nil
}
開發者ID:datatonic,項目名稱:Dominator,代碼行數:28,代碼來源:load.go

示例5: ListenAndServe

// ListenAndServe creates a context, registers all handlers
// using the provided routes function, and starts listening on the port
func ListenAndServe(l *log.Logger, port string, routes func(*context)) error {
	routes(&context{Logger: l})

	l.Printf("Listening on http://0.0.0.0:%s\n", port)

	return http.ListenAndServe(":"+port, nil)
}
開發者ID:stanim,項目名稱:karta,代碼行數:9,代碼來源:http.go

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

示例7: invokeEventScript

// invokeEventScript will execute the given event script with the given
// event. Depending on the event, the semantics of how data are passed
// are a bit different. For all events, the SERF_EVENT environmental
// variable is the type of the event. For user events, the SERF_USER_EVENT
// environmental variable is also set, containing the name of the user
// event that was fired.
//
// In all events, data is passed in via stdin to faciliate piping. See
// the various stdin functions below for more information.
func invokeEventScript(logger *log.Logger, script string, self serf.Member, event serf.Event) error {
	defer metrics.MeasureSince([]string{"agent", "invoke", script}, time.Now())
	var output bytes.Buffer

	// Determine the shell invocation based on OS
	var shell, flag string
	if runtime.GOOS == windows {
		shell = "cmd"
		flag = "/C"
	} else {
		shell = "/bin/sh"
		flag = "-c"
	}

	cmd := exec.Command(shell, flag, script)
	cmd.Args[0] = "serf-event"
	cmd.Env = append(os.Environ(),
		"SERF_EVENT="+event.EventType().String(),
		"SERF_SELF_NAME="+self.Name,
		"SERF_SELF_ROLE="+self.Tags["role"],
	)
	cmd.Stderr = &output
	cmd.Stdout = &output

	// Add all the tags
	for name, val := range self.Tags {
		tag_env := fmt.Sprintf("SERF_TAG_%s=%s", strings.ToUpper(name), val)
		cmd.Env = append(cmd.Env, tag_env)
	}

	stdin, err := cmd.StdinPipe()
	if err != nil {
		return err
	}

	switch e := event.(type) {
	case serf.MemberEvent:
		go memberEventStdin(logger, stdin, &e)
	case serf.UserEvent:
		cmd.Env = append(cmd.Env, "SERF_USER_EVENT="+e.Name)
		cmd.Env = append(cmd.Env, fmt.Sprintf("SERF_USER_LTIME=%d", e.LTime))
		go userEventStdin(logger, stdin, &e)
	default:
		return fmt.Errorf("Unknown event type: %s", event.EventType().String())
	}

	if err := cmd.Start(); err != nil {
		return err
	}

	err = cmd.Wait()
	logger.Printf("[DEBUG] Event '%s' script output: %s",
		event.EventType().String(), output.String())

	if err != nil {
		return err
	}

	return nil
}
開發者ID:karlgrz,項目名稱:serf,代碼行數:69,代碼來源:invoke.go

示例8: gceProjectIDFromMetadata

// gceProjectIDFromMetadata queries the metadata service on GCE to get the
// project ID (name) of an instance.
func gceProjectIDFromMetadata(logger *log.Logger) (string, error) {
	logger.Printf("[INFO] agent: Attempting to discover GCE project from metadata.")
	client := &http.Client{}

	req, err := http.NewRequest("GET", "http://metadata.google.internal/computeMetadata/v1/project/project-id", nil)
	if err != nil {
		return "", err
	}

	req.Header.Add("Metadata-Flavor", "Google")

	resp, err := client.Do(req)
	if err != nil {
		return "", err
	}

	defer resp.Body.Close()

	project, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		return "", err
	}

	logger.Printf("[INFO] agent: GCE project discovered as: %s", project)
	return string(project), nil
}
開發者ID:hashicorp,項目名稱:consul,代碼行數:28,代碼來源:command.go

示例9: gceDiscoverZones

// gceDiscoverZones discovers a list of zones from a supplied zone pattern, or
// all of the zones available to a project.
func gceDiscoverZones(logger *log.Logger, ctx context.Context, computeService *compute.Service, project, pattern string) ([]string, error) {
	var zones []string

	if pattern != "" {
		logger.Printf("[INFO] agent: Discovering zones for project %s matching pattern: %s", project, pattern)
	} else {
		logger.Printf("[INFO] agent: Discovering all zones available to project: %s", project)
	}

	call := computeService.Zones.List(project)
	if pattern != "" {
		call = call.Filter(fmt.Sprintf("name eq %s", pattern))
	}

	if err := call.Pages(ctx, func(page *compute.ZoneList) error {
		for _, v := range page.Items {
			zones = append(zones, v.Name)
		}
		return nil
	}); err != nil {
		return zones, err
	}

	logger.Printf("[INFO] agent: Discovered GCE zones: %s", strings.Join(zones, ", "))
	return zones, nil
}
開發者ID:hashicorp,項目名稱:consul,代碼行數:28,代碼來源:command.go

示例10: loginWithNameAndPwd

func loginWithNameAndPwd(r *http.Request, res http.ResponseWriter, params martini.Params, session sessions.Session, render render.Render, l *log.Logger) {
	err := r.ParseForm()
	if err != nil {
		l.Printf("ParseForm error: %v\n", err)
		render.HTML(200, "error", "登錄失敗!")
		return
	}

	username := r.PostFormValue("username")
	//password := r.PostFormValue("password")

	l.Printf("Start logging in, username = %s \n", username)
	//gitlabClient, err := gogitlab.NewGitlabByLogin(constant.GitLabHost, constant.GitLabApiPath, username, password)
	//if err != nil {
	//	l.Printf("Login error: %v\n", err)
	//	render.HTML(200, "error", "登錄失敗!")
	//	return
	//}
	//gitUser, err := gitlabClient.CurrentUser()
	//if err != nil {
	//	l.Printf("Get current error: %v\n", err)
	//	render.HTML(200, "error", "登錄失敗!")
	//	return
	//}
	uInfo := &UserInfo{}
	session.Set(constant.UserInfoKey, uInfo)
	render.HTML(200, "dashboard", uInfo)
}
開發者ID:ahmatjan,項目名稱:mycodefactory,代碼行數:28,代碼來源:webserver.go

示例11: loadFile

func (imdb *ImageDataBase) loadFile(filename string, logger *log.Logger) error {
	pathname := path.Join(imdb.baseDir, filename)
	file, err := os.Open(pathname)
	if err != nil {
		return err
	}
	defer file.Close()
	reader := fsutil.NewChecksumReader(file)
	decoder := gob.NewDecoder(reader)
	var image image.Image
	if err := decoder.Decode(&image); err != nil {
		return err
	}
	if err := reader.VerifyChecksum(); err != nil {
		if err == fsutil.ErrorChecksumMismatch {
			logger.Printf("Checksum mismatch for image: %s\n", filename)
			return nil
		}
		if err != io.EOF {
			return err
		}
	}
	image.FileSystem.RebuildInodePointers()
	if err := image.Verify(); err != nil {
		return err
	}
	imdb.Lock()
	defer imdb.Unlock()
	if imdb.scheduleExpiration(&image, filename) {
		imdb.logger.Printf("Deleting already expired image: %s\n", filename)
		return os.Remove(pathname)
	}
	imdb.imageMap[filename] = &image
	return nil
}
開發者ID:keep94,項目名稱:Dominator,代碼行數:35,代碼來源:load.go

示例12: makeProber

func makeProber(testname string, c *testConfig,
	logger *log.Logger) libprober.RegisterProber {
	switch c.Testtype {
	case "dns":
		hostname := c.Specs.Hostname
		return dnsprober.New(testname, hostname)
	case "ldap":
		sssd := c.Specs.SssdConfig
		ch := fsutil.WatchFile(sssd, logger)
		file := <-ch
		fsutil.WatchFileStop()
		return ldapprober.Makeldapprober(testname, file, c.Probefreq)
	case "pid":
		pidpath := c.Specs.Pathname
		if pidpath == "" {
			return nil
		}
		return pidprober.Makepidprober(testname, pidpath)
	case "testprog":
		testprogpath := c.Specs.Pathname
		if testprogpath == "" {
			return nil
		}
		return testprogprober.Maketestprogprober(testname, testprogpath)
	case "url":
		urlpath := c.Specs.Urlpath
		urlport := c.Specs.Urlport
		return urlprober.Makeurlprober(testname, urlpath, urlport)
	default:
		logger.Printf("Test type %s not supported", c.Testtype)
		return nil
	}
}
開發者ID:Symantec,項目名稱:health-agent,代碼行數:33,代碼來源:healthcheck.go

示例13: scannerDaemon

func scannerDaemon(rootDirectoryName string, cacheDirectoryName string,
	configuration *Configuration, fsChannel chan *FileSystem,
	logger *log.Logger) {
	if runtime.GOMAXPROCS(0) < 2 {
		runtime.GOMAXPROCS(2)
	}
	runtime.LockOSThread()
	loweredPriority := false
	var oldFS FileSystem
	for {
		fs, err := scanFileSystem(rootDirectoryName, cacheDirectoryName,
			configuration, &oldFS)
		if err != nil {
			logger.Printf("Error scanning\t%s\n", err)
		} else {
			oldFS.RegularInodeTable = fs.RegularInodeTable
			oldFS.SymlinkInodeTable = fs.SymlinkInodeTable
			oldFS.InodeTable = fs.InodeTable
			fsChannel <- fs
			if !loweredPriority {
				syscall.Setpriority(syscall.PRIO_PROCESS, 0, 10)
				loweredPriority = true
			}
		}
	}
}
開發者ID:wxdublin,項目名稱:Dominator,代碼行數:26,代碼來源:scand.go

示例14: loggingMiddleware

func loggingMiddleware(l *log.Logger, n http.Handler) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		start := time.Now()
		n.ServeHTTP(w, r)
		l.Printf("Req took %s to complete", time.Since(start))
	})
}
開發者ID:rodreegez,項目名稱:golang-middleware,代碼行數:7,代碼來源:server.go

示例15: makeHardlinks

func makeHardlinks(hardlinksToMake []sub.Hardlink, rootDirectoryName string,
	triggers *triggers.Triggers, tmpDir string, takeAction bool,
	logger *log.Logger) {
	tmpName := path.Join(tmpDir, "temporaryHardlink")
	for _, hardlink := range hardlinksToMake {
		triggers.Match(hardlink.NewLink)
		if takeAction {
			targetPathname := path.Join(rootDirectoryName, hardlink.Target)
			linkPathname := path.Join(rootDirectoryName, hardlink.NewLink)
			// A Link directly to linkPathname will fail if it exists, so do a
			// Link+Rename using a temporary filename.
			if err := fsutil.ForceLink(targetPathname, tmpName); err != nil {
				logger.Println(err)
				continue
			}
			if err := fsutil.ForceRename(tmpName, linkPathname); err != nil {
				logger.Println(err)
				if err := fsutil.ForceRemove(tmpName); err != nil {
					logger.Println(err)
				}
			} else {
				logger.Printf("Linked: %s => %s\n",
					linkPathname, targetPathname)
			}
		}
	}
}
開發者ID:datatonic,項目名稱:Dominator,代碼行數:27,代碼來源:update.go


注:本文中的log.Logger.Printf方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。