Skip to content

Commit d5bb89d

Browse files
authoredMay 1, 2024··
Merge pull request #122 from yubiuser/new/config_file
New/config file
2 parents 363454f + 9059ffd commit d5bb89d

15 files changed

+340
-275
lines changed
 

‎Readme.md

+39-53
Original file line numberDiff line numberDiff line change
@@ -37,39 +37,15 @@ docker pull ghcr.io/yubiuser/docker-event-monitor:latest
3737
### Docker compose
3838

3939
```yaml
40-
version: '2.4'
41-
4240
services:
4341
docker-event-monitor:
4442
container_name: docker-event-monitor
4543
image: ghcr.io/yubiuser/docker-event-monitor:latest
4644
volumes:
4745
- /var/run/docker.sock:/var/run/docker.sock:ro
4846
- /etc/localtime:/etc/localtime:ro
47+
- ./config.yml:/config.yml:ro
4948
restart: unless-stopped
50-
environment:
51-
PUSHOVER: false
52-
PUSHOVER_USER: 'USER'
53-
PUSHOVER_APITOKEN: 'TOKEN'
54-
GOTIFY: false
55-
GOTIFY_URL: 'URL'
56-
GOTIFY_TOKEN: 'TOKEN'
57-
MAIL: false
58-
MAIL_FROM: 'your.username@provider.com'
59-
MAIL_TO: 'recipient@provider.com'
60-
MAIL_USER: 'SMTP USER'
61-
MAIL_PASSWORD: 'PASSWORD'
62-
MAIL_PORT: 587
63-
MAIL_HOST: 'smtp@provider.com'
64-
MATTERMOST: false
65-
MATTERMOST_URL: 'URL'
66-
MATTERMOST_CHANNEL: 'Channel'
67-
MATTERMOST_USER: 'User'
68-
FILTER: 'type=container'
69-
EXCLUDE: 'Action=exec_start,Action=exec_die,Action=exec_create'
70-
DELAY: '500ms'
71-
LOG_LEVEL: 'info'
72-
SERVER_TAG: ''
7349
```
7450
7551
### Build image locally
@@ -85,34 +61,44 @@ docker build -t docker-event-monitor:local .
8561

8662
If you have a suitable `Go` environment set up, you can build the binary from `/src/`. For development, a `devcontainer` with a suitable `Dockerfile` is provided as well. If you run `make build` instead of `go build`, `git` commit/branch/date information are injected into to binary.
8763

88-
### Environment variables and configuration
89-
90-
Configurations can use the CLI flags or environment variables. The table below outlines all supported options and their respective env vars.
91-
92-
| Flag | Env Variable | Default | Details |
93-
| ---------------- | ---------------------- | ------- |-------- |
94-
| `--pushover` | `PUSHOVER` | `false` | Enable/Disable Pushover notification|
95-
| `--pushoverapitoken` | `PUSHOVER_APITOKEN` | `""` | |
96-
| `--pushoveruserkey` | `PUSHOVER_USER` | `""` | |
97-
| `--delay` | `DELAY` | `500ms` | Delay befor processing next event. Can be useful if messages arrive in wrong order |
98-
| `--gotify` | `GOTIFY` | `false` | Enable/Disable Gotify notification|
99-
| `--gotifyurl` | `GOTIFY_URL` | `""` | |
100-
| `--gotifytoken` | `GOTIFY_TOKEN` | `""` | |
101-
| `--mail` | `MAIL` | `false` | Enable/Disable E-Mail (SMTP) notification|
102-
| `--mailfrom` | `MAIL_FROM` | `""` | optional: `your.username@provider.com`, set to MAIL_USER if empty/unset |
103-
| `--mailto` | `MAIL_TO` | `""` | `recipient@provider.com` |
104-
| `--mailuser` | `MAIL_USER` | `""` | SMTP username |
105-
| `--mailpassword` | `MAIL_PASSWORD` | `""` | |
106-
| `--mailport` | `MAIL_PORT` | `587` | |
107-
| `--mailhost` | `MAIL_HOST` | `""` | `smtp@provider.com` |
108-
| `--mattermost` | `MATTERMOST` | `false` | Enable/Disable Mattermost notification|
109-
| `--mattermosturl` | `MATTERMOST_URL` | `""` | |
110-
| `--mattermostchannel` | `MATTERMOST_CHANNEL` | `""` | optional |
111-
| `--mattermostuser` | `MATTERMOST_USER` | `"Docker Event Monitor"` | |
112-
| `--filter` | `FILTER` | `""` | Filter events. Uses the same filters as `docker events` (see [here](https://docs.docker.com/engine/reference/commandline/events/#filter)) |
113-
| `--exclude` | `EXCLUDE` | `""` | Exclude events from being reported |
114-
| `--loglevel` | `LOG_LEVEL` | `"info"`| Use `debug` for more verbose logging |
115-
| `--servertag` | `SERVER_TAG` | `""` | Prefix to include in the title of notifications. Useful when running docker-event-monitors on multiple machines |
64+
### Configuration
65+
66+
Configuration is loaded from a config file, by defaut `config.yml`. The path can be adjusted by `docker-event-monitor --config [path]`.
67+
Currently the following options can be set via `config.yml`
68+
69+
```yaml
70+
---
71+
options:
72+
delay: 500ms
73+
filter_strings: ["type=container"]
74+
exclude_strings: ["Action=exec_start", "Action=exec_die", "Action=exec_create"]
75+
log_level: debug
76+
server_tag: My Server
77+
78+
reporter:
79+
pushover:
80+
enabled: true
81+
api_token: xyz
82+
user_key: abc
83+
gotify:
84+
enabled: true
85+
url: http://gotify.lan
86+
token: xyz
87+
mail:
88+
enabled: true
89+
from: your.username@provider.com
90+
to: recipient@provider.com
91+
user: SMTP Username
92+
password: SMTP Password
93+
port: 587
94+
host: SMTP Host
95+
mattermost:
96+
enabled: true
97+
url: http://mattermost.lan
98+
channel: Docker Event Channel
99+
user: Docker Event Bot
100+
101+
```
116102

117103
### Filter and exclude events
118104

‎docker-compose.yml

+1-20
Original file line numberDiff line numberDiff line change
@@ -1,28 +1,9 @@
1-
version: '2.4'
2-
31
services:
42
docker-event-monitor:
53
container_name: docker-event-monitor
64
image: ghcr.io/yubiuser/docker-event-monitor:latest
75
volumes:
86
- /var/run/docker.sock:/var/run/docker.sock:ro
97
- /etc/localtime:/etc/localtime:ro
8+
- ./config.yml:/config.yml:ro
109
restart: unless-stopped
11-
environment:
12-
PUSHOVER: false
13-
PUSHOVER_USER: 'USER'
14-
PUSHOVER_APITOKEN: 'TOKEN'
15-
GOTIFY: false
16-
GOTIFY_URL: 'URL'
17-
GOTIFY_TOKEN: 'TOKEN'
18-
MAIL: false
19-
MAIL_FROM: 'your.username@provider.com'
20-
MAIL_TO: 'recipient@provider.com'
21-
MAIL_USER: 'SMTP USER'
22-
MAIL_PASSWORD: 'PASSWORD'
23-
MAIL_PORT: 587
24-
MAIL_HOST: 'smtp@provider.com'
25-
FILTER: 'event=start,event=stop,type=container'
26-
DELAY: '500ms'
27-
LOG_LEVEL: 'info'
28-
SERVER_TAG: ''

‎src/config.yml

+31
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
---
2+
options:
3+
delay: 500ms
4+
filter_strings: ["type=container"]
5+
exclude_strings: ["Action=exec_start", "Action=exec_die", "Action=exec_create"]
6+
log_level: debug
7+
server_tag: My Server
8+
9+
reporter:
10+
pushover:
11+
enabled: true
12+
api_token: xyz
13+
user_key: abc
14+
gotify:
15+
enabled: true
16+
url: http://gotify.lan
17+
token: xyz
18+
mail:
19+
enabled: true
20+
from: your.username@provider.com
21+
to: recipient@provider.com
22+
user: SMTP Username
23+
password: SMTP Password
24+
port: 587
25+
host: SMTP Host
26+
mattermost:
27+
enabled: true
28+
url: http://mattermost.lan
29+
channel: Docker Event Channel
30+
user: Docker Event Bot
31+

‎src/events.go

+12-11
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@ import (
66
"time"
77

88
"github.com/docker/docker/api/types/events"
9+
"github.com/rs/zerolog/log"
910
"golang.org/x/text/cases"
1011
"golang.org/x/text/language"
1112
)
@@ -21,7 +22,7 @@ func processEvent(event events.Message) {
2122
// Sometimes events are pushed through the event channel really quickly, but they arrive on the notification clients in
2223
// wrong order (probably due to message delivery time), e.g. Pushover is susceptible for this.
2324
// Finishing this function not before a certain time before draining the next event from the event channel in main() solves the issue
24-
timer := time.NewTimer(glb_arguments.Delay)
25+
timer := time.NewTimer(config.Options.Delay)
2526

2627
ActorID = getActorID(event)
2728
ActorImage = getActorImage(event)
@@ -72,7 +73,7 @@ func processEvent(event events.Message) {
7273
message := strings.TrimRight(msg_builder.String(), "\n")
7374

7475
// Log message
75-
logger.Info().
76+
log.Info().
7677
Str("eventType", string(event.Type)).
7778
Str("ActorID", ActorID).
7879
Str("eventAction", string(event.Action)).
@@ -85,7 +86,7 @@ func processEvent(event events.Message) {
8586

8687
// send notifications to various reporters
8788
// function will finish when all reporters finished
88-
sendNotifications(timestamp, message, title, glb_arguments.Reporters)
89+
sendNotifications(timestamp, message, title, config.Reporters)
8990

9091
// block function until time (delay) triggers
9192
// if sendNotifications is faster than the delay, function blocks here until delay is over
@@ -155,22 +156,22 @@ func excludeEvent(event events.Message) bool {
155156
eventMap := structToFlatMap(event)
156157

157158
// Check for all exclude key -> value combinations if they match the event
158-
for key, values := range glb_arguments.Exclude {
159+
for key, values := range config.Exclude {
159160
eventValue, keyExist := eventMap[key]
160161

161162
// Check if the exclusion key exists in the eventMap
162163
if !keyExist {
163-
logger.Debug().
164+
log.Debug().
164165
Str("ActorID", ActorID).
165166
Msgf("Exclusion key \"%s\" did not match", key)
166167
return false
167168
}
168169

169-
logger.Debug().
170+
log.Debug().
170171
Str("ActorID", ActorID).
171172
Msgf("Exclusion key \"%s\" matched, checking values", key)
172173

173-
logger.Debug().
174+
log.Debug().
174175
Str("ActorID", ActorID).
175176
Msgf("Event's value for key \"%s\" is \"%s\"", key, eventValue)
176177

@@ -180,13 +181,13 @@ func excludeEvent(event events.Message) bool {
180181
// see https://github.com/moby/moby/blob/bf053be997f87af233919a76e6ecbd7d17390e62/api/types/events/events.go#L74-L81
181182

182183
if strings.HasPrefix(eventValue, value) {
183-
logger.Debug().
184+
log.Debug().
184185
Str("ActorID", ActorID).
185186
Msgf("Event excluded based on exclusion setting \"%s=%s\"", key, value)
186187
return true
187188
}
188189
}
189-
logger.Debug().
190+
log.Debug().
190191
Str("ActorID", ActorID).
191192
Msgf("Exclusion key \"%s\" matched, but values did not match", key)
192193
}
@@ -224,15 +225,15 @@ func structToFlatMap(s interface{}) map[string]string {
224225
m := make(map[string]interface{})
225226
b, err := json.Marshal(s)
226227
if err != nil {
227-
logger.Fatal().Err(err).Msg("Marshaling JSON failed")
228+
log.Fatal().Err(err).Msg("Marshaling JSON failed")
228229
}
229230

230231
// Using a custom decoder to set 'UseNumber' which will preserver a string representation of
231232
// time and timeNano instead of converting it to float64
232233
decoder := json.NewDecoder(strings.NewReader(string(b)))
233234
decoder.UseNumber()
234235
if err := decoder.Decode(&m); err != nil {
235-
logger.Fatal().Err(err).Msg("Unmarshaling JSON failed")
236+
log.Fatal().Err(err).Msg("Unmarshaling JSON failed")
236237
}
237238
return flattenMap("", m)
238239
}

‎src/go.mod

+1-2
Original file line numberDiff line numberDiff line change
@@ -3,15 +3,14 @@ module docker-event-monitor
33
go 1.21
44

55
require (
6-
github.com/alexflint/go-arg v1.4.3
76
github.com/docker/docker v26.1.0+incompatible
87
github.com/rs/zerolog v1.32.0
98
golang.org/x/text v0.14.0
9+
gopkg.in/yaml.v3 v3.0.1
1010
)
1111

1212
require (
1313
github.com/Microsoft/go-winio v0.6.1 // indirect
14-
github.com/alexflint/go-scalar v1.2.0 // indirect
1514
github.com/containerd/log v0.1.0 // indirect
1615
github.com/distribution/reference v0.5.0 // indirect
1716
github.com/docker/go-connections v0.5.0 // indirect

‎src/go.sum

+1-10
Original file line numberDiff line numberDiff line change
@@ -2,17 +2,11 @@ github.com/Azure/go-ansiterm v0.0.0-20210617225240-d185dfc1b5a1 h1:UQHMgLO+TxOEl
22
github.com/Azure/go-ansiterm v0.0.0-20210617225240-d185dfc1b5a1/go.mod h1:xomTg63KZ2rFqZQzSB4Vz2SUXa1BpHTVz9L5PTmPC4E=
33
github.com/Microsoft/go-winio v0.6.1 h1:9/kr64B9VUZrLm5YYwbGtUJnMgqWVOdUAXu6Migciow=
44
github.com/Microsoft/go-winio v0.6.1/go.mod h1:LRdKpFKfdobln8UmuiYcKPot9D2v6svN5+sAH+4kjUM=
5-
github.com/alexflint/go-arg v1.4.3 h1:9rwwEBpMXfKQKceuZfYcwuc/7YY7tWJbFsgG5cAU/uo=
6-
github.com/alexflint/go-arg v1.4.3/go.mod h1:3PZ/wp/8HuqRZMUUgu7I+e1qcpUbvmS258mRXkFH4IA=
7-
github.com/alexflint/go-scalar v1.1.0/go.mod h1:LoFvNMqS1CPrMVltza4LvnGKhaSpc3oyLEBUZVhhS2o=
8-
github.com/alexflint/go-scalar v1.2.0 h1:WR7JPKkeNpnYIOfHRa7ivM21aWAdHD0gEWHCx+WQBRw=
9-
github.com/alexflint/go-scalar v1.2.0/go.mod h1:LoFvNMqS1CPrMVltza4LvnGKhaSpc3oyLEBUZVhhS2o=
105
github.com/cenkalti/backoff/v4 v4.2.1 h1:y4OZtCnogmCPw98Zjyt5a6+QwPLGkiQsYW5oUqylYbM=
116
github.com/cenkalti/backoff/v4 v4.2.1/go.mod h1:Y3VNntkOUPxTVeUxJ/G5vcM//AlwfmyYozVcomhLiZE=
127
github.com/containerd/log v0.1.0 h1:TCJt7ioM2cr/tfR8GPbGf9/VRAX8D2B4PjzCpfX540I=
138
github.com/containerd/log v0.1.0/go.mod h1:VRRf09a7mHDIRezVKTRCrOq78v577GXq3bSa3EhrzVo=
149
github.com/coreos/go-systemd/v22 v22.5.0/go.mod h1:Y58oyj3AT4RCenI/lSvhwexgC+NSVTIJ3seZv2GcEnc=
15-
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
1610
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
1711
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
1812
github.com/distribution/reference v0.5.0 h1:/FUIFXtfc/x2gpa5/VGfiGLuOIdYa1t65IKK2OFGvA0=
@@ -66,9 +60,6 @@ github.com/rs/zerolog v1.32.0 h1:keLypqrlIjaFsbmJOBdB/qvyF8KEtCWHwobLp5l/mQ0=
6660
github.com/rs/zerolog v1.32.0/go.mod h1:/7mN4D5sKwJLZQ2b/znpjC3/GQWY/xaDXUM0kKWRHss=
6761
github.com/sirupsen/logrus v1.9.3 h1:dueUQJ1C2q9oE3F7wvmSGAaVtTmUizReu6fjN8uqzbQ=
6862
github.com/sirupsen/logrus v1.9.3/go.mod h1:naHLuLoDiP4jHNo9R0sCBMtWGeIprob74mVsIT4qYEQ=
69-
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
70-
github.com/stretchr/testify v1.2.2/go.mod h1:a8OnRcib4nhh0OaRAV+Yts87kKdq0PP7pXfy6kDkUVs=
71-
github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
7263
github.com/stretchr/testify v1.8.4 h1:CcVxjf3Q8PM0mHUKJCdn+eZZtm5yQwehR5yeSVQQcUk=
7364
github.com/stretchr/testify v1.8.4/go.mod h1:sz/lmYIOXD/1dqDmKjjqLyZ2RngseejIcXlSw2iwfAo=
7465
github.com/yuin/goldmark v1.1.27/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74=
@@ -139,8 +130,8 @@ google.golang.org/grpc v1.60.1 h1:26+wFr+cNqSGFcOXcabYC0lUVJVRa2Sb2ortSK7VrEU=
139130
google.golang.org/grpc v1.60.1/go.mod h1:OlCHIeLYqSSsLi6i49B5QGdzaMZK9+M7LXN2FKz4eGM=
140131
google.golang.org/protobuf v1.32.0 h1:pPC6BG5ex8PDFnkbrGU3EixyhKcQ2aDuBS36lqK/C7I=
141132
google.golang.org/protobuf v1.32.0/go.mod h1:c6P6GXX6sHbq/GpV6MGZEdwhWPcYBgnhAHhKbcUYpos=
133+
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM=
142134
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
143-
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
144135
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
145136
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
146137
gotest.tools/v3 v3.5.1 h1:EENdUnS3pdur5nybKYIh2Vfgc8IUNBjxDPSjtiJcOzU=

‎src/gotify.go

+4-2
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,8 @@ package main
33
import (
44
"encoding/json"
55
"errors"
6+
7+
"github.com/rs/zerolog/log"
68
)
79

810
type GotifyMessage struct {
@@ -24,13 +26,13 @@ func sendGotify(message string, title string, errCh chan ReporterError) {
2426

2527
messageJSON, err := json.Marshal(m)
2628
if err != nil {
27-
logger.Error().Err(err).Str("reporter", "Gotify").Msg("Failed to marshal JSON")
29+
log.Error().Err(err).Str("reporter", "Gotify").Msg("Failed to marshal JSON")
2830
e.Error = errors.New("failed to marshal JSON")
2931
errCh <- e
3032
return
3133
}
3234

33-
err = sendhttpMessage("Gotify", glb_arguments.GotifyURL+"/message?token="+glb_arguments.GotifyToken, messageJSON)
35+
err = sendhttpMessage("Gotify", config.Reporter.Gotify.URL+"/message?token="+config.Reporter.Gotify.Token, messageJSON)
3436
if err != nil {
3537
e.Error = err
3638
errCh <- e

‎src/mail.go

+9-7
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,8 @@ import (
66
"strconv"
77
"strings"
88
"time"
9+
10+
"github.com/rs/zerolog/log"
911
)
1012

1113
func buildEMail(timestamp time.Time, from string, to []string, subject string, body string) string {
@@ -26,13 +28,13 @@ func sendMail(timestamp time.Time, message string, title string, errCh chan Repo
2628
Reporter: "Mail",
2729
}
2830

29-
from := glb_arguments.MailFrom
30-
to := []string{glb_arguments.MailTo}
31-
username := glb_arguments.MailUser
32-
password := glb_arguments.MailPassword
31+
from := config.Reporter.Mail.From
32+
to := []string{config.Reporter.Mail.To}
33+
username := config.Reporter.Mail.User
34+
password := config.Reporter.Mail.Password
3335

34-
host := glb_arguments.MailHost
35-
port := strconv.Itoa(glb_arguments.MailPort)
36+
host := config.Reporter.Mail.Host
37+
port := strconv.Itoa(config.Reporter.Mail.Port)
3638
address := host + ":" + port
3739

3840
subject := title
@@ -44,7 +46,7 @@ func sendMail(timestamp time.Time, message string, title string, errCh chan Repo
4446

4547
err := smtp.SendMail(address, auth, from, to, []byte(mail))
4648
if err != nil {
47-
logger.Error().Err(err).Str("reporter", "Mail").Msg("")
49+
log.Error().Err(err).Str("reporter", "Mail").Msg("")
4850
e.Error = errors.New("failed to send mail")
4951
errCh <- e
5052
return

‎src/main.go

+109-109
Original file line numberDiff line numberDiff line change
@@ -2,109 +2,102 @@ package main
22

33
import (
44
"context"
5+
"flag"
6+
"fmt"
57
"os"
8+
"path/filepath"
69
"strings"
710
"time"
811

9-
"github.com/alexflint/go-arg"
1012
"github.com/docker/docker/api/types"
1113
"github.com/docker/docker/api/types/filters"
1214
"github.com/docker/docker/client"
15+
"gopkg.in/yaml.v3"
1316

1417
"github.com/rs/zerolog"
18+
"github.com/rs/zerolog/log"
1519
)
1620

17-
type args struct {
18-
Pushover bool `arg:"env:PUSHOVER" default:"false" help:"Enable/Disable Pushover Notification (True/False)"`
19-
PushoverAPIToken string `arg:"env:PUSHOVER_APITOKEN" help:"Pushover's API Token/Key"`
20-
PushoverUserKey string `arg:"env:PUSHOVER_USER" help:"Pushover's User Key"`
21-
Gotify bool `arg:"env:GOTIFY" default:"false" help:"Enable/Disable Gotify Notification (True/False)"`
22-
GotifyURL string `arg:"env:GOTIFY_URL" help:"URL of your Gotify server"`
23-
GotifyToken string `arg:"env:GOTIFY_TOKEN" help:"Gotify's App Token"`
24-
Mail bool `arg:"env:MAIL" default:"false" help:"Enable/Disable Mail (SMTP) Notification (True/False)"`
25-
MailFrom string `arg:"env:MAIL_FROM" help:"your.username@provider.com"`
26-
MailTo string `arg:"env:MAIL_TO" help:"recipient@provider.com"`
27-
MailUser string `arg:"env:MAIL_USER" help:"SMTP Username"`
28-
MailPassword string `arg:"env:MAIL_PASSWORD" help:"SMTP Password"`
29-
MailPort int `arg:"env:MAIL_PORT" default:"587" help:"SMTP Port"`
30-
MailHost string `arg:"env:MAIL_HOST" help:"SMTP Host"`
31-
Mattermost bool `arg:"env:MATTERMOST" default:"false" help:"Enable/Disable Mattermost Notification (True/False)"`
32-
MattermostURL string `arg:"env:MATTERMOST_URL" help:"URL of your Mattermost incoming webhook"`
33-
MattermostChannel string `arg:"env:MATTERMOST_CHANNEL" help:"Mattermost channel to post in"`
34-
MattermostUser string `arg:"env:MATTERMOST_USER" default:"Docker Event Monitor" help:"Mattermost user to post as"`
35-
Reporters []string `arg:"-"`
36-
Delay time.Duration `arg:"env:DELAY" default:"500ms" help:"Delay before next message is send"`
37-
FilterStrings []string `arg:"env:FILTER,--filter,separate" help:"Filter docker events using Docker syntax."`
38-
Filter map[string][]string `arg:"-"`
39-
ExcludeStrings []string `arg:"env:EXCLUDE,--exclude,separate" help:"Exclude docker events using Docker syntax."`
40-
Exclude map[string][]string `arg:"-"`
41-
LogLevel string `arg:"env:LOG_LEVEL" default:"info" help:"Set log level. Use debug for more logging."`
42-
ServerTag string `arg:"env:SERVER_TAG" help:"Prefix to include in the title of notifications. Useful when running docker-event-monitors on multiple machines."`
43-
Version bool `arg:"-v" help:"Print version information."`
44-
}
21+
// hold config options and settings globally
22+
var config Config
4523

46-
// Creating a global logger
47-
var logger zerolog.Logger
24+
// should we only print version information and exit
25+
var showVersion bool
4826

49-
// hold the supplied run-time arguments globally
50-
var glb_arguments args
27+
// config file path
28+
var configFilePath string
5129

52-
// version information, are injected during build process
53-
var (
54-
version string = "n/a"
55-
commit string = "n/a"
56-
date string = "0"
57-
gitdate string = "0"
58-
branch string = "n/a"
59-
)
30+
var PrintUsage = func() {
31+
fmt.Printf("Usage of %s", os.Args[0])
32+
fmt.Print(
33+
`
34+
-v, --version prints version information
35+
-c, --config [path] config file path (default "config.yml")
36+
-h, --help prints help information
37+
`)
38+
}
6039

6140
func init() {
41+
flag.BoolVar(&showVersion, "v", false, "print version information")
42+
flag.BoolVar(&showVersion, "version", false, "print version information")
43+
flag.StringVar(&configFilePath, "c", "config.yml", "config file path")
44+
flag.StringVar(&configFilePath, "config", "config.yml", "config file path")
45+
flag.Usage = PrintUsage
46+
flag.Parse()
47+
48+
configureLogger()
49+
loadConfig()
50+
51+
// after loading the config, we we migth increase log level
52+
if config.Options.LogLevel == "debug" {
53+
zerolog.SetGlobalLevel(zerolog.DebugLevel)
54+
}
55+
6256
parseArgs()
63-
configureLogger(glb_arguments.LogLevel)
6457

65-
if glb_arguments.Pushover {
66-
if len(glb_arguments.PushoverAPIToken) == 0 {
67-
logger.Fatal().Msg("Pushover enabled. Pushover API token required!")
58+
if config.Reporter.Pushover.Enabled {
59+
if len(config.Reporter.Pushover.APIToken) == 0 {
60+
log.Fatal().Msg("Pushover Enabled. Pushover API token required!")
6861
}
69-
if len(glb_arguments.PushoverUserKey) == 0 {
70-
logger.Fatal().Msg("Pushover enabled. Pushover user key required!")
62+
if len(config.Reporter.Pushover.UserKey) == 0 {
63+
log.Fatal().Msg("Pushover Enabled. Pushover user key required!")
7164
}
7265
}
73-
if glb_arguments.Gotify {
74-
if len(glb_arguments.GotifyURL) == 0 {
75-
logger.Fatal().Msg("Gotify enabled. Gotify URL required!")
66+
if config.Reporter.Gotify.Enabled {
67+
if len(config.Reporter.Gotify.URL) == 0 {
68+
log.Fatal().Msg("Gotify Enabled. Gotify URL required!")
7669
}
77-
if len(glb_arguments.GotifyToken) == 0 {
78-
logger.Fatal().Msg("Gotify enabled. Gotify APP token required!")
70+
if len(config.Reporter.Gotify.Token) == 0 {
71+
log.Fatal().Msg("Gotify Enabled. Gotify APP token required!")
7972
}
8073
}
81-
if glb_arguments.Mail {
82-
if len(glb_arguments.MailUser) == 0 {
83-
logger.Fatal().Msg("E-Mail notification enabled. SMTP username required!")
74+
if config.Reporter.Mail.Enabled {
75+
if len(config.Reporter.Mail.User) == 0 {
76+
log.Fatal().Msg("E-Mail notification Enabled. SMTP username required!")
8477
}
85-
if len(glb_arguments.MailTo) == 0 {
86-
logger.Fatal().Msg("E-Mail notification enabled. Recipient address required!")
78+
if len(config.Reporter.Mail.To) == 0 {
79+
log.Fatal().Msg("E-Mail notification Enabled. Recipient address required!")
8780
}
88-
if len(glb_arguments.MailFrom) == 0 {
89-
glb_arguments.MailFrom = glb_arguments.MailUser
81+
if len(config.Reporter.Mail.From) == 0 {
82+
config.Reporter.Mail.From = config.Reporter.Mail.User
9083
}
91-
if len(glb_arguments.MailPassword) == 0 {
92-
logger.Fatal().Msg("E-Mail notification enabled. SMTP Password required!")
84+
if len(config.Reporter.Mail.Password) == 0 {
85+
log.Fatal().Msg("E-Mail notification Enabled. SMTP Password required!")
9386
}
94-
if len(glb_arguments.MailHost) == 0 {
95-
logger.Fatal().Msg("E-Mail notification enabled. SMTP host address required!")
87+
if len(config.Reporter.Mail.Host) == 0 {
88+
log.Fatal().Msg("E-Mail notification Enabled. SMTP host address required!")
9689
}
9790
}
98-
if glb_arguments.Mattermost {
99-
if len(glb_arguments.MattermostURL) == 0 {
100-
logger.Fatal().Msg("Mattermost enabled. Mattermost URL required!")
91+
if config.Reporter.Mattermost.Enabled {
92+
if len(config.Reporter.Mattermost.URL) == 0 {
93+
log.Fatal().Msg("Mattermost Enabled. Mattermost URL required!")
10194
}
10295
}
10396
}
10497

10598
func main() {
10699
// if the -v flag was set, print version information and exit
107-
if glb_arguments.Version {
100+
if showVersion {
108101
printVersion()
109102
}
110103

@@ -113,18 +106,18 @@ func main() {
113106

114107
timestamp := time.Now()
115108
startup_message := buildStartupMessage(timestamp)
116-
sendNotifications(timestamp, startup_message, "Starting docker event monitor", glb_arguments.Reporters)
109+
sendNotifications(timestamp, startup_message, "Starting docker event monitor", config.Reporters)
117110

118111
filterArgs := filters.NewArgs()
119-
for key, values := range glb_arguments.Filter {
112+
for key, values := range config.Filter {
120113
for _, value := range values {
121114
filterArgs.Add(key, value)
122115
}
123116
}
124117

125118
cli, err := client.NewClientWithOpts(client.FromEnv, client.WithAPIVersionNegotiation())
126119
if err != nil {
127-
logger.Fatal().Err(err).Msg("Failed to create new docker client")
120+
log.Fatal().Err(err).Msg("Failed to create new docker client")
128121
}
129122
defer cli.Close()
130123

@@ -134,15 +127,15 @@ func main() {
134127
for {
135128
select {
136129
case err := <-errs:
137-
logger.Fatal().Err(err).Msg("")
130+
log.Fatal().Err(err).Msg("")
138131
case event := <-event_chan:
139132
// if logging level is debug, log the event
140-
logger.Debug().
133+
log.Debug().
141134
Interface("event", event).Msg("")
142135

143136
// Check if event should be exlcuded from reporting
144-
if len(glb_arguments.Exclude) > 0 {
145-
logger.Debug().Msg("Performing check for event exclusion")
137+
if len(config.Exclude) > 0 {
138+
log.Debug().Msg("Performing check for event exclusion")
146139
if excludeEvent(event) {
147140
break //breaks out of the select and waits for the next event to arrive
148141
}
@@ -152,71 +145,78 @@ func main() {
152145
}
153146
}
154147

148+
func loadConfig() {
149+
configFile, err := filepath.Abs(configFilePath)
150+
151+
if err != nil {
152+
log.Fatal().Err(err).Msg("Failed to set config file path")
153+
}
154+
155+
buf, err := os.ReadFile(configFile)
156+
if err != nil {
157+
log.Fatal().Err(err).Msg("Failed to read config file")
158+
}
159+
160+
err = yaml.Unmarshal(buf, &config)
161+
if err != nil {
162+
log.Fatal().Err(err).Msg("Failed to parse config file")
163+
}
164+
}
165+
155166
func parseArgs() {
156-
parser := arg.MustParse(&glb_arguments)
157167

158168
// Parse (include) filters
159-
glb_arguments.Filter = make(map[string][]string)
169+
config.Filter = make(map[string][]string)
160170

161-
for _, filter := range glb_arguments.FilterStrings {
171+
for _, filter := range config.Options.FilterStrings {
162172
pos := strings.Index(filter, "=")
163173
if pos == -1 {
164-
parser.Fail("each filter should be of the form key=value")
174+
log.Fatal().Msg("each filter should be of the form key=value")
165175
}
166176
key := filter[:pos]
167177
val := filter[pos+1:]
168-
glb_arguments.Filter[key] = append(glb_arguments.Filter[key], val)
178+
config.Filter[key] = append(config.Filter[key], val)
169179
}
170180

171181
// Parse exclude filters
172-
glb_arguments.Exclude = make(map[string][]string)
182+
config.Exclude = make(map[string][]string)
173183

174-
for _, exclude := range glb_arguments.ExcludeStrings {
184+
for _, exclude := range config.Options.ExcludeStrings {
175185
pos := strings.Index(exclude, "=")
176186
if pos == -1 {
177-
parser.Fail("each filter should be of the form key=value")
187+
log.Fatal().Msg("each filter should be of the form key=value")
178188
}
179189
//trim whitespaces
180190
key := strings.TrimSpace(exclude[:pos])
181191
val := exclude[pos+1:]
182-
glb_arguments.Exclude[key] = append(glb_arguments.Exclude[key], val)
192+
config.Exclude[key] = append(config.Exclude[key], val)
183193
}
184194

185-
//Parse enabled reportes
195+
//Parse Enabled reportes
186196

187-
if glb_arguments.Gotify {
188-
glb_arguments.Reporters = append(glb_arguments.Reporters, "Gotify")
197+
if config.Reporter.Gotify.Enabled {
198+
config.Reporters = append(config.Reporters, "Gotify")
189199
}
190-
if glb_arguments.Mattermost {
191-
glb_arguments.Reporters = append(glb_arguments.Reporters, "Mattermost")
200+
if config.Reporter.Mattermost.Enabled {
201+
config.Reporters = append(config.Reporters, "Mattermost")
192202
}
193-
if glb_arguments.Pushover {
194-
glb_arguments.Reporters = append(glb_arguments.Reporters, "Pushover")
203+
if config.Reporter.Pushover.Enabled {
204+
config.Reporters = append(config.Reporters, "Pushover")
195205
}
196-
if glb_arguments.Mail {
197-
glb_arguments.Reporters = append(glb_arguments.Reporters, "Mail")
206+
if config.Reporter.Mail.Enabled {
207+
config.Reporters = append(config.Reporters, "Mail")
198208
}
199209

200210
}
201211

202-
func configureLogger(LogLevel string) {
212+
func configureLogger() {
213+
203214
// Configure time/timestamp format
204215
zerolog.TimeFieldFormat = time.RFC1123Z
205216

206-
// Change logging level when debug flag is set
207-
if LogLevel == "debug" {
208-
logger = zerolog.New(os.Stdout).
209-
Level(zerolog.DebugLevel).
210-
With().
211-
Timestamp().
212-
Str("service", "docker event monitor").
213-
Logger()
214-
} else {
215-
logger = zerolog.New(os.Stdout).
216-
Level(zerolog.InfoLevel).
217-
With().
218-
Str("service", "docker event monitor").
219-
Timestamp().
220-
Logger()
221-
}
217+
// Default level is info
218+
zerolog.SetGlobalLevel(zerolog.InfoLevel)
219+
220+
// Add timestamp and service string
221+
log.Logger = log.With().Timestamp().Str("service", "docker event monitor").Logger()
222222
}

‎src/mattermost.go

+6-4
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,8 @@ package main
33
import (
44
"encoding/json"
55
"errors"
6+
7+
"github.com/rs/zerolog/log"
68
)
79

810
// Adapted from https://github.com/mdeheij/mattergo
@@ -18,8 +20,8 @@ type MattermostMessage struct {
1820
func sendMattermost(message string, title string, errCh chan ReporterError) {
1921

2022
m := MattermostMessage{
21-
Username: glb_arguments.MattermostUser,
22-
Channel: glb_arguments.MattermostChannel,
23+
Username: config.Reporter.Mattermost.User,
24+
Channel: config.Reporter.Mattermost.Channel,
2325
Text: "##### " + title + "\n" + message,
2426
}
2527

@@ -29,13 +31,13 @@ func sendMattermost(message string, title string, errCh chan ReporterError) {
2931

3032
messageJSON, err := json.Marshal(m)
3133
if err != nil {
32-
logger.Error().Err(err).Str("reporter", "Mattermost").Msg("Failed to marshal JSON")
34+
log.Error().Err(err).Str("reporter", "Mattermost").Msg("Failed to marshal JSON")
3335
e.Error = errors.New("failed to marshal JSON")
3436
errCh <- e
3537
return
3638
}
3739

38-
err = sendhttpMessage("Mattermost", glb_arguments.MattermostURL, messageJSON)
40+
err = sendhttpMessage("Mattermost", config.Reporter.Mattermost.URL, messageJSON)
3941
if err != nil {
4042
e.Error = err
4143
errCh <- e

‎src/notifications.go

+10-8
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,8 @@ import (
1010
"strconv"
1111
"sync"
1212
"time"
13+
14+
"github.com/rs/zerolog/log"
1315
)
1416

1517
type ReporterError struct {
@@ -29,8 +31,8 @@ func sendNotifications(timestamp time.Time, message string, title string, report
2931
errCh := make(chan ReporterError, len(reporters))
3032

3133
// If there is a server tag, add it to the title
32-
if len(glb_arguments.ServerTag) > 0 {
33-
title = "[" + glb_arguments.ServerTag + "] " + title
34+
if len(config.Options.ServerTag) > 0 {
35+
title = "[" + config.Options.ServerTag + "] " + title
3436
}
3537

3638
if slices.Contains(reporters, "Pushover") {
@@ -79,7 +81,7 @@ func sendNotifications(timestamp time.Time, message string, title string, report
7981

8082
// Error if all failed
8183
if len(ReporterErrors) == len(reporters) {
82-
logger.Error().Msg("All reporters failed!")
84+
log.Error().Msg("All reporters failed!")
8385
return
8486
}
8587

@@ -114,7 +116,7 @@ func sendhttpMessage(reporter string, address string, messageJSON []byte) error
114116
req, err := http.NewRequest("POST", address, bytes.NewBuffer(messageJSON))
115117
req.Header.Set("Content-Type", "application/json; charset=UTF-8")
116118
if err != nil {
117-
logger.Error().Err(err).Str("reporter", reporter).Msg("Failed to build request")
119+
log.Error().Err(err).Str("reporter", reporter).Msg("Failed to build request")
118120
return errors.New("failed to build request")
119121
}
120122

@@ -126,7 +128,7 @@ func sendhttpMessage(reporter string, address string, messageJSON []byte) error
126128
// Send request
127129
resp, err := netClient.Do(req)
128130
if err != nil {
129-
logger.Error().Err(err).Str("reporter", reporter).Msg("Failed to send request")
131+
log.Error().Err(err).Str("reporter", reporter).Msg("Failed to send request")
130132
return errors.New("failed to send request")
131133
}
132134
defer resp.Body.Close()
@@ -135,20 +137,20 @@ func sendhttpMessage(reporter string, address string, messageJSON []byte) error
135137

136138
respBody, err := io.ReadAll(resp.Body)
137139
if err != nil {
138-
logger.Error().Err(err).Str("reporter", reporter).Msg("")
140+
log.Error().Err(err).Str("reporter", reporter).Msg("")
139141
return errors.New("reading response body failed")
140142
}
141143

142144
// Log non successfull status codes
143145
if statusCode != 200 {
144-
logger.Error().
146+
log.Error().
145147
Str("reporter", reporter).
146148
Int("status code", statusCode).
147149
Str("response body", string(respBody)).
148150
Msg("Pushing message failed")
149151
return errors.New("pushing message failed\nhttp status code: " + strconv.Itoa(statusCode))
150152
}
151-
logger.Debug().
153+
log.Debug().
152154
Str("reporter", reporter).
153155
Int("statusCode", statusCode).
154156
Str("responseBody", string(respBody)).

‎src/pushover.go

+5-3
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,8 @@ import (
55
"errors"
66
"strconv"
77
"time"
8+
9+
"github.com/rs/zerolog/log"
810
)
911

1012
type PushoverMessage struct {
@@ -19,8 +21,8 @@ func sendPushover(timestamp time.Time, message string, title string, errCh chan
1921
// Send a message to Pushover
2022

2123
m := PushoverMessage{
22-
Token: glb_arguments.PushoverAPIToken,
23-
User: glb_arguments.PushoverUserKey,
24+
Token: config.Reporter.Pushover.APIToken,
25+
User: config.Reporter.Pushover.UserKey,
2426
Title: title,
2527
Message: message,
2628
Timestamp: strconv.FormatInt(timestamp.Unix(), 10),
@@ -32,7 +34,7 @@ func sendPushover(timestamp time.Time, message string, title string, errCh chan
3234

3335
messageJSON, err := json.Marshal(m)
3436
if err != nil {
35-
logger.Error().Err(err).Str("reporter", "Pushover").Msg("Failed to marshal JSON")
37+
log.Error().Err(err).Str("reporter", "Pushover").Msg("Failed to marshal JSON")
3638
e.Error = errors.New("failed to marshal JSON")
3739
errCh <- e
3840
return

‎src/startup.go

+45-44
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@ import (
66
"time"
77

88
"github.com/rs/zerolog"
9+
"github.com/rs/zerolog/log"
910
)
1011

1112
func buildStartupMessage(timestamp time.Time) string {
@@ -14,57 +15,57 @@ func buildStartupMessage(timestamp time.Time) string {
1415
startup_message_builder.WriteString("Docker event monitor started at " + timestamp.Format(time.RFC1123Z) + "\n")
1516
startup_message_builder.WriteString("Docker event monitor version: " + version + "\n")
1617

17-
if glb_arguments.Pushover {
18-
startup_message_builder.WriteString("Pushover notification enabled")
18+
if config.Reporter.Pushover.Enabled {
19+
startup_message_builder.WriteString("Pushover notification Enabled")
1920
} else {
2021
startup_message_builder.WriteString("Pushover notification disabled")
2122
}
2223

23-
if glb_arguments.Gotify {
24-
startup_message_builder.WriteString("\nGotify notification enabled")
24+
if config.Reporter.Gotify.Enabled {
25+
startup_message_builder.WriteString("\nGotify notification Enabled")
2526
} else {
2627
startup_message_builder.WriteString("\nGotify notification disabled")
2728
}
28-
if glb_arguments.Mail {
29-
startup_message_builder.WriteString("\nE-Mail notification enabled")
29+
if config.Reporter.Mail.Enabled {
30+
startup_message_builder.WriteString("\nE-Mail notification Enabled")
3031
} else {
3132
startup_message_builder.WriteString("\nE-Mail notification disabled")
3233
}
3334

34-
if glb_arguments.Mattermost {
35-
startup_message_builder.WriteString("\nMattermost notification enabled")
36-
if glb_arguments.MattermostChannel != "" {
37-
startup_message_builder.WriteString("\nMattermost channel: " + glb_arguments.MattermostChannel)
35+
if config.Reporter.Mattermost.Enabled {
36+
startup_message_builder.WriteString("\nMattermost notification Enabled")
37+
if config.Reporter.Mattermost.Channel != "" {
38+
startup_message_builder.WriteString("\nMattermost channel: " + config.Reporter.Mattermost.Channel)
3839
}
39-
if glb_arguments.MattermostUser != "" {
40-
startup_message_builder.WriteString("\nMattermost username: " + glb_arguments.MattermostUser)
40+
if config.Reporter.Mattermost.User != "" {
41+
startup_message_builder.WriteString("\nMattermost username: " + config.Reporter.Mattermost.User)
4142
}
4243
} else {
4344
startup_message_builder.WriteString("\nMattermost notification disabled")
4445
}
4546

46-
if glb_arguments.Delay > 0 {
47-
startup_message_builder.WriteString("\nUsing delay of " + glb_arguments.Delay.String())
47+
if config.Options.Delay > 0 {
48+
startup_message_builder.WriteString("\nUsing delay of " + config.Options.Delay.String())
4849
} else {
4950
startup_message_builder.WriteString("\nDelay disabled")
5051
}
5152

52-
startup_message_builder.WriteString("\nLog level: " + glb_arguments.LogLevel)
53+
startup_message_builder.WriteString("\nLog level: " + config.Options.LogLevel)
5354

54-
if glb_arguments.ServerTag != "" {
55-
startup_message_builder.WriteString("\nServerTag: " + glb_arguments.ServerTag)
55+
if config.Options.ServerTag != "" {
56+
startup_message_builder.WriteString("\nServerTag: " + config.Options.ServerTag)
5657
} else {
5758
startup_message_builder.WriteString("\nServerTag: none")
5859
}
5960

60-
if len(glb_arguments.FilterStrings) > 0 {
61-
startup_message_builder.WriteString("\nFilterStrings: " + strings.Join(glb_arguments.FilterStrings, " "))
61+
if len(config.Options.FilterStrings) > 0 {
62+
startup_message_builder.WriteString("\nFilterStrings: " + strings.Join(config.Options.FilterStrings, " "))
6263
} else {
6364
startup_message_builder.WriteString("\nFilterStrings: none")
6465
}
6566

66-
if len(glb_arguments.ExcludeStrings) > 0 {
67-
startup_message_builder.WriteString("\nExcludeStrings: " + strings.Join(glb_arguments.ExcludeStrings, " "))
67+
if len(config.Options.ExcludeStrings) > 0 {
68+
startup_message_builder.WriteString("\nExcludeStrings: " + strings.Join(config.Options.ExcludeStrings, " "))
6869
} else {
6970
startup_message_builder.WriteString("\nExcludeStrings: none")
7071
}
@@ -73,39 +74,39 @@ func buildStartupMessage(timestamp time.Time) string {
7374
}
7475

7576
func logArguments() {
76-
logger.Info().
77+
log.Info().
7778
Dict("options", zerolog.Dict().
7879
Dict("reporter", zerolog.Dict().
7980
Dict("Pushover", zerolog.Dict().
80-
Bool("enabled", glb_arguments.Pushover).
81-
Str("PushoverAPIToken", glb_arguments.PushoverAPIToken).
82-
Str("PushoverUserKey", glb_arguments.PushoverUserKey),
81+
Bool("Enabled", config.Reporter.Pushover.Enabled).
82+
Str("PushoverAPIToken", config.Reporter.Pushover.APIToken).
83+
Str("PushoverUserKey", config.Reporter.Pushover.UserKey),
8384
).
8485
Dict("Gotify", zerolog.Dict().
85-
Bool("enabled", glb_arguments.Gotify).
86-
Str("GotifyURL", glb_arguments.GotifyURL).
87-
Str("GotifyToken", glb_arguments.GotifyToken),
86+
Bool("Enabled", config.Reporter.Gotify.Enabled).
87+
Str("GotifyURL", config.Reporter.Gotify.URL).
88+
Str("GotifyToken", config.Reporter.Gotify.Token),
8889
).
8990
Dict("Mail", zerolog.Dict().
90-
Bool("enabled", glb_arguments.Mail).
91-
Str("MailFrom", glb_arguments.MailFrom).
92-
Str("MailTo", glb_arguments.MailTo).
93-
Str("MailHost", glb_arguments.MailHost).
94-
Str("MailUser", glb_arguments.MailUser).
95-
Int("Port", glb_arguments.MailPort),
91+
Bool("Enabled", config.Reporter.Mail.Enabled).
92+
Str("MailFrom", config.Reporter.Mail.From).
93+
Str("MailTo", config.Reporter.Mail.To).
94+
Str("MailHost", config.Reporter.Mail.Host).
95+
Str("MailUser", config.Reporter.Mail.User).
96+
Int("Port", config.Reporter.Mail.Port),
9697
).
9798
Dict("Mattermost", zerolog.Dict().
98-
Bool("enabled", glb_arguments.Mattermost).
99-
Str("MattermostURL", glb_arguments.MattermostURL).
100-
Str("MattermostChannel", glb_arguments.MattermostChannel).
101-
Str("MattermostUser", glb_arguments.MattermostUser),
99+
Bool("Enabled", config.Reporter.Mattermost.Enabled).
100+
Str("MattermostURL", config.Reporter.Mattermost.URL).
101+
Str("MattermostChannel", config.Reporter.Mattermost.Channel).
102+
Str("MattermostUser", config.Reporter.Mattermost.User),
102103
),
103104
).
104-
Str("Delay", glb_arguments.Delay.String()).
105-
Str("Loglevel", glb_arguments.LogLevel).
106-
Str("ServerTag", glb_arguments.ServerTag).
107-
Str("Filter", strings.Join(glb_arguments.FilterStrings, " ")).
108-
Str("Exclude", strings.Join(glb_arguments.ExcludeStrings, " ")),
105+
Str("Delay", config.Options.Delay.String()).
106+
Str("Loglevel", config.Options.LogLevel).
107+
Str("ServerTag", config.Options.ServerTag).
108+
Str("Filter", strings.Join(config.Options.FilterStrings, " ")).
109+
Str("Exclude", strings.Join(config.Options.ExcludeStrings, " ")),
109110
).
110111
Dict("version", zerolog.Dict().
111112
Str("Version", version).
@@ -120,7 +121,7 @@ func logArguments() {
120121
func stringToUnix(str string) time.Time {
121122
i, err := strconv.ParseInt(str, 10, 64)
122123
if err != nil {
123-
logger.Fatal().Err(err).Msg("String to timestamp conversion failed")
124+
log.Fatal().Err(err).Msg("String to timestamp conversion failed")
124125
}
125126
tm := time.Unix(i, 0)
126127
return tm

‎src/types.go

+52
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
1+
package main
2+
3+
import "time"
4+
5+
type pushover struct {
6+
Enabled bool
7+
APIToken string `yaml:"api_token"`
8+
UserKey string `yaml:"user_key"`
9+
}
10+
type gotify struct {
11+
Enabled bool
12+
URL string `yaml:"url"`
13+
Token string `yaml:"token"`
14+
}
15+
type mail struct {
16+
Enabled bool
17+
From string `yaml:"from"`
18+
To string `yaml:"to"`
19+
User string `yaml:"user"`
20+
Password string `yaml:"password"`
21+
Port int `yaml:"port"`
22+
Host string `yaml:"host"`
23+
}
24+
type mattermost struct {
25+
Enabled bool
26+
URL string `yaml:"url"`
27+
Channel string `yaml:"channel"`
28+
User string `yaml:"user"`
29+
}
30+
31+
type reporter struct {
32+
Pushover pushover
33+
Gotify gotify
34+
Mail mail
35+
Mattermost mattermost
36+
}
37+
38+
type options struct {
39+
FilterStrings []string `yaml:"filter_strings,flow"`
40+
ExcludeStrings []string `yaml:"exclude_strings,flow"`
41+
LogLevel string `yaml:"log_level"`
42+
ServerTag string `yaml:"server_tag"`
43+
Delay time.Duration `yaml:"delay"`
44+
}
45+
46+
type Config struct {
47+
Reporter reporter
48+
Options options
49+
Reporters []string `yaml:"-"`
50+
Filter map[string][]string `yaml:"-"`
51+
Exclude map[string][]string `yaml:"-"`
52+
}

‎src/version.go

+15-2
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,22 @@
11
package main
22

3-
import "os"
3+
import (
4+
"os"
5+
6+
"github.com/rs/zerolog/log"
7+
)
8+
9+
// version information, are injected during build process
10+
var (
11+
version string = "n/a"
12+
commit string = "n/a"
13+
date string = "0"
14+
gitdate string = "0"
15+
branch string = "n/a"
16+
)
417

518
func printVersion() {
6-
logger.Info().
19+
log.Info().
720
Str("Version", version).
821
Str("Branch", branch).
922
Str("Commit", commit).

0 commit comments

Comments
 (0)
Please sign in to comment.