Skip to content

Commit

Permalink
feat: add more params to logger
Browse files Browse the repository at this point in the history
  • Loading branch information
davidramiro committed Feb 11, 2024
1 parent 1327858 commit b3d1395
Show file tree
Hide file tree
Showing 8 changed files with 110 additions and 56 deletions.
10 changes: 8 additions & 2 deletions internal/api/api.go
Original file line number Diff line number Diff line change
Expand Up @@ -35,16 +35,19 @@ func NewUpdateApi(dnsServiceFactory factory.ServiceFactory) *UpdateApi {
func (u *UpdateApi) HandleUpdateRequest(c echo.Context) error {
var request UpdateRequest

logger := log.With().Str("subdomains", request.Subdomains).Str("domain", request.Domain).Str("IP", request.IP).Logger()

err := c.Bind(&request)
if err != nil {
log.Error().Err(err).Msg(ErrCannotParseRequest.Error())
return c.String(http.StatusBadRequest, ErrCannotParseRequest.Error())
}

log.Info().Str("subdomains", request.Subdomains).Str("domain", request.Domain).Str("IP", request.IP).Msg("request received")
logger.Info().Msg("request received")

err = validateRequest(request.Domain, request.IP)
if err != nil {
logger.Error().Err(err).Msg(err.Error())
return c.String(400, err.Error())
}

Expand All @@ -53,13 +56,15 @@ func (u *UpdateApi) HandleUpdateRequest(c echo.Context) error {
successfulUpdates := 0

if len(subdomains) == 0 || subdomains[0] == "" {
logger.Error().Err(ErrMissingParameter).Msg(ErrMissingParameter.Error())
return c.String(http.StatusBadRequest, ErrMissingParameter.Error())
}

for i := range subdomains {

service, err := u.dnsServiceFactory.Find(services.Registrar(request.Registrar))
if err != nil {
logger.Err(err).Msg("getting registrar from factory failed")
return c.String(400, err.Error())
}

Expand All @@ -71,13 +76,14 @@ func (u *UpdateApi) HandleUpdateRequest(c echo.Context) error {

err = service.UpdateRecord(request)
if err != nil {
logger.Err(err).Msg("updating record failed")
return c.String(http.StatusInternalServerError, err.Error())
}

successfulUpdates++
}

log.Info().Int("updates", successfulUpdates).Str("subdomains", request.Subdomains).Str("domain", request.Domain).Msg("successfully created")
logger.Info().Int("updates", successfulUpdates).Msg("successfully created")

return c.String(http.StatusOK, fmt.Sprintf("created %d entries for subdomains %s on %s: %s", successfulUpdates, request.Subdomains, request.Domain, request.IP))

Expand Down
55 changes: 38 additions & 17 deletions services/cloudflare.go
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,9 @@ func NewCloudflareDnsUpdateService(client HTTPClient) (*CloudflareDnsUpdateServi
ttl := viper.GetInt("cloudflare.ttl")
apikey := viper.GetString("cloudflare.apiKey")
zoneId := viper.GetString("cloudflare.zoneId")

log.Info().Msg("initializing cloudflare service")

if len(baseUrl) == 0 || ttl == 0 || len(apikey) == 0 || len(zoneId) == 0 {
return nil, ErrMissingInfoForServiceInit
}
Expand Down Expand Up @@ -64,6 +67,9 @@ func (c *CloudflareDnsUpdateService) UpdateRecord(request *DynDnsRequest) error
endpoint := fmt.Sprintf("%s/zones/%s/dns_records", c.baseUrl,
c.zoneId)

logger := log.With().Str("func", "UpdateRecord").Str("registrar", "cloudflare").Str("endpoint", endpoint).Str("domain", request.Domain).Str("subdomain", request.Subdomain).Logger()
logger.Info().Msg("building update request")

req, err := http.NewRequest("GET", endpoint, nil)

var r CloudflareQueryResponse
Expand All @@ -73,14 +79,20 @@ func (c *CloudflareDnsUpdateService) UpdateRecord(request *DynDnsRequest) error

resp, err := c.client.Do(req)
if err != nil {
return errors.New("error getting cloudflare request")
logger.Error().Err(err).Msg(ErrBuildingRequest.Error())
return ErrBuildingRequest
}

b, _ := io.ReadAll(resp.Body)
err = json.Unmarshal(b, &r)

if resp.StatusCode != http.StatusOK || len(r.Errors) > 0 || err != nil {
log.Error().Msg("could not query record:" + string(b))
if err != nil {
logger.Error().Err(err).Msg(ErrParsingResponse.Error())
return err
}

if resp.StatusCode != http.StatusOK || len(r.Errors) > 0 {
logger.Error().Interface("response", b).Msg("could not query record")
return errors.New("could not query record: " + string(b))
}

Expand All @@ -95,8 +107,10 @@ func (c *CloudflareDnsUpdateService) UpdateRecord(request *DynDnsRequest) error
}

if len(id) == 0 {
logger.Info().Msg("entry not found, creating new")
return c.newRecord(request)
} else {
logger.Info().Msg("entry found, updating")
return c.editExistingRecord(request, id)
}
}
Expand All @@ -111,35 +125,40 @@ func (c *CloudflareDnsUpdateService) newRecord(request *DynDnsRequest) error {

endpoint := fmt.Sprintf("%s/zones/%s/dns_records", c.baseUrl,
c.zoneId)
log.Info().Str("subdomain", cloudflareRequest.Subdomain).Str("endpoint", endpoint).Str("IP", cloudflareRequest.IP).Msg("building update request")

logger := log.With().Str("func", "newRecord").Str("registrar", "cloudflare").Str("subdomain", cloudflareRequest.Subdomain).Str("endpoint", endpoint).Str("IP", cloudflareRequest.IP).Logger()
logger.Info().Msg("building new record request")

body, err := json.Marshal(cloudflareRequest)
if err != nil {
log.Error().Err(err).Msg("marshalling failed")
return errors.New("could not parse request")
logger.Error().Err(err).Msg(ErrBuildingRequest.Error())
return ErrBuildingRequest
}

req, err := http.NewRequest("POST", endpoint, bytes.NewBuffer(body))
if err != nil {
log.Error().Err(err).Msg("building request failed failed")
return errors.New("could not create request for cloudflare")
logger.Error().Err(err).Msg(ErrBuildingRequest.Error())
return ErrBuildingRequest
}

req.Header.Set("Content-Type", "application/json; charset=utf-8")
req.Header.Set("Authorization", fmt.Sprintf("Bearer %s", c.apiKey))

logger.Info().Msg("executing request")
resp, err := c.client.Do(req)
if err != nil {
log.Error().Err(err).Msg("executing request failed")
return errors.New("could not execute request")
logger.Error().Err(err).Msg(ErrExecutingRequest.Error())
return ErrExecutingRequest
}

if resp.StatusCode != 200 {
b, _ := io.ReadAll(resp.Body)
log.Error().Msg("gandi rejected request")
return fmt.Errorf("cloudflare rejected request: %s", string(b))
logger.Error().Bytes("response", b).Msg(ErrRegistrarRejectedRequest.Error())
return ErrRegistrarRejectedRequest
}

logger.Info().Msg("request for new record successful")

return nil
}

Expand All @@ -153,17 +172,19 @@ func (c *CloudflareDnsUpdateService) editExistingRecord(request *DynDnsRequest,

endpoint := fmt.Sprintf("%s/zones/%s/dns_records/%s", c.baseUrl,
c.zoneId, id)
log.Info().Str("subdomain", cloudflareRequest.Subdomain).Str("endpoint", endpoint).Str("IP", cloudflareRequest.IP).Msg("building update request")

logger := log.With().Str("func", "editExistingRecord").Str("registrar", "cloudflare").Str("subdomain", cloudflareRequest.Subdomain).Str("endpoint", endpoint).Str("IP", cloudflareRequest.IP).Logger()
logger.Info().Msg("building request to edit record")

body, err := json.Marshal(cloudflareRequest)
if err != nil {
log.Error().Err(err).Msg("marshalling failed")
logger.Error().Err(err).Msg("marshalling failed")
return errors.New("could not parse request")
}

req, err := http.NewRequest("PUT", endpoint, bytes.NewBuffer(body))
if err != nil {
log.Error().Err(err).Msg("building request failed failed")
logger.Error().Err(err).Msg("building request failed failed")
return errors.New("could not create request for cloudflare")
}

Expand All @@ -172,13 +193,13 @@ func (c *CloudflareDnsUpdateService) editExistingRecord(request *DynDnsRequest,

resp, err := c.client.Do(req)
if err != nil {
log.Error().Err(err).Msg("executing request failed")
logger.Error().Err(err).Msg("executing request failed")
return errors.New("could not execute request")
}

if resp.StatusCode != 200 {
b, _ := io.ReadAll(resp.Body)
log.Error().Msg("cloudflare rejected request")
logger.Error().Bytes("response", b).Msg("cloudflare rejected request")
return fmt.Errorf("cloudflare rejected request: %s", string(b))
}

Expand Down
4 changes: 2 additions & 2 deletions services/cloudflare_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -234,7 +234,7 @@ func TestCloudflareDnsUpdateService_UpdateRecord_NewRecord_ApiError(t *testing.T

err = registrar.UpdateRecord(dynReq)

assert.EqualError(t, err, "cloudflare rejected request: api error")
assert.EqualError(t, err, services.ErrRegistrarRejectedRequest.Error())
}

func TestCloudflareDnsUpdateService_UpdateRecord_ExistingRecord_ApiError(t *testing.T) {
Expand Down Expand Up @@ -363,5 +363,5 @@ func TestCloudflareDnsUpdateService_UpdateRecord_NewRecord_RequestError(t *testi

err = registrar.UpdateRecord(dynReq)

assert.EqualError(t, err, "could not execute request")
assert.EqualError(t, err, services.ErrExecutingRequest.Error())
}
4 changes: 4 additions & 0 deletions services/errors.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,4 +5,8 @@ import "errors"
var (
ErrMissingInfoForServiceInit = errors.New("cannot setup service, missing config param")
ErrRegistrarNotFound = errors.New("registrar not found")
ErrBuildingRequest = errors.New("error building request")
ErrParsingResponse = errors.New("error parsing api response")
ErrRegistrarRejectedRequest = errors.New("registrar rejected request")
ErrExecutingRequest = errors.New("error executing request")
)
25 changes: 15 additions & 10 deletions services/gandi.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@ package services
import (
"bytes"
"encoding/json"
"errors"
"fmt"
"github.com/rs/zerolog/log"
"github.com/spf13/viper"
Expand All @@ -21,6 +20,9 @@ func NewGandiDnsUpdateService(client HTTPClient) (*GandiDnsUpdateService, error)
baseUrl := viper.GetString("gandi.baseUrl")
ttl := viper.GetInt("gandi.ttl")
apikey := viper.GetString("gandi.apiKey")

log.Info().Msg("initializing gandi service")

if len(baseUrl) == 0 || ttl == 0 || len(apikey) == 0 {
return nil, ErrMissingInfoForServiceInit
}
Expand Down Expand Up @@ -63,35 +65,38 @@ func (g *GandiDnsUpdateService) UpdateRecord(request *DynDnsRequest) error {
endpoint := fmt.Sprintf("%s/domains/%s/records/%s/A", g.baseUrl,
request.Domain, gandiRequest.Subdomain)

log.Info().Str("subdomain", gandiRequest.Subdomain).Str("endpoint", endpoint).Str("IP", gandiRequest.IPValues[0]).Msg("building update request")
logger := log.With().Str("func", "UpdateRecord").Str("registrar", "gandi").Str("endpoint", endpoint).Str("domain", request.Domain).Str("subdomain", request.Subdomain).Logger()
logger.Info().Msg("building update request")

body, err := json.Marshal(gandiRequest)
if err != nil {
log.Error().Err(err).Msg("marshalling failed")
return errors.New("error")
logger.Error().Err(err).Msg(ErrBuildingRequest.Error())
return ErrBuildingRequest
}

req, err := http.NewRequest("PUT", endpoint, bytes.NewBuffer(body))
if err != nil {
log.Error().Err(err).Msg("building request failed failed")
return errors.New("could not create request for gandi")
logger.Error().Err(err).Msg(ErrBuildingRequest.Error())
return ErrBuildingRequest
}

req.Header.Set("Content-Type", "application/json; charset=utf-8")
req.Header.Set("Authorization", "Apikey "+g.apiKey)

resp, err := g.client.Do(req)
if err != nil {
log.Error().Err(err).Msg("executing request failed")
return errors.New("could execute request")
logger.Error().Err(err).Msg(ErrExecutingRequest.Error())
return ErrExecutingRequest
}

if resp.StatusCode != 201 {
b, _ := io.ReadAll(resp.Body)
log.Error().Msg("gandi rejected request")
return fmt.Errorf("gandi rejected request: %s", string(b))
logger.Error().Bytes("response", b).Msg(ErrRegistrarRejectedRequest.Error())
return ErrRegistrarRejectedRequest
}

logger.Info().Msg("update request successful")

return nil
}

Expand Down
2 changes: 1 addition & 1 deletion services/gandi_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -97,7 +97,7 @@ func TestGandiDnsUpdateService_UpdateRecord_ApiError(t *testing.T) {

err = registrar.UpdateRecord(req)

assert.EqualError(t, err, "gandi rejected request: {\"errors\":[{\"message\":\"error\"}],\"result\":null}")
assert.EqualError(t, err, services.ErrRegistrarRejectedRequest.Error())
}

func TestGandiDnsUpdateService_UpdateRecord_Success(t *testing.T) {
Expand Down
Loading

0 comments on commit b3d1395

Please sign in to comment.