本文整理汇总了Golang中log.SetOutput函数的典型用法代码示例。如果您正苦于以下问题:Golang SetOutput函数的具体用法?Golang SetOutput怎么用?Golang SetOutput使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了SetOutput函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。
示例1: TestPause
func TestPause(t *testing.T) {
log.SetOutput(ioutil.Discard)
defer log.SetOutput(os.Stdout)
_, _, nsqd := mustStartNSQD(NewNSQDOptions())
defer nsqd.Exit()
topicName := "test_topic_pause" + strconv.Itoa(int(time.Now().Unix()))
topic := nsqd.GetTopic(topicName)
err := topic.Pause()
assert.Equal(t, err, nil)
channel := topic.GetChannel("ch1")
assert.NotEqual(t, channel, nil)
msg := nsq.NewMessage(<-nsqd.idChan, []byte("aaaaaaaaaaaaaaaaaaaaaaaaaaa"))
err = topic.PutMessage(msg)
assert.Equal(t, err, nil)
time.Sleep(15 * time.Millisecond)
assert.Equal(t, topic.Depth(), int64(1))
assert.Equal(t, channel.Depth(), int64(0))
err = topic.UnPause()
assert.Equal(t, err, nil)
time.Sleep(15 * time.Millisecond)
assert.Equal(t, topic.Depth(), int64(0))
assert.Equal(t, channel.Depth(), int64(1))
}
示例2: supressOutput
// Supress output of function to keep logs clean
func supressOutput(f func()) {
old := os.Stdout
oldErr := os.Stderr
r, w, _ := os.Pipe()
os.Stdout = w
os.Stderr = w
l.SetOutput(w)
f()
outC := make(chan string)
// copy the output in a separate goroutine so printing can't block indefinitely
go func() {
var buf bytes.Buffer
io.Copy(&buf, r)
o := buf.String()
log.Trace(o)
outC <- o
}()
// log to TRACE
// back to normal state
w.Close()
os.Stdout = old
os.Stderr = oldErr
l.SetOutput(old)
}
示例3: BenchmarkTopicToChannelPut
func BenchmarkTopicToChannelPut(b *testing.B) {
b.StopTimer()
log.SetOutput(ioutil.Discard)
defer log.SetOutput(os.Stdout)
topicName := "bench_topic_to_channel_put" + strconv.Itoa(b.N)
channelName := "bench"
options := NewNSQDOptions()
options.MemQueueSize = int64(b.N)
_, _, nsqd := mustStartNSQD(options)
defer nsqd.Exit()
channel := nsqd.GetTopic(topicName).GetChannel(channelName)
b.StartTimer()
for i := 0; i <= b.N; i++ {
topic := nsqd.GetTopic(topicName)
msg := nsq.NewMessage(<-nsqd.idChan, []byte("aaaaaaaaaaaaaaaaaaaaaaaaaaa"))
topic.PutMessage(msg)
}
for {
if len(channel.memoryMsgChan) == b.N {
break
}
runtime.Gosched()
}
}
示例4: TestBasicV2
// exercise the basic operations of the V2 protocol
func TestBasicV2(t *testing.T) {
log.SetOutput(ioutil.Discard)
defer log.SetOutput(os.Stdout)
options := NewNsqdOptions()
options.clientTimeout = 60 * time.Second
tcpAddr, _, nsqd := mustStartNSQd(options)
defer nsqd.Exit()
topicName := "test_v2" + strconv.Itoa(int(time.Now().Unix()))
topic := nsqd.GetTopic(topicName)
msg := nsq.NewMessage(<-nsqd.idChan, []byte("test body"))
topic.PutMessage(msg)
conn, err := mustConnectNSQd(tcpAddr)
assert.Equal(t, err, nil)
identify(t, conn)
sub(t, conn, topicName, "ch")
err = nsq.Ready(1).Write(conn)
assert.Equal(t, err, nil)
resp, err := nsq.ReadResponse(conn)
assert.Equal(t, err, nil)
frameType, data, err := nsq.UnpackResponse(resp)
msgOut, _ := nsq.DecodeMessage(data)
assert.Equal(t, frameType, nsq.FrameTypeMessage)
assert.Equal(t, msgOut.Id, msg.Id)
assert.Equal(t, msgOut.Body, msg.Body)
assert.Equal(t, msgOut.Attempts, uint16(1))
}
示例5: TestStats
func TestStats(t *testing.T) {
log.SetOutput(ioutil.Discard)
defer log.SetOutput(os.Stdout)
options := NewNsqdOptions()
tcpAddr, _, nsqd := mustStartNSQd(options)
defer nsqd.Exit()
topicName := "test_stats" + strconv.Itoa(int(time.Now().Unix()))
topic := nsqd.GetTopic(topicName)
msg := nsq.NewMessage(<-nsqd.idChan, []byte("test body"))
topic.PutMessage(msg)
conn, err := mustConnectNSQd(tcpAddr)
assert.Equal(t, err, nil)
identify(t, conn)
sub(t, conn, topicName, "ch")
stats := nsqd.getStats()
assert.Equal(t, len(stats), 1)
assert.Equal(t, len(stats[0].Channels), 1)
assert.Equal(t, len(stats[0].Channels[0].Clients), 1)
log.Printf("stats: %+v", stats)
}
示例6: TestChunkedResponseHeaders
func TestChunkedResponseHeaders(t *testing.T) {
log.SetOutput(ioutil.Discard) // is noisy otherwise
defer log.SetOutput(os.Stderr)
ts := httptest.NewServer(HandlerFunc(func(w ResponseWriter, r *Request) {
w.Header().Set("Content-Length", "intentional gibberish") // we check that this is deleted
w.(Flusher).Flush()
fmt.Fprintf(w, "I am a chunked response.")
}))
defer ts.Close()
res, err := Get(ts.URL)
if err != nil {
t.Fatalf("Get error: %v", err)
}
if g, e := res.ContentLength, int64(-1); g != e {
t.Errorf("expected ContentLength of %d; got %d", e, g)
}
if g, e := res.TransferEncoding, []string{"chunked"}; !reflect.DeepEqual(g, e) {
t.Errorf("expected TransferEncoding of %v; got %v", e, g)
}
if _, haveCL := res.Header["Content-Length"]; haveCL {
t.Errorf("Unexpected Content-Length")
}
}
示例7: main
func main() {
flag.Parse()
if *jsonFlag {
doc, _ := registryEntry.JSON()
fmt.Println(string(doc))
os.Exit(0)
}
log.SetFlags(0)
if *debug {
log.SetOutput(os.Stdout)
} else {
log.SetOutput(ioutil.Discard)
}
validateArgs()
// Communication channels
inCh = make(chan bool)
outCh = make(chan bool)
exitCh = make(chan os.Signal, 1)
// Start the communication & processing logic
go mainLoop()
// Wait for the end...
signal.Notify(exitCh, os.Interrupt, syscall.SIGTERM)
<-exitCh
log.Println("Done")
}
示例8: logIRC
func logIRC(irc map[string]string) {
if _, err := os.Stat("./logs"); err != nil {
if os.IsNotExist(err) {
color.Green("Creating directory logs")
os.Mkdir("./logs", 0766)
}
}
if strings.HasPrefix(irc["params"], "#") {
s := strings.Split(irc["params"], " ")
f, err := os.OpenFile("logs/"+s[0]+".log", os.O_WRONLY|os.O_CREATE|os.O_APPEND, 0666)
if err != nil {
log.Fatalf("Error opening logfile for %s: %v", irc["params"], err)
}
log.SetOutput(f)
log.Printf("%s %s %s %s\n", irc["prefix"], irc["command"], irc["params"], irc["trailing"])
defer f.Close()
} else {
f, err := os.OpenFile("logs/all.log", os.O_WRONLY|os.O_CREATE|os.O_APPEND, 0666)
if err != nil {
log.Fatalf("Error opening logfile all: %v", err)
}
log.SetOutput(f)
log.Printf("%s %s %s %s %s\n", irc["tags"], irc["prefix"], irc["command"], irc["params"], irc["trailing"])
defer f.Close()
}
}
示例9: main
func main() {
flag.Parse() // called here in main() to allow other packages to set flags in their inits
caddy.AppName = appName
caddy.AppVersion = appVersion
// set up process log before anything bad happens
switch logfile {
case "stdout":
log.SetOutput(os.Stdout)
case "stderr":
log.SetOutput(os.Stderr)
case "":
log.SetOutput(ioutil.Discard)
default:
file, err := os.OpenFile(logfile, os.O_RDWR|os.O_CREATE|os.O_APPEND, 0644)
if err != nil {
log.Fatalf("Error opening log file: %v", err)
}
log.SetOutput(file)
}
if version {
fmt.Printf("%s %s\n", caddy.AppName, caddy.AppVersion)
os.Exit(0)
}
if revoke != "" {
err := letsencrypt.Revoke(revoke)
if err != nil {
log.Fatal(err)
}
fmt.Printf("Revoked certificate for %s\n", revoke)
os.Exit(0)
}
// Set CPU cap
err := setCPU(cpu)
if err != nil {
mustLogFatal(err)
}
// Get Caddyfile input
caddyfile, err := caddy.LoadCaddyfile(loadCaddyfile)
if err != nil {
mustLogFatal(err)
}
// Start your engines
err = caddy.Start(caddyfile)
if err != nil {
if caddy.IsRestart() {
log.Printf("[ERROR] Upon starting %s: %v", appName, err)
} else {
mustLogFatal(err)
}
}
// Twiddle your thumbs
caddy.Wait()
}
示例10: TestSnagInit
func TestSnagInit(t *testing.T) {
buf := bytes.NewBuffer(nil)
log.SetOutput(buf)
defer log.SetOutput(os.Stdout)
wd, tmpDir := tmpDirectory(t)
defer os.RemoveAll(tmpDir)
chdir(t, tmpDir)
defer os.Chdir(wd)
_, err := os.Stat(SnagFile)
assert.True(t, os.IsNotExist(err))
err = initSnag()
require.NoError(t, err)
assert.Contains(t, buf.String(), "Success")
_, err = os.Stat(SnagFile)
require.NoError(t, err)
err = initSnag()
require.Error(t, err)
assert.Contains(t, err.Error(), "file already exists")
}
示例11: TestTombstonedNodes
func TestTombstonedNodes(t *testing.T) {
log.SetOutput(ioutil.Discard)
defer log.SetOutput(os.Stdout)
tcpAddr, httpAddr := mustStartLookupd()
defer lookupd.Exit()
lookupd.inactiveProducerTimeout = 50 * time.Millisecond
lookupdHTTPAddrs := []string{fmt.Sprintf("%s", httpAddr)}
topicName := "inactive_nodes"
conn := mustConnectLookupd(t, tcpAddr)
identify(t, conn, "ip.address", 5000, 5555, "fake-version")
nsq.Register(topicName, "channel1").Write(conn)
_, err := nsq.ReadResponse(conn)
assert.Equal(t, err, nil)
producers, _ := lookuputil.GetLookupdProducers(lookupdHTTPAddrs)
assert.Equal(t, len(producers), 1)
assert.Equal(t, len(producers[0].Topics), 1)
assert.Equal(t, producers[0].Topics[0].Topic, topicName)
assert.Equal(t, producers[0].Topics[0].Tombstoned, false)
endpoint := fmt.Sprintf("http://%s/tombstone_topic_producer?topic=%s&node=%s", httpAddr, topicName, "ip.address:5555")
_, err = nsq.ApiRequest(endpoint)
assert.Equal(t, err, nil)
producers, _ = lookuputil.GetLookupdProducers(lookupdHTTPAddrs)
assert.Equal(t, len(producers), 1)
assert.Equal(t, len(producers[0].Topics), 1)
assert.Equal(t, producers[0].Topics[0].Topic, topicName)
assert.Equal(t, producers[0].Topics[0].Tombstoned, true)
}
示例12: TestReverseProxyInsecureSkipVerify
func TestReverseProxyInsecureSkipVerify(t *testing.T) {
log.SetOutput(ioutil.Discard)
defer log.SetOutput(os.Stderr)
var requestReceived bool
backend := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
requestReceived = true
w.Write([]byte("Hello, client"))
}))
defer backend.Close()
// set up proxy
p := &Proxy{
Upstreams: []Upstream{newFakeUpstream(backend.URL, true)},
}
// create request and response recorder
r, err := http.NewRequest("GET", "/", nil)
if err != nil {
t.Fatalf("Failed to create request: %v", err)
}
w := httptest.NewRecorder()
p.ServeHTTP(w, r)
if !requestReceived {
t.Error("Even with insecure HTTPS, expected backend to receive request, but it didn't")
}
}
示例13: TestPutMessage
func TestPutMessage(t *testing.T) {
log.SetOutput(ioutil.Discard)
defer log.SetOutput(os.Stdout)
sb := NewScalingBloom(1000, 0.5, "testbloom.bin")
if sb == nil {
t.Fatalf("NewScalingBloom failed")
}
key := []byte("test")
if sb.Check(key) != false {
t.Fatalf("Check failed")
}
if sb.Add(key, 1) != true {
t.Fatalf("Add failed")
}
if sb.Check(key) != true {
t.Fatalf("'%s' not found", key)
}
if sb.Remove(key, 1) != true {
t.Fatalf("Remove failed")
}
if sb.Check(key) != false {
t.Fatalf("'%s' was found (after remove)", key)
}
}
示例14: captureOutput
func captureOutput(f func()) string {
var buf bytes.Buffer
log.SetOutput(&buf)
f()
log.SetOutput(os.Stderr)
return buf.String()
}
示例15: Test_aggWorkerProcessOrForward
func Test_aggWorkerProcessOrForward(t *testing.T) {
saveFn := aggWorkerForwardACToNode
forward, fwErr := 0, error(nil)
aggWorkerForwardACToNode = func(ac *aggregator.Command, node *cluster.Node, snd chan *cluster.Msg) error {
forward++
return fwErr
}
ac := aggregator.NewCommand(aggregator.CmdAdd, "foo", 123)
agg := &fakeAggregatorer{}
aggDd := &distDatumAggregator{agg}
// cluster
clstr := &fakeCluster{}
md := make([]byte, 20)
md[0] = 1 // Ready
node := &cluster.Node{Node: &memberlist.Node{Meta: md, Name: "local"}}
clstr.nodesForDd = []*cluster.Node{node}
clstr.ln = node
// Test if we are LocalNode
aggWorkerProcessOrForward(ac, aggDd, clstr, nil)
aggWorkerProcessOrForward(ac, aggDd, clstr, nil)
if agg.pcCalled < 1 {
t.Errorf("aggWorkerProcessOrForward: agg.ProcessCmd() not called")
}
// Now test we are NOT LN, forward
remote := &cluster.Node{Node: &memberlist.Node{Meta: md, Name: "remote"}}
clstr.nodesForDd = []*cluster.Node{remote}
n := aggWorkerProcessOrForward(ac, aggDd, clstr, nil)
if forward != 1 {
t.Errorf("aggWorkerProcessOrForward: aggWorkerForwardDPToNode not called")
}
if n != 1 {
t.Errorf("aggWorkerProcessOrForward: return value != 1")
}
fl := &fakeLogger{}
log.SetOutput(fl)
defer func() {
// restore default output
log.SetOutput(os.Stderr)
}()
fwErr = fmt.Errorf("some error")
n = aggWorkerProcessOrForward(ac, aggDd, clstr, nil)
if n != 0 {
t.Errorf("aggWorkerProcessOrForward: return value != 0")
}
if !strings.Contains(string(fl.last), "some error") {
t.Errorf("aggWorkerProcessOrForward: aggWorkerForwardACToNode not logged")
}
fwErr = nil
// restore
aggWorkerForwardACToNode = saveFn
}