okit/observer/local.go

82 lines
2.3 KiB
Go
Raw Normal View History

2022-12-14 16:23:55 +00:00
// Copyright (C) 2022 The OKit Authors
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
// IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE
// OR OTHER DEALINGS IN THE SOFTWARE.
2022-12-20 06:41:28 +00:00
package observer
2022-11-06 17:59:39 +00:00
import (
"bufio"
2022-12-20 06:41:28 +00:00
"io"
"os"
2022-11-06 17:59:39 +00:00
2022-12-20 06:41:28 +00:00
"go.pitz.tech/okit/format"
2022-11-06 17:59:39 +00:00
"go.pitz.tech/okit/pb"
)
2022-12-20 06:41:28 +00:00
// LocalOption defines a mechanism that allows properties of the observer to be overridden or configured.
type LocalOption func(l *local)
2022-11-06 17:59:39 +00:00
2022-12-20 06:41:28 +00:00
// Output configures the output of the local observer to point to the provided writer.
func Output(writer io.Writer) LocalOption {
return func(l *local) {
l.output = bufio.NewWriter(writer)
}
2022-11-06 17:59:39 +00:00
}
2022-12-20 06:41:28 +00:00
// Format configures how the information is written to the target writer.
func Format(fmt string) LocalOption {
return func(l *local) {
switch fmt {
case "json":
l.format = format.JSON{}
default:
l.format = format.Text{}
}
}
2022-11-06 17:59:39 +00:00
}
2022-12-20 06:41:28 +00:00
// Local creates an Observer that writes logs to an output stream using a configured format.
func Local(opts ...LocalOption) Observer {
l := &local{
output: bufio.NewWriter(os.Stdout),
format: format.Text{},
}
2022-11-06 17:59:39 +00:00
2022-12-20 06:41:28 +00:00
for _, o := range opts {
o(l)
}
2022-11-06 17:59:39 +00:00
2022-12-20 06:41:28 +00:00
return l
}
type local struct {
output *bufio.Writer
format format.Marshaler
}
func (l *local) Observe(entries []*pb.Entry) {
// TODO: how to handle internal errors
2022-11-06 17:59:39 +00:00
2022-12-20 06:41:28 +00:00
for _, entry := range entries {
_ = l.format.Marshal(l.output, entry)
2022-11-06 17:59:39 +00:00
}
2022-12-20 06:41:28 +00:00
_ = l.output.Flush()
2022-11-06 17:59:39 +00:00
}