本文整理汇总了Golang中log.Info函数的典型用法代码示例。如果您正苦于以下问题:Golang Info函数的具体用法?Golang Info怎么用?Golang Info使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了Info函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。
示例1: TestInvalidData
func TestInvalidData(t *testing.T) {
expect(t, func() {
log := NewLogger(SkipStackFrames(-1))
log.Info("foo", "a")
log.Event("")
log.Event("f\noo:")
log.Event("foo:")
log.Events("foo=", 2)
log.Gauge("\tfoo", 2)
log.Value("=foo", 2)
log.NewTiming().Say(":foo")
log.Info("foo", "a")
log.Info("foo", true, "foo")
log.Info("foo", "foo\t", "bar")
}, []string{
"ERROR " + errOddNumArgs.Error(),
"INFO foo",
"ERROR " + errKeyEmpty.Error(),
"ERROR " + errKeyInvalid.Error(),
"ERROR " + errKeyInvalid.Error(),
"ERROR " + errKeyInvalid.Error(),
"ERROR " + errKeyInvalid.Error(),
"ERROR " + errKeyInvalid.Error(),
"ERROR " + errKeyInvalid.Error(),
"ERROR " + errOddNumArgs.Error(),
"INFO foo",
"ERROR " + errKeyNotString.Error(),
"INFO foo",
"ERROR " + errKeyInvalid.Error(),
"INFO foo",
})
}
示例2: exportImage
func (e *Exporter) exportImage(name string, artifact *ct.Artifact) error {
log := e.log.New("name", name)
for _, rootfs := range artifact.Manifest().Rootfs {
for _, layer := range rootfs.Layers {
log.Info("exporting layer", "id", layer.ID)
if err := e.exportLayer(layer); err != nil {
log.Error("error exporting layer", "id", layer.ID, "err", err)
return err
}
}
}
path := e.imagePath(artifact.Manifest().ID())
if _, err := os.Stat(path); err == nil {
log.Info("manifest already exists")
return nil
}
log.Info("writing image manifest", "path", path)
if err := os.MkdirAll(filepath.Dir(path), 0755); err != nil {
log.Error("error writing image manifest", "path", path, "err", err)
return err
}
if err := ioutil.WriteFile(path, artifact.RawManifest, 0644); err != nil {
log.Error("error writing image manifest", "path", path, "err", err)
return err
}
return nil
}
示例3: babySit
func babySit(process *os.Process) int {
log := logger.New("fn", "babySit")
// Forward all signals to the app
sigchan := make(chan os.Signal, 1)
sigutil.CatchAll(sigchan)
go func() {
for sig := range sigchan {
log.Info("received signal", "type", sig)
if sig == syscall.SIGCHLD {
continue
}
log.Info("forwarding signal to command", "type", sig)
process.Signal(sig)
}
}()
// Wait for the app to exit. Also, as pid 1 it's our job to reap all
// orphaned zombies.
var wstatus syscall.WaitStatus
for {
pid, err := syscall.Wait4(-1, &wstatus, 0, nil)
if err == nil && pid == process.Pid {
break
}
}
if wstatus.Signaled() {
log.Info("command exited due to signal")
return 0
}
return wstatus.ExitStatus()
}
示例4: StreamState
func (c *ContainerInit) StreamState(arg struct{}, stream rpcplus.Stream) error {
log := logger.New("fn", "StreamState")
log.Info("starting to stream state")
ch := make(chan StateChange)
c.streamsMtx.Lock()
c.mtx.Lock()
select {
case stream.Send <- StateChange{State: c.state, Error: c.error, ExitStatus: c.exitStatus}:
log.Info("sent initial state")
case <-stream.Error:
c.mtx.Unlock()
c.streamsMtx.Unlock()
return nil
}
c.mtx.Unlock()
c.streams[ch] = struct{}{}
c.streamsMtx.Unlock()
defer func() {
log.Info("cleanup")
go func() {
// drain to prevent deadlock while removing the listener
for range ch {
}
}()
c.streamsMtx.Lock()
delete(c.streams, ch)
c.streamsMtx.Unlock()
close(ch)
}()
log.Info("waiting for state changes")
for {
select {
case change := <-ch:
select {
case stream.Send <- change:
log.Info("sent state change", "state", change.State)
case <-stream.Error:
return nil
}
case <-stream.Error:
return nil
}
}
}
示例5: Home
// Function Home - that handles a web server request for a page
func Home(w http.ResponseWriter, req *http.Request) {
io.WriteString(w, "Hello World!")
log := logrus.New()
hook, err := logrus_syslog.NewSyslogHook("udp", os.Getenv("SYSLOG_SERVER")+":"+os.Getenv("SYSLOG_PORT"), syslog.LOG_INFO, "")
if err == nil {
log.Hooks.Add(hook)
}
log.Info(req, "\n")
}
示例6: TestLogCalldepth
func TestLogCalldepth(t *testing.T) {
buf := &bytes.Buffer{}
SetBackend(NewLogBackend(buf, "", log.Lshortfile))
log := MustGetLogger("test")
log.Info("test filename")
// Verify that the correct filename is registered
if !strings.HasPrefix(buf.String(), "log_test.go:") {
t.Errorf("incorrect filename: %s", buf.String())
}
}
示例7: export
func export(args *docopt.Args) {
log := log15.New()
log.Info("decoding manifest")
var manifest map[string]*ct.Artifact
if err := cliutil.DecodeJSONArg(args.String["<manifest>"], &manifest); err != nil {
log.Error("error decoding manifest", "err", err)
os.Exit(1)
}
exporter := Exporter{
dir: args.String["<dir>"],
log: log15.New(),
}
log.Info(fmt.Sprintf("exporting %d images to %s", len(manifest), exporter.dir))
if err := exporter.Export(manifest); err != nil {
log.Error("error exporting images", "err", err)
os.Exit(1)
}
}
示例8: TestRedacted
func TestRedacted(t *testing.T) {
s := sensitive{"dupa55", "normal"}
var _ Redactor = s
for _, format := range []string{"%s", "%v", "%#v", "%q"} {
b := new(bytes.Buffer)
log := New(b, "test", DEBUG)
log.Info(format, s)
if logged := b.String(); strings.Contains(logged, s.Password) {
t.Errorf("Not redacted: %#v in %#v.", s.Password, logged)
}
}
}
示例9: makeRequest
func makeRequest(addr string, t *testing.T) {
log.Info("Sending Request: %s", addr)
res, err := http.Get(addr)
if err != nil {
t.Fatalf("Error occured: %+s", err)
}
body, err := ioutil.ReadAll(res.Body)
if err != nil {
t.Fatalf("Error occured while reading body: %+s", err)
}
t.Logf("Body response: %s", body)
}
示例10: logBroadcast
func logBroadcast(event *discoverd.Event) {
log := logger.New("fn", "broadcast")
ctx := []interface{}{
"event", event.Kind,
"service", event.Service,
}
if event.Instance != nil {
ctx = append(ctx, []interface{}{
"instance.id", event.Instance.ID,
"instance.addr", event.Instance.Addr,
}...)
}
if event.ServiceMeta != nil {
ctx = append(ctx, []interface{}{"service_meta.index", event.ServiceMeta.Index, "service_meta.data", string(event.ServiceMeta.Data)}...)
}
log.Info(fmt.Sprintf("broadcasting %s event", event.Kind), ctx...)
}
示例11: cli_db
func cli_db(fn func(*Db) error) func(*cli.Context) {
return func(c *cli.Context) {
env := cmd.Env(c)
log := logging.Open(env)
db, err := Open(env)
if err == nil {
db.Logger = log
err = fn(db)
}
if err == nil {
log.Info("Done!")
} else {
log.Error(err.Error())
}
}
}
示例12: TestLogCalldepth
func TestLogCalldepth(t *testing.T) {
buf := &bytes.Buffer{}
SetBackend(NewLogBackend(buf, "", log.Lshortfile))
SetFormatter(MustStringFormatter("%{shortfile} %{level} %{message}"))
log := MustGetLogger("test")
log.Info("test filename")
parts := strings.SplitN(buf.String(), " ", 2)
// Verify that the correct filename is registered by the stdlib logger
if !strings.HasPrefix(parts[0], "log_test.go:") {
t.Errorf("incorrect filename: %s", parts[0])
}
// Verify that the correct filename is registered by go-logging
if !strings.HasPrefix(parts[1], "log_test.go:") {
t.Errorf("incorrect filename: %s", parts[1])
}
}
示例13: mockServer
// This is a simple stand-in for the Apple feedback service that
// can be used for testing purposes.
func mockServer(cert, key string) {
crt, err := tls.X509KeyPair([]byte(cert), []byte(key))
if err != nil {
log.Fatal(err)
}
config := tls.Config{Certificates: []tls.Certificate{crt}, ClientAuth: tls.RequireAnyClientCert}
log.Info("- starting Mock Apple TCP server at " + APNSGateway)
srv, err := tls.Listen("tcp", APNSGateway, &config)
if err != nil {
log.Fatal(err)
}
for {
conn, err := srv.Accept()
if err != nil {
log.Fatal(err)
}
go loop(conn)
}
}
示例14: main
// Command veb to do things with your stuff!
// See all the commands in const, above. Also flags.
// 'veb help' for a pretty print of flags/commands on command line.
func main() {
out := log.New(os.Stdout, "", 0)
// define flags
// TODO
// - max CPUs
// - verbose
// parse flags & args
flag.Parse()
// setup goroutine parallization
// cuz it just runs on one processor out of the box...
NUM_CPUS := runtime.NumCPU()
runtime.GOMAXPROCS(NUM_CPUS)
MAX_HANDLERS = NUM_CPUS
if NUM_CPUS > 4 {
// TODO: is running on all procs a good idea? (will it starve the system?)
// using half for now
// probably go back to all when niced.
MAX_HANDLERS /= 2
}
// sanity check
if len(flag.Args()) == 0 {
// TODO
out.Fatal("INSERT HELP HERE")
}
// init is a bit different (no pre-existing index),
// so take care of it here instead of inside switch
if flag.Args()[0] == INIT {
err := Init()
if err != nil {
out.Fatal(err)
}
pwd, _ := os.Getwd()
out.Println("Initialized empty veb repository at", pwd)
return // done
}
// find veb repo
root, err := cdBaseDir()
if err != nil {
fmt.Println(err, "\n")
out.Fatal("Use 'veb init' to create this veb repository.")
}
// make the logger
logf, err := os.OpenFile(path.Join(root, veb.META_FOLDER, veb.LOG_FILE),
os.O_RDWR|os.O_APPEND|os.O_CREATE, 0644)
log := veb.NewLog(log.New(logf, "", log.LstdFlags|log.Lshortfile))
defer log.Info().Println("done\n\n")
// load the index
index, err := veb.Load(root, log)
if err != nil {
out.Fatal("veb could not load index")
}
// print intro
fmt.Println("veb repository at", root, "\n")
// act on command
switch flag.Args()[0] {
case STATUS:
err = Status(index, log)
if err != nil {
out.Fatal(err)
}
case VERIFY:
err = Verify(index, log)
if err != nil {
out.Fatal(err)
}
case COMMIT:
err = Commit(index, log)
if err != nil {
out.Fatal(err)
}
case REMOTE:
if len(flag.Args()) < 2 {
out.Fatal(REMOTE, " needs a path to the backup repository",
"\n e.g. 'veb remote ~/backups/music'")
}
err = Remote(index, flag.Args()[1], log)
if err != nil {
out.Fatal(err)
}
case PUSH:
err = Push(index, log)
if err != nil {
out.Fatal(err)
//.........这里部分代码省略.........
示例15: containerInitApp
// Run as pid 1 and monitor the contained process to return its exit code.
func containerInitApp(c *Config, logFile *os.File) error {
log := logger.New("fn", "containerInitApp")
init := newContainerInit(c, logFile)
log.Info("registering RPC server")
if err := rpcplus.Register(init); err != nil {
log.Error("error registering RPC server", "err", err)
return err
}
init.mtx.Lock()
defer init.mtx.Unlock()
// Prepare the cmd based on the given args
// If this fails we report that below
cmdPath, cmdErr := getCmdPath(c)
cmd := exec.Command(cmdPath, c.Args[1:]...)
cmd.Dir = c.WorkDir
cmd.Env = make([]string, 0, len(c.Env))
for k, v := range c.Env {
cmd.Env = append(cmd.Env, k+"="+v)
}
// App runs in its own session
cmd.SysProcAttr = &syscall.SysProcAttr{Setsid: true}
// Console setup. Hook up the container app's stdin/stdout/stderr to
// either a pty or pipes. The FDs for the controlling side of the
// pty/pipes will be passed to flynn-host later via a UNIX socket.
if c.TTY {
log.Info("creating PTY")
ptyMaster, ptySlave, err := pty.Open()
if err != nil {
log.Info("error creating PTY", "err", err)
return err
}
init.ptyMaster = ptyMaster
cmd.Stdout = ptySlave
cmd.Stderr = ptySlave
if c.OpenStdin {
log.Info("attaching stdin to PTY")
cmd.Stdin = ptySlave
cmd.SysProcAttr.Setctty = true
}
} else {
// we use syscall.Socketpair (rather than cmd.StdoutPipe) to make it easier
// for flynn-host to do non-blocking I/O (via net.FileConn) so that no
// read(2) calls can succeed after closing the logs during an update.
log.Info("creating stdout pipe")
var err error
cmd.Stdout, init.stdout, err = newSocketPair("stdout")
if err != nil {
log.Error("error creating stdout pipe", "err", err)
return err
}
log.Info("creating stderr pipe")
cmd.Stderr, init.stderr, err = newSocketPair("stderr")
if err != nil {
log.Error("error creating stderr pipe", "err", err)
return err
}
log.Info("creating FD proxies")
if err := createFDProxies(cmd); err != nil {
log.Error("error creating FD proxies", "err", err)
return err
}
if c.OpenStdin {
// Can't use cmd.StdinPipe() here, since in Go 1.2 it
// returns an io.WriteCloser with the underlying object
// being an *exec.closeOnce, neither of which provides
// a way to convert to an FD.
log.Info("creating stdin pipe")
pipeRead, pipeWrite, err := os.Pipe()
if err != nil {
log.Error("creating stdin pipe", "err", err)
return err
}
cmd.Stdin = pipeRead
init.stdin = pipeWrite
}
}
go runRPCServer()
// Wait for flynn-host to tell us to start
init.mtx.Unlock() // Allow calls
log.Info("waiting to be resumed")
<-init.resume
log.Info("resuming")
init.mtx.Lock()
if cmdErr != nil {
log.Error("command failed", "err", cmdErr)
init.changeState(StateFailed, cmdErr.Error(), -1)
init.exit(1)
}
//.........这里部分代码省略.........