// 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. package observer import ( "bufio" "io" "os" "go.pitz.tech/okit/format" "go.pitz.tech/okit/pb" ) // LocalOption defines a mechanism that allows properties of the observer to be overridden or configured. type LocalOption func(l *local) // 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) } } // 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{} } } } // 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{}, } for _, o := range opts { o(l) } return l } type local struct { output *bufio.Writer format format.Marshaler } func (l *local) Observe(entries []*pb.Entry) { // TODO: how to handle internal errors for _, entry := range entries { _ = l.format.Marshal(l.output, entry) } _ = l.output.Flush() }