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


Golang log.Logger类代码示例

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


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

示例1: PurgeURL

func PurgeURL(url string, log *log.Logger) error {
	timeout := time.Duration(2 * time.Second)
	client := &http.Client{
		Timeout: timeout,
	}

	// Invalidate the file
	req, err := http.NewRequest("PURGE", url, nil)
	if err != nil {
		log.Println("Unable to purge " + url + ": " + err.Error())
		return err
	}

	resp, err := client.Do(req)
	if err == nil {
		defer resp.Body.Close()
	}

	if err != nil {
		log.Println("Unable to purge " + url + ": " + err.Error())
		return err
	}

	log.Println("Purging " + url + ": " + resp.Status)

	return nil
}
开发者ID:espebra,项目名称:filebin,代码行数:27,代码来源:shared.go

示例2: ZmqPubSubProxy

// ZmqPubSubProxy Implements a many-to-many device on a zmq PUB-SUB connection
func ZmqPubSubProxy(host string, portIn int, portOut int, logger *log.Logger) {
	xsub, _ := zmq.NewSocket(zmq.SUB)
	xpub, _ := zmq.NewSocket(zmq.PUB)

	defer xsub.Close()
	defer xpub.Close()

	addrIn := fmt.Sprintf("tcp://*:%d", portIn)
	addrOut := fmt.Sprintf("tcp://*:%d", portOut)

	logger.Println("ZMQ XSUB on", addrIn)
	xsub.Bind(addrIn)
	xsub.SetSubscribe("")

	logger.Println("ZMQ XPUB on", addrOut)
	xpub.Bind(addrOut)

	poller := zmq.NewPoller()
	poller.Add(xsub, zmq.POLLIN)

	for {
		// keep looping
		sockets, _ := poller.Poll(5 * time.Second)
		for _, socket := range sockets {
			switch s := socket.Socket; s {
			case xsub:
				ZmqSendMulti(xpub, ZmqRecvMulti(s))
			}
		}
	}
}
开发者ID:mahasak,项目名称:workerpoolmanager,代码行数:32,代码来源:zmqwrapper.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: 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

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

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

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

示例8: LockMetrics

func LockMetrics(logger *log.Logger, dbs []string, HOSTNAME string, dbConn *sql.DB) []Metric {
	logger.Println("get lock metrics 3.1")

	var metrics = make([]Metric, 0)

	for i := 0; i < len(dbs); i++ {
		metric := Metric{}

		var lockCount int64
		var lockType, lockMode string
		err := dbConn.QueryRow("select locktype,mode, count(*) from pg_locks, pg_database where pg_locks.database = pg_database.oid and pg_database.datname = '"+dbs[i]+"' group by pg_locks.locktype, pg_locks.mode").Scan(&lockType, &lockMode, &lockCount)
		if err != nil {
			logger.Println("error: " + err.Error())
			return metrics
		}

		metric.Hostname = HOSTNAME
		metric.MetricName = "lock_count"
		metric.Units = "count"
		metric.Value = lockCount
		metric.LockType = lockType
		metric.LockMode = lockMode
		metric.DatabaseName = dbs[i]
		metrics = append(metrics, metric)
	}

	return metrics

}
开发者ID:xraduhx,项目名称:crunchy-containers,代码行数:29,代码来源:locks.go

示例9: AddLogger

func (m *MultiLogger) AddLogger(l *log.Logger) {
	m.loggers = append(m.loggers, l)
	//Update the just added logger to be consistent with the style of the
	//rest of the loggers.
	l.SetFlags(m.loggers[0].Flags())
	l.SetPrefix(m.loggers[0].Prefix())
}
开发者ID:zeebo,项目名称:taglog,代码行数:7,代码来源:multilogger.go

示例10: incomingVoicemail

func incomingVoicemail(tc *twilio.Client, m mailgun.Mailgun, req *http.Request, log *log.Logger) {
	log.Printf("%#v", req.Form)
	transReq, err := tc.NewRequest("GET", req.FormValue("TranscriptionUrl")+".json", nil)
	if err != nil {
		log.Println("Transcription req build error:", err)
		return
	}
	var trans transcription
	_, err = tc.Do(transReq, &trans)
	if err != nil {
		log.Println("Transcription req error:", err)
		return
	}

	var buf bytes.Buffer
	err = voicemailTemplate.Execute(&buf, &voicemailData{
		From:      req.FormValue("From"),
		Duration:  trans.Duration,
		Recording: req.FormValue("RecordingUrl"),
		Text:      trans.Text,
	})
	if err != nil {
		log.Println("Email template error:", err)
		return
	}

	msg := mailgun.NewMessage("[email protected]"+emailDomain, "New voicemail from "+req.FormValue("From"), buf.String(), emailTo)
	msg.SetDKIM(true)
	_, _, err = m.Send(msg)
	if err != nil {
		log.Println("Voicemail send error:", err)
		return
	}
}
开发者ID:kelsieflynn,项目名称:twilio-forwarder,代码行数:34,代码来源:server.go

示例11: incomingEmail

func incomingEmail(tc *twilio.Client, req *http.Request, log *log.Logger) {
	if err := verifyMailgunSig(
		req.FormValue("token"),
		req.FormValue("timestamp"),
		req.FormValue("signature"),
	); err != nil {
		log.Println("Mailgun request verification failed:", err)
		return
	}

	dkim := req.FormValue("X-Mailgun-Spf")
	spf := req.FormValue("X-Mailgun-Dkim-Check-Result")
	sender := req.FormValue("sender")
	if dkim != "Pass" || spf != "Pass" || sender != emailTo {
		log.Printf("Email verification failed: SPF: %s, DKIM: %s, addr: %s", spf, dkim, sender)
		return
	}

	params := twilio.MessageParams{Body: req.FormValue("stripped-text")}
	dest := strings.SplitN(req.FormValue("recipient"), "@", 2)[0]
	_, _, err := tc.Messages.Send(smsFrom, dest, params)
	if err != nil {
		log.Println("SMS send failed:", err)
		return
	}
	log.Println("SMS sent to", dest)
}
开发者ID:kelsieflynn,项目名称:twilio-forwarder,代码行数:27,代码来源:server.go

示例12: newObjectServer

func newObjectServer(baseDir string, logger *log.Logger) (
	*ObjectServer, 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))
	}
	var objSrv ObjectServer
	objSrv.baseDir = baseDir
	objSrv.sizesMap = make(map[hash.Hash]uint64)
	if logger == nil {
		logger = log.New(os.Stdout, "", log.LstdFlags)
	}
	objSrv.logger = logger
	startTime := time.Now()
	if err = scanDirectory(&objSrv, baseDir, ""); err != nil {
		return nil, err
	}
	plural := ""
	if len(objSrv.sizesMap) != 1 {
		plural = "s"
	}
	logger.Printf("Scanned %d object%s in %s\n",
		len(objSrv.sizesMap), plural, time.Since(startTime))
	return &objSrv, nil
}
开发者ID:datatonic,项目名称:Dominator,代码行数:29,代码来源:new.go

示例13: WithLog

// WithLog is a decorator that calls Println method
// of provided logger to log received requests.
// Format is:
// <http method> <remote addr> <requested url>
func WithLog(logger *log.Logger, fn http.HandlerFunc) http.HandlerFunc {
	//TODO use constants to define format like in log package.
	return func(w http.ResponseWriter, r *http.Request) {
		logger.Println(r.Method, r.RemoteAddr, r.URL)
		fn(w, r)
	}
}
开发者ID:eraclitux,项目名称:httph,代码行数:11,代码来源:httph.go

示例14: proberLoop

func (p *proberType) proberLoop(defaultProbeInterval uint, logger *log.Logger) {
	// Set the initial probe interval to the global default, if less than the
	// interval for this prober. The probe interval will be gradually increased
	// until the target probe interval is reached. This gives faster probing at
	// startup when higher resolution may be helpful, and then backs off.
	probeInterval := time.Duration(defaultProbeInterval) * time.Second
	if probeInterval > p.probeInterval {
		probeInterval = p.probeInterval
	}
	for {
		p.probeStartTime = time.Now()
		if err := p.prober.Probe(); err != nil {
			logger.Println(err)
		}
		probeDuration := time.Since(p.probeStartTime)
		p.probeTimeDistribution.Add(probeDuration)
		time.Sleep(probeInterval - probeDuration)
		// Increase the probe interval until the interval for this prober is
		// reached.
		if probeInterval < p.probeInterval {
			probeInterval += time.Duration(defaultProbeInterval) * time.Second
		}
		if probeInterval > p.probeInterval {
			probeInterval = p.probeInterval
		}
	}
}
开发者ID:rgooch,项目名称:health-agent,代码行数:27,代码来源:impl.go

示例15: validateConfig

func validateConfig(logger *log.Logger) {
	c := nbadConfig

	if c.MessageInitBufferTimeSeconds > c.MessageCacheTTLInSeconds {
		logger.Fatalln("init buffer ttl cannot be greater than message cache ttl")
	}
}
开发者ID:JohnMurray,项目名称:nbad,代码行数:7,代码来源:config.go


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