Skip to content

Instantly share code, notes, and snippets.

@RichardHightower
Last active November 28, 2016 22:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save RichardHightower/e92d5803c33755ee0fd4aaa287d8c3d1 to your computer and use it in GitHub Desktop.
Save RichardHightower/e92d5803c33755ee0fd4aaa287d8c3d1 to your computer and use it in GitHub Desktop.
reading system logs from go
package main 

import (
	"os"
	"fmt"
	"github.com/coreos/go-systemd/sdjournal"
)

func main() {
	err := run()
	if err != nil {
		os.Stderr.WriteString(err.Error())
		os.Stderr.Write([]byte{'\n'})
		os.Exit(2)
	}
}

func run() error {

	journal, err  := sdjournal.NewJournal()
	defer journal.Close()

	if err != nil {
		return fmt.Errorf("error opening journal: %s", err)
	}

	lastNRecords := uint64(1000)

	err = journal.SeekTail()

	if err != nil { return err }

	if _,err = journal.PreviousSkip(lastNRecords) ; err!= nil {
		return err
	}


	for i := 0; i < int(lastNRecords); i++ {
		
		seeked, err := journal.Next()
	        if seeked == 0 || err != nil {
        	        return fmt.Errorf("unable to seek to first item in journal %s", err)
	        }

		bootId, err := journal.GetDataValue("_BOOT_ID")
	        if err != nil { return err }
        	message, err := journal.GetDataValue("MESSAGE")
	        if err != nil { return err }

	        fmt.Printf("BOOT ID %s MESSAGE %s\n", bootId, message)
	}

	return nil

}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment