-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathperflog.go
More file actions
81 lines (66 loc) · 1.43 KB
/
Copy pathperflog.go
File metadata and controls
81 lines (66 loc) · 1.43 KB
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
package main
import (
"bytes"
"errors"
"fmt"
"io"
"os"
"time"
)
type LogItem struct {
HostToResolve string
RequestedBy string
Action string
Duration float64
}
type LogClient interface {
Connect() error
Close() error
WriteItem(item *LogItem) error
}
type LogFileClient struct {
filename string
file *os.File
Sink io.Writer
}
//
// ErrFileNotOpen raised when the log file is not opened
//
var ErrFileNotOpen = errors.New("File not open, did you check return from New??")
func NewLogFileClient(FileName string) (*LogFileClient, error) {
client := LogFileClient{
filename: FileName,
}
if FileName == "-" {
client.file = os.Stdout
client.Sink = os.Stdout
} else {
f, err := os.OpenFile(FileName, os.O_APPEND|os.O_WRONLY|os.O_CREATE, 0644)
if err != nil {
return nil, err
}
client.file = f
client.Sink = f
}
return &client, nil
}
// Not implemented/needed
func (c *LogFileClient) Connect() error {
return nil
}
func (c *LogFileClient) Close() error {
if c.file == nil {
return ErrFileNotOpen
}
return c.file.Close()
}
func (c *LogFileClient) WriteItem(item *LogItem) error {
if c.file == nil {
return ErrFileNotOpen
}
ts := time.Now().UTC().Format("2006-01-02T15:04:05Z07:00")
strItem := fmt.Sprintf("%s,%s,%s,%s,%f\n", ts, item.HostToResolve, item.RequestedBy, item.Action, item.Duration)
buf := bytes.NewBufferString(strItem)
_, err := c.Sink.Write(buf.Bytes())
return err
}