-
Notifications
You must be signed in to change notification settings - Fork 0
/
output.go
89 lines (79 loc) · 2.54 KB
/
output.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
package jasper
import (
"context"
"errors"
"fmt"
"io"
"github.com/tychoish/grip/send"
"github.com/tychoish/jasper/options"
)
// NewInMemoryLogger is a basic constructor that constructs a logger
// configuration for plain formatted in-memory buffered logger. The
// logger will capture up to maxSize messages.
func NewInMemoryLogger(maxSize int) (*options.LoggerConfig, error) {
loggerProducer := &options.InMemoryLoggerOptions{
InMemoryCap: maxSize,
Base: options.BaseOptions{
Format: options.LogFormatPlain,
},
}
config := &options.LoggerConfig{}
if err := config.Set(loggerProducer); err != nil {
return nil, fmt.Errorf("problem setting logger producer for logger config: %w", err)
}
return config, nil
}
// LogStream represents the output of reading the in-memory log buffer as a
// stream, containing the logs (if any) and whether or not the stream is done
// reading.
type LogStream struct {
Logs []string `bson:"logs,omitempty" json:"logs,omitempty"`
Done bool `bson:"done" json:"done"`
}
// GetInMemoryLogStream gets at most count logs from the in-memory output logs
// for the given Process proc. If the process has not been called with
// Process.Wait(), this is not guaranteed to produce all the logs. This function
// assumes that there is exactly one in-memory logger attached to this process's
// output. It returns io.EOF if the stream is done. For remote interfaces, this
// function will not work; use (RemoteClient).GetLogStream() instead.
func GetInMemoryLogStream(ctx context.Context, proc Process, count int) ([]string, error) {
if proc == nil {
return nil, errors.New("cannot get output logs from nil process")
}
for _, logger := range proc.Info(ctx).Options.Output.Loggers {
if logger.Type() != options.LogInMemory {
continue
}
// This is fine because logger.sender is already set.
sender, err := logger.Resolve()
if err != nil {
continue
}
safeSender, ok := sender.(*options.SafeSender)
if ok {
sender = safeSender.GetSender()
}
inMemorySender, ok := sender.(*send.InMemorySender)
if !ok {
continue
}
msgs, _, err := inMemorySender.GetCount(count)
if err != nil {
if err != io.EOF {
err = fmt.Errorf("failed to get logs from in-memory stream: %w", err)
}
return nil, err
}
strs := make([]string, 0, len(msgs))
formatter := inMemorySender.GetFormatter()
for _, msg := range msgs {
str, err := formatter(msg)
if err != nil {
return nil, err
}
strs = append(strs, str)
}
return strs, nil
}
return nil, errors.New("could not find in-memory output logs")
}