Skip to content

Commit 4cd5aed

Browse files
authored
Merge pull request #102 from pyroscope-io/gospy-logging-fix
Improves logging in gospy agent
2 parents 2da1333 + f8e033e commit 4cd5aed

File tree

11 files changed

+71
-53
lines changed

11 files changed

+71
-53
lines changed

.github/workflows/tests.yml

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,8 @@ jobs:
1919
key: ${{ runner.os }}-go-${{ hashFiles('**/go.sum') }}
2020
restore-keys: |
2121
${{ runner.os }}-go-
22+
- name: Ensure logrus is not used by pkg/agent/profiler
23+
run: make ensure-logrus-not-used
2224
- name: Run Go tests
2325
run: go test ./...
2426
- name: Install Webapp dependencies

Makefile

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -72,6 +72,11 @@ embedded-assets: install-dev-tools $(shell echo $(EMBEDDED_ASSETS_DEPS))
7272
lint:
7373
revive -config revive.toml -formatter stylish ./...
7474

75+
.PHONY: ensure-logrus-not-used
76+
ensure-logrus-not-used:
77+
@! godepgraph -nostdlib -s ./pkg/agent/profiler/ | grep ' -> "github.com/sirupsen/logrus' \
78+
|| (echo "\n^ ERROR: make sure ./pkg/agent/profiler/ does not depend on logrus. We don't want users' logs to be tainted. Talk to @petethepig if have questions\n" &1>2; exit 1)
79+
7580
.PHONY: unused
7681
unused:
7782
staticcheck -f stylish -unused.whole-program ./...
Lines changed: 12 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -1,21 +1,21 @@
1-
package agent
1+
package cli
22

33
import (
44
"os"
55

6-
"github.com/sirupsen/logrus"
7-
6+
"github.com/pyroscope-io/pyroscope/pkg/agent"
87
"github.com/pyroscope-io/pyroscope/pkg/agent/csock"
98
"github.com/pyroscope-io/pyroscope/pkg/agent/upstream"
109
"github.com/pyroscope-io/pyroscope/pkg/agent/upstream/remote"
1110
"github.com/pyroscope-io/pyroscope/pkg/config"
1211
"github.com/pyroscope-io/pyroscope/pkg/util/id"
12+
"github.com/sirupsen/logrus"
1313
)
1414

1515
type Agent struct {
1616
cfg *config.Config
1717
cs *csock.CSock
18-
activeProfiles map[int]*ProfileSession
18+
activeProfiles map[int]*agent.ProfileSession
1919
id id.ID
2020
u upstream.Upstream
2121
}
@@ -27,25 +27,26 @@ func New(cfg *config.Config) *Agent {
2727
UpstreamAddress: cfg.Agent.ServerAddress,
2828
UpstreamRequestTimeout: cfg.Agent.UpstreamRequestTimeout,
2929
})
30+
r.Logger = logrus.StandardLogger()
3031
return &Agent{
3132
cfg: cfg,
32-
activeProfiles: make(map[int]*ProfileSession),
33+
activeProfiles: make(map[int]*agent.ProfileSession),
3334
u: r,
3435
}
3536
}
3637

37-
func (a *Agent) Start() {
38+
func (a *Agent) Start() error {
3839
sockPath := a.cfg.Agent.UNIXSocketPath
3940
cs, err := csock.NewUnixCSock(sockPath, a.controlSocketHandler)
4041
if err != nil {
41-
logrus.Fatal(err)
42+
return err
4243
}
4344
a.cs = cs
4445
defer os.Remove(sockPath)
4546

46-
go SelfProfile(a.cfg, a.u, "pyroscope.agent.cpu{}")
47-
logrus.WithField("addr", cs.CanonicalAddr()).Info("Starting control socket")
47+
go agent.SelfProfile(a.cfg, a.u, "pyroscope.agent.cpu{}", logrus.StandardLogger())
4848
cs.Start()
49+
return nil
4950
}
5051

5152
func (a *Agent) Stop() {
@@ -59,7 +60,8 @@ func (a *Agent) controlSocketHandler(req *csock.Request) *csock.Response {
5960
// TODO: pass withSubprocesses from somewhere
6061
// TODO: pass appName from somewhere
6162
// TODO: add sample rate
62-
s := NewSession(a.u, "testapp.cpu", "gospy", 100, 0, false)
63+
s := agent.NewSession(a.u, "testapp.cpu", "gospy", 100, 0, false)
64+
s.Logger = logrus.StandardLogger()
6365
a.activeProfiles[profileID] = s
6466
s.Start()
6567
return &csock.Response{ProfileID: profileID}

pkg/agent/logger.go

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
package agent
2+
3+
// Logger is an interface that library users can use
4+
// It is based on logrus, but much smaller — That's because we don't want library users to have to implement
5+
// all of the logrus's methods
6+
type Logger interface {
7+
Infof(format string, args ...interface{})
8+
Debugf(format string, args ...interface{})
9+
Errorf(format string, args ...interface{})
10+
}

pkg/agent/profiler/profiler.go

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@ type Config struct {
1313
ApplicationName string // e.g backend.purchases
1414
ServerAddress string // e.g http://pyroscope.services.internal:4040
1515
AuthToken string
16+
Logger agent.Logger
1617
}
1718

1819
type Profiler struct {
@@ -27,11 +28,16 @@ func Start(cfg Config) (*Profiler, error) {
2728
UpstreamThreads: 4,
2829
UpstreamRequestTimeout: 30 * time.Second,
2930
})
31+
32+
u.Logger = cfg.Logger
33+
3034
if err != nil {
3135
return nil, err
3236
}
37+
3338
// TODO: add sample rate
3439
sess := agent.NewSession(u, cfg.ApplicationName, "gospy", 100, 0, false)
40+
sess.Logger = cfg.Logger
3541
sess.Start()
3642

3743
p := &Profiler{

pkg/agent/selfprofile.go

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -4,18 +4,19 @@ import (
44
"github.com/pyroscope-io/pyroscope/pkg/agent/upstream"
55
"github.com/pyroscope-io/pyroscope/pkg/config"
66
"github.com/pyroscope-io/pyroscope/pkg/util/atexit"
7-
"github.com/sirupsen/logrus"
87
)
98

10-
func SelfProfile(_ *config.Config, u upstream.Upstream, appName string) {
9+
func SelfProfile(_ *config.Config, u upstream.Upstream, appName string, logger Logger) error {
1110
// TODO: add sample rate
1211
s := NewSession(u, appName, "gospy", 100, 0, false)
1312
err := s.Start()
1413

14+
s.Logger = logger
15+
1516
if err != nil {
16-
logrus.Errorf("failed to start profiling session: %s", err)
17-
return
17+
return err
1818
}
1919

2020
atexit.Register(s.Stop)
21+
return nil
2122
}

pkg/agent/session.go

Lines changed: 8 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,6 @@ import (
1313
_ "github.com/pyroscope-io/pyroscope/pkg/agent/pyspy"
1414
_ "github.com/pyroscope-io/pyroscope/pkg/agent/rbspy"
1515
"github.com/pyroscope-io/pyroscope/pkg/agent/upstream"
16-
"github.com/sirupsen/logrus"
1716

1817
// revive:enable:blank-imports
1918

@@ -36,6 +35,8 @@ type ProfileSession struct {
3635

3736
startTime time.Time
3837
stopTime time.Time
38+
39+
Logger Logger
3940
}
4041

4142
func NewSession(upstream upstream.Upstream, appName string, spyName string, sampleRate int, pid int, withSubprocesses bool) *ProfileSession {
@@ -155,15 +156,13 @@ func (ps *ProfileSession) addSubprocesses() {
155156
ps.pids = append(ps.pids, newPid)
156157
newSpy, err := spy.SpyFromName(ps.spyName, newPid)
157158
if err != nil {
158-
logrus.WithFields(logrus.Fields{
159-
"spy-name": ps.spyName,
160-
"pid": newPid,
161-
}).Error("failed to initialize a spy")
159+
if ps.Logger != nil {
160+
ps.Logger.Errorf("failed to initialize a spy %d [%s]", newPid, ps.spyName)
161+
}
162162
} else {
163-
logrus.WithFields(logrus.Fields{
164-
"spy-name": ps.spyName,
165-
"pid": newPid,
166-
}).Debug("started spy for subprocess")
163+
if ps.Logger != nil {
164+
ps.Logger.Debugf("started spy for subprocess %d [%s]", newPid, ps.spyName)
165+
}
167166
ps.spies = append(ps.spies, newSpy)
168167
}
169168
}

pkg/agent/upstream/remote/remote.go

Lines changed: 18 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -12,8 +12,7 @@ import (
1212
"sync"
1313
"time"
1414

15-
"github.com/sirupsen/logrus"
16-
15+
"github.com/pyroscope-io/pyroscope/pkg/agent"
1716
"github.com/pyroscope-io/pyroscope/pkg/structs/transporttrie"
1817
)
1918

@@ -34,6 +33,8 @@ type Remote struct {
3433
todo chan *uploadJob
3534
done chan *sync.WaitGroup
3635
client *http.Client
36+
37+
Logger agent.Logger
3738
}
3839

3940
type RemoteConfig struct {
@@ -97,7 +98,9 @@ func (u *Remote) Upload(name string, startTime time.Time, endTime time.Time, spy
9798
select {
9899
case u.todo <- job:
99100
default:
100-
logrus.Error("Remote upload queue is full, dropping a profile")
101+
if u.Logger != nil {
102+
u.Logger.Errorf("Remote upload queue is full, dropping a profile")
103+
}
101104
}
102105
}
103106

@@ -115,11 +118,15 @@ func (u *Remote) uploadProfile(j *uploadJob) {
115118
urlObj.Path = path.Join(urlObj.Path, "/ingest")
116119
urlObj.RawQuery = q.Encode()
117120
buf := j.t.Bytes()
118-
logrus.Info("uploading at ", urlObj.String())
121+
if u.Logger != nil {
122+
u.Logger.Infof("uploading at %s", urlObj.String())
123+
}
119124

120125
req, err := http.NewRequest("POST", urlObj.String(), bytes.NewReader(buf))
121126
if err != nil {
122-
logrus.Error("Error happened when uploading a profile:", err)
127+
if u.Logger != nil {
128+
u.Logger.Errorf("Error happened when uploading a profile: %v", err)
129+
}
123130
return
124131
}
125132
req.Header.Set("Content-Type", "binary/octet-stream+trie")
@@ -129,15 +136,19 @@ func (u *Remote) uploadProfile(j *uploadJob) {
129136
resp, err := u.client.Do(req)
130137

131138
if err != nil {
132-
logrus.Error("Error happened when uploading a profile:", err)
139+
if u.Logger != nil {
140+
u.Logger.Errorf("Error happened when uploading a profile: %v", err)
141+
}
133142
return
134143
}
135144

136145
if resp != nil {
137146
defer resp.Body.Close()
138147
_, err := ioutil.ReadAll(resp.Body)
139148
if err != nil {
140-
logrus.Error("Error happened while reading server response:", err)
149+
if u.Logger != nil {
150+
u.Logger.Errorf("Error happened while reading server response: %v", err)
151+
}
141152
}
142153
}
143154
}

pkg/cli/cli.go

Lines changed: 1 addition & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -177,7 +177,6 @@ func resolvePath(path string) string {
177177

178178
func Start(cfg *config.Config) error {
179179
var (
180-
agentFlagSet = flag.NewFlagSet("pyroscope agent", flag.ExitOnError)
181180
serverFlagSet = flag.NewFlagSet("pyroscope server", flag.ExitOnError)
182181
convertFlagSet = flag.NewFlagSet("pyroscope convert", flag.ExitOnError)
183182
execFlagSet = flag.NewFlagSet("pyroscope exec", flag.ExitOnError)
@@ -187,7 +186,6 @@ func Start(cfg *config.Config) error {
187186
rootFlagSet = flag.NewFlagSet("pyroscope", flag.ExitOnError)
188187
)
189188

190-
agentSortedFlags := PopulateFlagSet(&cfg.Agent, agentFlagSet)
191189
serverSortedFlags := PopulateFlagSet(&cfg.Server, serverFlagSet)
192190
convertSortedFlags := PopulateFlagSet(&cfg.Convert, convertFlagSet)
193191
execSortedFlags := PopulateFlagSet(&cfg.Exec, execFlagSet, "pid")
@@ -203,15 +201,6 @@ func Start(cfg *config.Config) error {
203201
ff.WithConfigFileFlag("config"),
204202
}
205203

206-
agentCmd := &ffcli.Command{
207-
UsageFunc: agentSortedFlags.printUsage,
208-
Options: options,
209-
Name: "agent",
210-
ShortUsage: "pyroscope agent [flags]",
211-
ShortHelp: "starts pyroscope agent. Run this one on the machines you want to profile",
212-
FlagSet: agentFlagSet,
213-
}
214-
215204
serverCmd := &ffcli.Command{
216205
UsageFunc: serverSortedFlags.printUsage,
217206
Options: options,
@@ -272,7 +261,6 @@ func Start(cfg *config.Config) error {
272261
ShortUsage: "pyroscope [flags] <subcommand>",
273262
FlagSet: rootFlagSet,
274263
Subcommands: []*ffcli.Command{
275-
agentCmd,
276264
convertCmd,
277265
serverCmd,
278266
execCmd,
@@ -282,15 +270,6 @@ func Start(cfg *config.Config) error {
282270
},
283271
}
284272

285-
agentCmd.Exec = func(_ context.Context, args []string) error {
286-
if l, err := logrus.ParseLevel(cfg.Agent.LogLevel); err == nil {
287-
logrus.SetLevel(l)
288-
}
289-
a := agent.New(cfg)
290-
atexit.Register(a.Stop)
291-
a.Start()
292-
return nil
293-
}
294273
serverCmd.Exec = func(_ context.Context, args []string) error {
295274
if l, err := logrus.ParseLevel(cfg.Server.LogLevel); err == nil {
296275
logrus.SetLevel(l)
@@ -374,7 +353,7 @@ func startServer(cfg *config.Config) {
374353
panic(err)
375354
}
376355
u := direct.New(cfg, s)
377-
go agent.SelfProfile(cfg, u, "pyroscope.server.cpu{}")
356+
go agent.SelfProfile(cfg, u, "pyroscope.server.cpu{}", logrus.StandardLogger())
378357
go printRAMUsage()
379358
go printDiskUsage(cfg)
380359
c := server.New(cfg, s)

pkg/dbmanager/cli.go

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@ import (
99
"github.com/pyroscope-io/pyroscope/pkg/config"
1010
"github.com/pyroscope-io/pyroscope/pkg/storage"
1111
"github.com/pyroscope-io/pyroscope/pkg/util/atexit"
12+
"github.com/sirupsen/logrus"
1213

1314
"github.com/cheggaaa/pb/v3"
1415
)
@@ -69,7 +70,7 @@ func copyData(cfg *config.Config) error {
6970

7071
if cfg.DbManager.EnableProfiling {
7172
u := direct.New(cfg, s)
72-
go agent.SelfProfile(cfg, u, "pyroscope.dbmanager.cpu{}")
73+
go agent.SelfProfile(cfg, u, "pyroscope.dbmanager.cpu{}", logrus.StandardLogger())
7374
}
7475

7576
st := srcSt

0 commit comments

Comments
 (0)