| 1 |
// +build linux |
| 2 |
|
| 3 |
package journald_test |
| 4 |
|
| 5 |
import ( |
| 6 |
"bytes" |
| 7 |
"io" |
| 8 |
"testing" |
| 9 |
|
| 10 |
"github.com/rs/zerolog" |
| 11 |
"github.com/rs/zerolog/journald" |
| 12 |
) |
| 13 |
|
| 14 |
func ExampleNewJournalDWriter() { |
| 15 |
log := zerolog.New(journald.NewJournalDWriter()) |
| 16 |
log.Info().Str("foo", "bar").Uint64("small", 123).Float64("float", 3.14).Uint64("big", 1152921504606846976).Msg("Journal Test") |
| 17 |
// Output: |
| 18 |
} |
| 19 |
|
| 20 |
/* |
| 21 |
|
| 22 |
There is no automated way to verify the output - since the output is sent |
| 23 |
to journald process and method to retrieve is journalctl. Will find a way |
| 24 |
to automate the process and fix this test. |
| 25 |
|
| 26 |
$ journalctl -o verbose -f |
| 27 |
|
| 28 |
Thu 2018-04-26 22:30:20.768136 PDT [s=3284d695bde946e4b5017c77a399237f;i=329f0;b=98c0dca0debc4b98a5b9534e910e7dd6;m=7a702e35dd4;t=56acdccd2ed0a;x=4690034cf0348614] |
| 29 |
PRIORITY=6 |
| 30 |
_AUDIT_LOGINUID=1000 |
| 31 |
_BOOT_ID=98c0dca0debc4b98a5b9534e910e7dd6 |
| 32 |
_MACHINE_ID=926ed67eb4744580948de70fb474975e |
| 33 |
_HOSTNAME=sprint |
| 34 |
_UID=1000 |
| 35 |
_GID=1000 |
| 36 |
_CAP_EFFECTIVE=0 |
| 37 |
_SYSTEMD_SLICE=-.slice |
| 38 |
_TRANSPORT=journal |
| 39 |
_SYSTEMD_CGROUP=/ |
| 40 |
_AUDIT_SESSION=2945 |
| 41 |
MESSAGE=Journal Test |
| 42 |
FOO=bar |
| 43 |
BIG=1152921504606846976 |
| 44 |
_COMM=journald.test |
| 45 |
SMALL=123 |
| 46 |
FLOAT=3.14 |
| 47 |
JSON={"level":"info","foo":"bar","small":123,"float":3.14,"big":1152921504606846976,"message":"Journal Test"} |
| 48 |
_PID=27103 |
| 49 |
_SOURCE_REALTIME_TIMESTAMP=1524807020768136 |
| 50 |
*/ |
| 51 |
|
| 52 |
func TestWriteReturnsNoOfWrittenBytes(t *testing.T) { |
| 53 |
input := []byte(`{"level":"info","time":1570912626,"message":"Starting..."}`) |
| 54 |
wr := journald.NewJournalDWriter() |
| 55 |
want := len(input) |
| 56 |
got, err := wr.Write(input) |
| 57 |
|
| 58 |
if err != nil { |
| 59 |
t.Errorf("Unexpected error %v", err) |
| 60 |
} |
| 61 |
|
| 62 |
if want != got { |
| 63 |
t.Errorf("Expected %d bytes to be written got %d", want, got) |
| 64 |
} |
| 65 |
} |
| 66 |
|
| 67 |
func TestMultiWrite(t *testing.T) { |
| 68 |
var ( |
| 69 |
w1 = new(bytes.Buffer) |
| 70 |
w2 = new(bytes.Buffer) |
| 71 |
w3 = journald.NewJournalDWriter() |
| 72 |
) |
| 73 |
|
| 74 |
zerolog.ErrorHandler = func(err error) { |
| 75 |
if err == io.ErrShortWrite { |
| 76 |
t.Errorf("Unexpected ShortWriteError") |
| 77 |
t.FailNow() |
| 78 |
} |
| 79 |
} |
| 80 |
|
| 81 |
log := zerolog.New(io.MultiWriter(w1, w2, w3)).With().Logger() |
| 82 |
|
| 83 |
for i := 0; i < 10; i++ { |
| 84 |
log.Info().Msg("Tick!") |
| 85 |
} |
| 86 |
} |