Example #1
0
func (s *journald) Log(msg *logger.Message) error {
	vars := map[string]string{}
	for k, v := range s.vars {
		vars[k] = v
	}
	if msg.Partial {
		vars["CONTAINER_PARTIAL_MESSAGE"] = "true"
	}
	if msg.Source == "stderr" {
		return journal.Send(string(msg.Line), journal.PriErr, vars)
	}
	return journal.Send(string(msg.Line), journal.PriInfo, vars)
}
Example #2
0
func (j *jlogger) Fatal(exit bool, v ...interface{}) error {
	err := journal.Send(fmt.Sprint(v...), journal.PriErr, nil)
	if exit {
		os.Exit(1)
	}
	return err
}
Example #3
0
func TestJournalGetUniqueValues(t *testing.T) {
	j, err := NewJournal()
	if err != nil {
		t.Fatal(err)
	}

	defer j.Close()

	uniqueString := generateRandomField(20)
	testEntries := []string{"A", "B", "C", "D"}
	for _, v := range testEntries {
		err := journal.Send("TEST: "+uniqueString, journal.PriInfo, map[string]string{uniqueString: v})
		if err != nil {
			t.Fatal(err)
		}
	}

	// TODO: add proper `waitOnMatch` function which should wait for journal entry with filter to commit.
	time.Sleep(time.Millisecond * 500)

	values, err := j.GetUniqueValues(uniqueString)
	if err != nil {
		t.Fatal(err)
	}

	if len(values) != len(testEntries) {
		t.Fatalf("Expect %d entries. Got %d", len(testEntries), len(values))
	}

	if !contains(values, "A") || !contains(values, "B") || !contains(values, "C") || !contains(values, "D") {
		t.Fatalf("Expect 4 values for %s field: A,B,C,D. Got %s", uniqueString, values)
	}
}
func (j *journaldFormatter) Format(pkg string, l LogLevel, _ int, entries ...interface{}) {
	var pri journal.Priority
	switch l {
	case CRITICAL:
		pri = journal.PriCrit
	case ERROR:
		pri = journal.PriErr
	case WARNING:
		pri = journal.PriWarning
	case NOTICE:
		pri = journal.PriNotice
	case INFO:
		pri = journal.PriInfo
	case DEBUG:
		pri = journal.PriDebug
	case TRACE:
		pri = journal.PriDebug
	default:
		panic("Unhandled loglevel")
	}
	msg := fmt.Sprint(entries...)
	tags := map[string]string{
		"PACKAGE": pkg,
	}
	err := journal.Send(msg, pri, tags)
	if err != nil {
		fmt.Fprintln(os.Stderr, err)
	}
}
Example #5
0
func (j *jlogger) Write(b []byte) (int, error) {
	err := journal.Send(string(b), journal.PriInfo, nil)
	if err != nil {
		return 0, err
	}
	return len(b), nil
}
Example #6
0
func (j *jlogger) Fatalf(exit bool, format string, v ...interface{}) error {
	err := journal.Send(fmt.Sprintf(format, v...), journal.PriErr, nil)
	if exit {
		os.Exit(1)
	}
	return err
}
Example #7
0
func (s *systemdJournal) Send(p level.Priority, m message.Composer) {
	if !GetMessageInfo(s.level, p, m).ShouldLog() {
		return
	}

	msg := m.Resolve()
	err := journal.Send(msg, s.convertPrioritySystemd(p), s.options)
	if err != nil {
		s.fallback.Println("systemd journaling error:", err.Error())
		s.fallback.Printf("[p=%s]: %s\n", p, msg)
	}
}
Example #8
0
func (sink *journalSink) Log(fields Fields) {
	message := fields["message"].(string)
	priority := toJournalPriority(fields["priority"].(Priority))
	journalFields := make(map[string]string)
	for k, v := range fields {
		if k == "message" || k == "priority" {
			continue
		}
		journalFields[strings.ToUpper(k)] = fmt.Sprint(v)
	}
	journal.Send(message, priority, journalFields)
}
Example #9
0
func TestJournalGetEntry(t *testing.T) {
	j, err := NewJournal()
	if err != nil {
		t.Fatalf("Error opening journal: %s", err)
	}

	if j == nil {
		t.Fatal("Got a nil journal")
	}

	defer j.Close()

	j.FlushMatches()

	matchField := "TESTJOURNALGETENTRY"
	matchValue := fmt.Sprintf("%d", time.Now().UnixNano())
	m := Match{Field: matchField, Value: matchValue}
	err = j.AddMatch(m.String())
	if err != nil {
		t.Fatalf("Error adding matches to journal: %s", err)
	}

	want := fmt.Sprintf("test journal get entry message %s", time.Now())
	err = journal.Send(want, journal.PriInfo, map[string]string{matchField: matchValue})
	if err != nil {
		t.Fatalf("Error writing to journal: %s", err)
	}

	r := j.Wait(time.Duration(1) * time.Second)
	if r < 0 {
		t.Fatalf("Error waiting to journal")
	}

	n, err := j.Next()
	if err != nil {
		t.Fatalf("Error reading to journal: %s", err)
	}

	if n == 0 {
		t.Fatalf("Error reading to journal: %s", io.EOF)
	}

	entry, err := j.GetEntry()
	if err != nil {
		t.Fatalf("Error getting the entry to journal: %s", err)
	}

	got := entry.Fields["MESSAGE"]
	if got != want {
		t.Fatalf("Bad result for entry.Fields[\"MESSAGE\"]: got %s, want %s", got, want)
	}
}
Example #10
0
// Check for incorrect read into small buffers,
// see https://github.com/coreos/go-systemd/issues/172
func TestJournalReaderSmallReadBuffer(t *testing.T) {
	// Write a long entry ...
	delim := "%%%%%%"
	longEntry := strings.Repeat("a", 256)
	matchField := "TESTJOURNALREADERSMALLBUF"
	matchValue := fmt.Sprintf("%d", time.Now().UnixNano())
	r, err := NewJournalReader(JournalReaderConfig{
		Since: time.Duration(-15) * time.Second,
		Matches: []Match{
			{
				Field: matchField,
				Value: matchValue,
			},
		},
	})
	if err != nil {
		t.Fatalf("Error opening journal: %s", err)
	}
	if r == nil {
		t.Fatal("Got a nil reader")
	}
	defer r.Close()

	want := fmt.Sprintf("%slongentry %s%s", delim, longEntry, delim)
	err = journal.Send(want, journal.PriInfo, map[string]string{matchField: matchValue})
	if err != nil {
		t.Fatal("Error writing to journal", err)
	}
	time.Sleep(time.Second)

	// ... and try to read it back piece by piece via a small buffer
	finalBuff := new(bytes.Buffer)
	var e error
	for c := -1; c != 0 && e == nil; {
		smallBuf := make([]byte, 5)
		c, e = r.Read(smallBuf)
		if c > len(smallBuf) {
			t.Fatalf("Got unexpected read length: %d vs %d", c, len(smallBuf))
		}
		_, _ = finalBuff.Write(smallBuf)
	}
	b := finalBuff.String()
	got := strings.Split(b, delim)
	if len(got) != 3 {
		t.Fatalf("Got unexpected entry %s", b)
	}
	if got[1] != strings.Trim(want, delim) {
		t.Fatalf("Got unexpected message %s", got[1])
	}
}
Example #11
0
func setupJournalRoundtrip() (*Journal, map[string]string, error) {
	j, err := NewJournal()
	if err != nil {
		return nil, nil, fmt.Errorf("Error opening journal: %s", err)
	}

	if j == nil {
		return nil, nil, fmt.Errorf("Got a nil journal")
	}

	j.FlushMatches()

	matchField := "TESTJOURNALENTRY"
	matchValue := fmt.Sprintf("%d", time.Now().UnixNano())
	m := Match{Field: matchField, Value: matchValue}
	err = j.AddMatch(m.String())
	if err != nil {
		return nil, nil, fmt.Errorf("Error adding matches to journal: %s", err)
	}

	msg := fmt.Sprintf("test journal get entry message %s", time.Now())
	data := map[string]string{matchField: matchValue}
	err = journal.Send(msg, journal.PriInfo, data)
	if err != nil {
		return nil, nil, fmt.Errorf("Error writing to journal: %s", err)
	}

	time.Sleep(time.Duration(1) * time.Second)

	n, err := j.Next()
	if err != nil {
		return nil, nil, fmt.Errorf("Error reading from journal: %s", err)
	}

	if n == 0 {
		return nil, nil, fmt.Errorf("Error reading from journal: %s", io.EOF)
	}

	data["MESSAGE"] = msg

	return j, data, nil
}
Example #12
0
// CheckApply method for Msg resource.
// Every check leads to an apply, meaning that the message is flushed to the journal.
func (obj *MsgRes) CheckApply(apply bool) (bool, error) {

	// isStateOK() done by engine, so we updateStateOK() to pass in value
	//if obj.isAllStateOK() {
	//	return true, nil
	//}

	if obj.Refresh() { // if we were notified...
		// invalidate cached state...
		obj.logStateOK = false
		if obj.Journal {
			obj.journalStateOK = false
		}
		if obj.Syslog {
			obj.syslogStateOK = false
		}
		obj.updateStateOK()
	}

	if !obj.logStateOK {
		log.Printf("%s[%s]: Body: %s", obj.Kind(), obj.GetName(), obj.Body)
		obj.logStateOK = true
		obj.updateStateOK()
	}

	if !apply {
		return false, nil
	}
	if obj.Journal && !obj.journalStateOK {
		if err := journal.Send(obj.Body, obj.journalPriority(), obj.Fields); err != nil {
			return false, err
		}
		obj.journalStateOK = true
		obj.updateStateOK()
	}
	if obj.Syslog && !obj.syslogStateOK {
		// TODO: implement syslog client
		obj.syslogStateOK = true
		obj.updateStateOK()
	}
	return false, nil
}
Example #13
0
func log(level LogLevel, printerID, jobID, format string, args ...interface{}) {
	if level > logger.level {
		return
	}

	levelInitial := levelToInitial[level]
	dateTime := time.Now().Format(dateTimeFormat)
	var message string
	if format == "" {
		message = fmt.Sprint(args...)
	} else {
		message = fmt.Sprintf(format, args...)
	}

	journalVars := make(map[string]string)
	var journalMessage string
	if printerID != "" {
		fmt.Fprintf(logger.writer, logPrinterFormat, levelInitial, dateTime, printerID, message)
		journalVars["PRINTER_ID"] = printerID
		journalMessage = fmt.Sprintf(journalPrinterFormat, printerID, message)
	} else if jobID != "" {
		fmt.Fprintf(logger.writer, logJobFormat, levelInitial, dateTime, jobID, message)
		journalVars["JOB_ID"] = jobID
		journalMessage = fmt.Sprintf(journalJobFormat, jobID, message)
	} else {
		fmt.Fprintf(logger.writer, logFormat, levelInitial, dateTime, message)
		journalMessage = message
	}

	if logger.journalEnabled {
		pc := make([]uintptr, 1)
		runtime.Callers(3, pc)
		f := runtime.FuncForPC(pc[0])
		journalVars["CODE_FUNC"] = f.Name()
		file, line := f.FileLine(pc[0])
		journalVars["CODE_FILE"] = file
		journalVars["CODE_LINE"] = strconv.Itoa(line)
		journal.Send(journalMessage, level.priority(), journalVars)
	}
}
Example #14
0
func (s *journald) Log(msg *logger.Message) error {
	if msg.Source == "stderr" {
		return journal.Send(string(msg.Line), journal.PriErr, s.vars)
	}
	return journal.Send(string(msg.Line), journal.PriInfo, s.vars)
}
Example #15
0
func (j *jlogger) Warnf(format string, v ...interface{}) error {
	return journal.Send(fmt.Sprintf(format, v...), journal.PriWarning, nil)
}
Example #16
0
func (j *jlogger) Warn(v ...interface{}) error {
	return journal.Send(fmt.Sprint(v...), journal.PriWarning, nil)
}
Example #17
0
func (j *jlogger) Info(v ...interface{}) error {
	return journal.Send(fmt.Sprint(v...), journal.PriInfo, nil)
}