Пример #1
0
func TestBadValues(t *testing.T) {

	pErr := "parse @#$%: invalid URL escape \"%\""
	header := make(stdhttp.Header, 0)
	header.Set("Content-Type", "text/plain")

	_, err := New("@#$%", "POST", header)
	if err == nil {
		t.Fatalf("Expected '<nil>' Got '%s'", err)
	}

	if err.Error() != pErr {
		t.Fatalf("Expected '%s' Got '%s'", pErr, err)
	}

	hLog, err := New("http://127.0.0.1:4354", "POST", header)
	if err != nil {
		t.Fatalf("Expected '<nil>' Got '%s'", err)
	}

	hLog.SetFormatFunc(func(h HTTP) Formatter {
		return func(e *log.Entry) []byte {
			return []byte(e.Message)
		}
	})
	log.RegisterHandler(hLog, log.DebugLevel, log.TraceLevel, log.InfoLevel, log.NoticeLevel, log.WarnLevel, log.PanicLevel, log.AlertLevel, log.FatalLevel)

	log.Debug("debug")
}
Пример #2
0
func TestCustomFormatFunc(t *testing.T) {

	buff := new(bytes.Buffer)
	cLog := New()
	cLog.SetWriter(buff)
	cLog.SetTimestampFormat("2006")
	cLog.SetBuffersAndWorkers(3, 2)
	cLog.SetFormatFunc(func(c *Console) Formatter {

		var b []byte

		return func(e *log.Entry) []byte {
			b = b[0:0]
			b = append(b, e.Message...)
			return b
		}
	})

	log.RegisterHandler(cLog, log.AllLevels...)

	log.Debug("debug")
	if buff.String() != "debug" {
		log.Errorf("Expected '%s' Got '%s'", "debug", buff.String())
	}
	buff.Reset()
}
Пример #3
0
func TestBadWorkerCountAndCustomFormatFunc(t *testing.T) {

	addr, err := net.ResolveUDPAddr("udp", ":2004")
	if err != nil {
		log.Errorf("Expected '%v' Got '%v'", nil, err)
	}

	conn, err := net.ListenUDP("udp", addr)
	if err != nil {
		log.Errorf("Expected '%v' Got '%v'", nil, err)
	}
	defer conn.Close()

	sLog, err := New("udp", "127.0.0.1:2004", "", nil)
	if err != nil {
		log.Errorf("Expected '%v' Got '%v'", nil, err)
	}

	sLog.SetDisplayColor(true)
	sLog.SetBuffersAndWorkers(3, 0)
	sLog.SetTimestampFormat("2006")
	sLog.SetFormatFunc(func(s *Syslog) Formatter {
		return func(e *log.Entry) []byte {
			return []byte(e.Message)
		}
	})

	log.RegisterHandler(sLog, log.AllLevels...)

	log.Debug("debug")
	if s := hasString(conn); s != "debug" {
		log.Errorf("Expected '%s' Got '%s'", "debug", s)
	}
}
Пример #4
0
func TestBadTemplate(t *testing.T) {

	tests := []string{
		"\"color\":\"green\"",
		"\"notify\":true",
		"\"message\":\"\"",
	}

	var msg string

	server := httptest.NewServer(stdhttp.HandlerFunc(func(w stdhttp.ResponseWriter, r *stdhttp.Request) {
		b, err := ioutil.ReadAll(r.Body)
		if err != nil {
			msg = err.Error()
			return
		}

		msg = string(b)

		if strings.Contains(msg, "badrequest") {
			w.WriteHeader(stdhttp.StatusBadRequest)
			return
		}

		w.WriteHeader(stdhttp.StatusAccepted)
	}))
	defer server.Close()

	hc, err := New(APIv2, server.URL, "application/json", authToken)
	if err != nil {
		log.Fatalf("Error initializing hipchat received '%s'", err)
	}

	hc.SetBuffersAndWorkers(1, 1)
	hc.SetTimestampFormat("MST")
	hc.SetEmailTemplate("{{.NonExistantField}}")
	hc.SetFilenameDisplay(log.Llongfile)
	log.RegisterHandler(hc, log.DebugLevel)

	log.Debug("debug test")

	for i, tt := range tests {
		if !strings.Contains(msg, tt) {
			t.Errorf("Index '%d' Expected '%s' Got '%s'", i, tt, msg)
		}
	}
}
Пример #5
0
func main() {

	cLog := console.New()

	log.RegisterHandler(cLog, log.AllLevels...)

	// Trace
	defer log.Trace("trace").End()

	log.Debug("debug")
	log.Info("info")
	log.Notice("notice")
	log.Warn("warn")
	log.Error("error")
	// log.Panic("panic") // this will panic
	log.Alert("alert")
	// log.Fatal("fatal") // this will call os.Exit(1)

	// logging with fields can be used with any of the above
	log.WithFields(log.F("key", "value")).Info("test info")
}
Пример #6
0
func TestHTTPLogger(t *testing.T) {

	tests := getTestHTTPLoggerTests()
	var msg string

	server := httptest.NewServer(stdhttp.HandlerFunc(func(w stdhttp.ResponseWriter, r *stdhttp.Request) {
		b, err := ioutil.ReadAll(r.Body)
		if err != nil {
			msg = err.Error()
			return
		}

		msg = string(b)

		if msg == "UTC  DEBUG badrequest" {
			w.WriteHeader(stdhttp.StatusBadRequest)
			return
		}
	}))
	defer server.Close()

	header := make(stdhttp.Header, 0)
	header.Set("Content-Type", "text/plain")

	hLog, err := New(server.URL, "POST", header)
	if err != nil {
		log.Fatalf("Error initializing HTTP received '%s'", err)
	}
	hLog.SetBuffersAndWorkers(0, 0)
	hLog.SetTimestampFormat("MST")
	log.SetCallerInfoLevels(log.WarnLevel, log.ErrorLevel, log.PanicLevel, log.AlertLevel, log.FatalLevel)
	log.RegisterHandler(hLog, log.DebugLevel, log.TraceLevel, log.InfoLevel, log.NoticeLevel, log.WarnLevel, log.PanicLevel, log.AlertLevel, log.FatalLevel)

	for i, tt := range tests {

		var l log.LeveledLogger

		if tt.flds != nil {
			l = log.WithFields(tt.flds...)
		} else {
			l = log.Logger
		}

		switch tt.lvl {
		case log.DebugLevel:
			l.Debug(tt.msg)
		case log.TraceLevel:
			l.Trace(tt.msg).End()
		case log.InfoLevel:
			l.Info(tt.msg)
		case log.NoticeLevel:
			l.Notice(tt.msg)
		case log.WarnLevel:
			l.Warn(tt.msg)
		case log.ErrorLevel:
			l.Error(tt.msg)
		case log.PanicLevel:
			func() {
				defer func() {
					recover()
				}()

				l.Panic(tt.msg)
			}()
		case log.AlertLevel:
			l.Alert(tt.msg)
		}

		if msg != tt.want {

			if tt.lvl == log.TraceLevel {
				if !strings.HasPrefix(msg, tt.want) {
					t.Errorf("test %d: Expected '%s' Got '%s'", i, tt.want, msg)
				}
				continue
			}

			t.Errorf("test %d: Expected '%s' Got '%s'", i, tt.want, msg)
		}
	}

	log.Debug("badrequest")
}
Пример #7
0
func TestEmailHandler(t *testing.T) {

	tests := []struct {
		expected string
	}{
		{
			expected: "*****@*****.**",
		},
		{
			expected: "*****@*****.**",
		},
		{
			expected: "Subject: debug",
		},
		{
			expected: "DEBUG",
		},
	}

	email := New("localhost", 3041, "", "", "*****@*****.**", []string{"*****@*****.**"})
	email.SetBuffersAndWorkers(1, 0)
	email.SetTimestampFormat("MST")
	email.SetKeepAliveTimout(time.Second * 0)
	email.SetEmailTemplate(defaultTemplate)
	email.SetFilenameDisplay(log.Llongfile)
	// email.SetFormatFunc(testFormatFunc)
	log.RegisterHandler(email, log.InfoLevel, log.DebugLevel)

	var msg string

	server, err := net.Listen("tcp", ":3041")
	if err != nil {
		t.Errorf("Expected <nil> Got '%s'", err)
	}

	defer server.Close()

	proceed := make(chan struct{})
	defer close(proceed)

	go func() {
		for {
			conn, err := server.Accept()
			if err != nil {
				msg = ""
				break
			}

			if conn == nil {
				continue
			}

			c := &Client{
				conn:    conn,
				address: conn.RemoteAddr().String(),
				time:    time.Now().Unix(),
				bufin:   bufio.NewReader(conn),
				bufout:  bufio.NewWriter(conn),
			}

			msg = handleClient(c, false)

			proceed <- struct{}{}
		}
	}()

	log.Debug("debug")

	<-proceed

	for i, tt := range tests {
		if !strings.Contains(msg, tt.expected) {
			t.Errorf("Index %d Expected '%s' Got '%s'", i, tt.expected, msg)
		}
	}

	// this is normally not safe, but in these tests won't cause any issue
	// flipping during runtime.
	email.SetFilenameDisplay(log.Lshortfile)

	log.Debug("debug")

	<-proceed

	for i, tt := range tests {
		if !strings.Contains(msg, tt.expected) {
			t.Errorf("Index %d Expected '%s' Got '%s'", i, tt.expected, msg)
		}
	}
}
Пример #8
0
func TestSyslogTLS(t *testing.T) {

	// setup server

	addr, err := net.ResolveTCPAddr("tcp", ":2022")
	if err != nil {
		log.Errorf("Expected '%v' Got '%v'", nil, err)
	}

	cnn, err := net.ListenTCP("tcp", addr)
	if err != nil {
		log.Errorf("Expected '%v' Got '%v'", nil, err)
	}
	defer cnn.Close()

	tlsConfig := &tls.Config{
		Certificates: make([]tls.Certificate, 1),
	}

	tlsConfig.Certificates[0], err = tls.X509KeyPair([]byte(publicKey), []byte(privateKey))
	if err != nil {
		log.Errorf("Expected '%v' Got '%v'", nil, err)
	}

	conn := tls.NewListener(cnn, tlsConfig)

	var msg string
	var m sync.Mutex

	go func() {
		client, err := conn.Accept()
		if err != nil {
			log.Errorf("Expected '%v' Got '%v'", nil, err)
		}

		b := make([]byte, 1024)

		read, err := client.Read(b)
		if err != nil {
			log.Errorf("Expected '%v' Got '%v'", nil, err)
		}

		m.Lock()
		defer m.Unlock()
		msg = string(b[0:read])
	}()

	// setup client log

	pool := x509.NewCertPool()
	pool.AppendCertsFromPEM([]byte(publicKey))

	config := &tls.Config{
		RootCAs: pool,
	}

	sLog, err := New("tcp+tls", "127.0.0.1:2022", "", config)
	if err != nil {
		log.Fatalf("Expected '%v' Got '%v'", nil, err)
	}

	//sLog.SetDisplayColor(true)
	// sLog.SetBuffersAndWorkers(3, 0)
	// sLog.SetTimestampFormat("2006")
	sLog.SetFormatFunc(func(s *Syslog) Formatter {
		return func(e *log.Entry) []byte {
			return []byte(e.Message)
		}
	})

	log.RegisterHandler(sLog, log.AllLevels...)

	log.Debug("debug")
	time.Sleep(500 * time.Millisecond)

	m.Lock()
	defer m.Unlock()

	if msg != "debug" {
		log.Errorf("Expected '%s' Got '%s'", "debug", msg)
	}
}