本文整理匯總了Golang中log.Printf函數的典型用法代碼示例。如果您正苦於以下問題:Golang Printf函數的具體用法?Golang Printf怎麽用?Golang Printf使用的例子?那麽, 這裏精選的函數代碼示例或許可以為您提供幫助。
在下文中一共展示了Printf函數的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Golang代碼示例。
示例1: DeleteMessageHandler
func (s *Server) DeleteMessageHandler(w http.ResponseWriter, r *http.Request) {
login, err := getYandexLogin(r)
if login == "" || err != nil {
writeError(w, 403, "forbidden")
return
}
subject := r.FormValue("subject")
if subject != "" {
log.Printf("DELETE login=%s subject=%s", login, subject)
err = s.deleteMessagesBySubject(login, subject)
if err != nil {
writeError(w, 500, "failed to delete message: "+err.Error())
return
}
}
id := r.FormValue("id")
if id != "" {
log.Printf("DELETE login=%s id=%s", login, id)
err = s.deleteMessagesByID(login, id)
if err != nil {
writeError(w, 500, "failed to delete message: "+err.Error())
return
}
}
writeResponse(w, 200, map[string]interface{}{
"status": "success",
})
}
示例2: processTask
// Processes new tasks
func (m *etcdMinion) processTask(t *task.Task) error {
var buf bytes.Buffer
// Update state of task to indicate that we are now processing it
t.State = task.TaskStateProcessing
m.SaveTaskResult(t)
cmd := exec.Command(t.Command, t.Args...)
cmd.Stdout = &buf
cmd.Stderr = &buf
log.Printf("Processing task %s\n", t.TaskID)
cmdError := cmd.Run()
t.TimeProcessed = time.Now().Unix()
t.Result = buf.String()
if cmdError != nil {
log.Printf("Failed to process task %s\n", t.TaskID)
t.Error = cmdError.Error()
t.State = task.TaskStateFailed
} else {
log.Printf("Finished processing task %s\n", t.TaskID)
t.State = task.TaskStateSuccess
}
m.SaveTaskResult(t)
return cmdError
}
示例3: RootObject
// RootObject returns the root permanode for this importer account.
func (h *Host) RootObject() (*Object, error) {
res, err := h.search.GetPermanodesWithAttr(&search.WithAttrRequest{
N: 2, // only expect 1
Attr: "camliImportRoot",
Value: h.imp.Prefix(),
})
if err != nil {
log.Printf("RootObject searching GetPermanodesWithAttr: %v", err)
return nil, err
}
if len(res.WithAttr) == 0 {
obj, err := h.NewObject()
if err != nil {
return nil, err
}
log.Printf("No root object found. Created %v", obj.pn)
if err := obj.SetAttr("camliImportRoot", h.imp.Prefix()); err != nil {
return nil, err
}
return obj, nil
}
if len(res.WithAttr) > 1 {
return nil, fmt.Errorf("Found %d import roots for %q; want 1", len(res.WithAttr), h.imp.Prefix())
}
pn := res.WithAttr[0].Permanode
return h.ObjectFromRef(pn)
}
示例4: handleBind
func (s *Session) handleBind(stream conn.Conn, bind *proto.Bind) (err error) {
// stream.Debug("Binding new tunnel: %v", bind)
log.Printf("Binding new tunnel: %v\n", bind)
respond := func(resp *proto.BindResp) {
if err = proto.WriteMsg(stream, resp); err != nil {
err := fmt.Errorf("Failed to send bind response: %v", err)
log.Println(err)
// err = stream.Error("Failed to send bind response: %v", err)
}
}
if err = s.hooks.OnBind(s, bind); err != nil {
return
}
t, err := newTunnel(bind, s, s.binders, s.tunnelHooks)
if err != nil {
respond(&proto.BindResp{Error: err.Error()})
return
}
// t.Info("Registered new tunnel on session %s", s.id)
log.Printf("[INFO] Registered new tunnel on session %s", s.id)
// add it to the list of tunnels
s.addTunnel(t)
// acknowledge success
respond(&proto.BindResp{Url: t.url})
return
}
示例5: handleHook
func handleHook(h *hook.Hook, headers, query, payload *map[string]interface{}, body *[]byte) string {
cmd := exec.Command(h.ExecuteCommand)
cmd.Args = h.ExtractCommandArguments(headers, query, payload)
cmd.Dir = h.CommandWorkingDirectory
log.Printf("executing %s (%s) with arguments %s using %s as cwd\n", h.ExecuteCommand, cmd.Path, cmd.Args, cmd.Dir)
out, err := cmd.CombinedOutput()
log.Printf("command output: %s\n", out)
var errorResponse string
if err != nil {
log.Printf("error occurred: %+v\n", err)
errorResponse = fmt.Sprintf("%+v", err)
}
log.Printf("finished handling %s\n", h.ID)
var response []byte
response, err = json.Marshal(&hook.CommandStatusResponse{ResponseMessage: h.ResponseMessage, Output: string(out), Error: errorResponse})
if err != nil {
log.Printf("error marshalling response: %+v", err)
return h.ResponseMessage
}
return string(response)
}
示例6: resourceAwsS3BucketObjectRead
func resourceAwsS3BucketObjectRead(d *schema.ResourceData, meta interface{}) error {
s3conn := meta.(*AWSClient).s3conn
bucket := d.Get("bucket").(string)
key := d.Get("key").(string)
etag := d.Get("etag").(string)
resp, err := s3conn.HeadObject(
&s3.HeadObjectInput{
Bucket: aws.String(bucket),
Key: aws.String(key),
IfMatch: aws.String(etag),
})
if err != nil {
// If S3 returns a 404 Request Failure, mark the object as destroyed
if awsErr, ok := err.(awserr.RequestFailure); ok && awsErr.StatusCode() == 404 {
d.SetId("")
log.Printf("[WARN] Error Reading Object (%s), object not found (HTTP status 404)", key)
return nil
}
return err
}
d.Set("cache_control", resp.CacheControl)
d.Set("content_disposition", resp.ContentDisposition)
d.Set("content_encoding", resp.ContentEncoding)
d.Set("content_language", resp.ContentLanguage)
d.Set("content_type", resp.ContentType)
d.Set("version_id", resp.VersionId)
log.Printf("[DEBUG] Reading S3 Bucket Object meta: %s", resp)
return nil
}
示例7: SetClassifier
// Classifies the minion
func (m *etcdMinion) SetClassifier(c *classifier.Classifier) error {
// Classifiers in etcd expire after an hour
opts := &etcdclient.SetOptions{
PrevExist: etcdclient.PrevIgnore,
TTL: time.Hour,
}
// Serialize classifier to JSON and save it in etcd
data, err := json.Marshal(c)
if err != nil {
log.Printf("Failed to serialize classifier %s: %s\n", c.Key, err)
return err
}
// Classifier key in etcd
klassifierKey := filepath.Join(m.classifierDir, c.Key)
_, err = m.kapi.Set(context.Background(), klassifierKey, string(data), opts)
if err != nil {
log.Printf("Failed to set classifier %s: %s\n", c.Key, err)
return err
}
return nil
}
示例8: query
func (ec2 *EC2) query(params map[string]string, resp interface{}) error {
params["Version"] = "2013-02-01"
params["Timestamp"] = timeNow().In(time.UTC).Format(time.RFC3339)
endpoint, err := url.Parse(ec2.Region.EC2Endpoint)
if err != nil {
return err
}
if endpoint.Path == "" {
endpoint.Path = "/"
}
sign(ec2.Auth, "GET", endpoint.Path, params, endpoint.Host)
endpoint.RawQuery = multimap(params).Encode()
if debug {
log.Printf("get { %v } -> {\n", endpoint.String())
}
r, err := http.Get(endpoint.String())
if err != nil {
return err
}
defer r.Body.Close()
if debug {
dump, _ := httputil.DumpResponse(r, true)
log.Printf("response:\n")
log.Printf("%v\n}\n", string(dump))
}
if r.StatusCode != 200 {
return buildError(r)
}
err = xml.NewDecoder(r.Body).Decode(resp)
return err
}
示例9: realMain
// realMain is the actual entry point, but we wrap it to set
// a proper exit code on return
func realMain() int {
if len(os.Args) == 1 {
usage()
return 1
}
// Read the configuration
conf, err := getConfig()
if err != nil {
log.Printf("[ERR] %v", err)
return 1
}
// Sanity check the configuration
if errs := validateConfig(conf); len(errs) != 0 {
for _, err := range errs {
log.Printf("[ERR] %v", err)
}
return 1
}
// Start watching for changes
stopCh, finishCh := watch(conf)
// Wait for termination
return waitForTerm(conf, stopCh, finishCh)
}
示例10: RefreshCache
// RefreshCache updates the list of metric names in the cache from the local
// file store. Blocks until completion. Does not check cache freshness
// so use with care.
func (m *MetricsCacheType) RefreshCache() error {
m.lock.Lock()
m.updating = true
examine := func(path string, info os.FileInfo, err error) error {
ok, err := checkWalk(path, info, err)
if err != nil {
return err
}
if ok {
//log.Printf("Found %s or %s", path, PathToMetric(path))
m.metrics = append(m.metrics, PathToMetric(path))
}
return nil
}
// Create new empty slice
log.Printf("Scaning %s for metrics...", Prefix)
m.metrics = make([]string, 0)
err := filepath.Walk(Prefix, examine)
log.Printf("Scan complete.")
if err != nil {
log.Printf("Scan returned an Error: %s", err)
}
m.timestamp = time.Now().Unix()
m.updating = false
m.lock.Unlock()
return nil
}
示例11: populateServer
func populateServer(serv *server) []sfs.ReplicateChunkArgs {
str := fmt.Sprintf("%s:%d", serv.addr.IP.String(), serv.addr.Port)
log.Printf("master: PopulateServer: populating %s\n", str)
log.Printf("master: PopulateServer: server heap state:\n%s\n", sHeap.printPresent())
if len(chunks) == 0 {
return nil
}
thisVec := new(vector.Vector)
for _, chunk := range chunks {
//log.Printf("master: PopulateServer: examining chunk %+v, nservers %d\n", *chunk, chunk.servers.Len())
if chunk.servers.Len() < sfs.NREPLICAS {
//populate chunk location list
chunklist := make([]net.TCPAddr, chunk.servers.Len())
for cnt1 := 0; cnt1 < chunk.servers.Len(); cnt1++ {
chunklist[cnt1] = chunk.servers.At(cnt1).(*server).addr
}
//send rpc call off
thisVec.Push(sfs.ReplicateChunkArgs{chunk.chunkID, chunklist})
}
}
cnt := thisVec.Len()
thisSlice := make([]sfs.ReplicateChunkArgs, cnt)
for i := 0; i < cnt; i++ {
thisSlice[i] = thisVec.Pop().(sfs.ReplicateChunkArgs) //horribly inefficient but what can you do...
}
return thisSlice
}
示例12: Signal
func (self *Task) Signal(sig os.Signal) {
log.Printf("Signaling: %s", self.Config.ShortName)
for _, proc := range self.Running {
log.Printf("Signaled: %d - %s", proc.Process.Pid, sig)
proc.Process.Signal(sig)
}
}
示例13: GetMember
func GetMember(email, password string) (Member, error) {
log.Printf("Get member '%s' ('%s')", email, password)
db, err := GetDBConnection()
if err == nil {
defer db.Close()
pwd := sha256.Sum256([]byte(password))
log.Printf("Encrypted password: %s", hex.EncodeToString(pwd[:]))
row := db.QueryRow(`SELECT id, email, first_name
FROM Member
WHERE email = $1 AND password = $2`,
email,
hex.EncodeToString(pwd[:]),
)
result := Member{}
err = row.Scan(&result.id, &result.email, &result.firstName)
log.Printf("Err: %v", err)
if err == nil {
return result, nil
} else {
return result, errors.New("Unable to find Member with email: " + email)
}
} else {
return Member{}, errors.New("Unable to get database connection")
}
}
示例14: parser
// parser() reads all incoming messages from the consumer, and parses them into
// influxdb metric points.
func (k *Kafka) parser() {
for {
select {
case <-k.done:
return
case err := <-k.errs:
log.Printf("Kafka Consumer Error: %s\n", err.Error())
case msg := <-k.in:
points, err := jsonToPoints(msg.Value)
if err != nil {
log.Printf("Could not parse kafka message: %s, error: %s",
string(msg.Value), err.Error())
}
for _, point := range points {
select {
case k.pointChan <- point:
continue
default:
log.Printf("Kafka Consumer buffer is full, dropping a point." +
" You may want to increase the point_buffer setting")
}
}
if !k.doNotCommitMsgs {
// TODO(cam) this locking can be removed if this PR gets merged:
// https://github.com/wvanbergen/kafka/pull/84
k.Lock()
k.Consumer.CommitUpto(msg)
k.Unlock()
}
}
}
}
示例15: ensureEnvironment
//
// Make sure everything is ok to proceed.
// 1. Ensure that data directory is present and writable.
//
func ensureEnvironment(conf *Config) {
log.Printf("Checking Environment...\n")
ensureDataDir(conf)
log.Printf("done.\n")
}