Skip to content

Commit

Permalink
fix: add logging interface for abstracting logging
Browse files Browse the repository at this point in the history
  • Loading branch information
thejurysays committed Feb 14, 2024
1 parent c600323 commit 323662f
Show file tree
Hide file tree
Showing 8 changed files with 188 additions and 65 deletions.
48 changes: 23 additions & 25 deletions api/authentication/authetication.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,10 +7,9 @@ import (
"encoding/json"
"fmt"
"go-client-library-passwordsafe/api/entities"
"go-client-library-passwordsafe/api/utils"
"go-client-library-passwordsafe/api/logging"
"io"

"log"
"net/http"
"net/url"
"time"
Expand All @@ -19,17 +18,17 @@ import (
)

type AuthenticationObj struct {
ApiUrl string
clientId string
clientSecret string
httpClient *http.Client
ExponentialBackOff *backoff.ExponentialBackOff
signApinResponse entities.SignApinResponse
autenticationLogger log.Logger
ApiUrl string
clientId string
clientSecret string
httpClient *http.Client
ExponentialBackOff *backoff.ExponentialBackOff
signApinResponse entities.SignApinResponse
log logging.Logger
}

// Authenticate in PS API
func Authenticate(httpClient *http.Client, endpointUrl string, clientId string, clientSecret string, logger *log.Logger, maxElapsedTime int) (*AuthenticationObj, error) {
func Authenticate(httpClient *http.Client, endpointUrl string, clientId string, clientSecret string, logger logging.Logger, maxElapsedTime int) (*AuthenticationObj, error) {

backoffDefinition := backoff.NewExponentialBackOff()
backoffDefinition.InitialInterval = 1 * time.Second
Expand All @@ -40,12 +39,12 @@ func Authenticate(httpClient *http.Client, endpointUrl string, clientId string,
var client = httpClient

authenticationObj := &AuthenticationObj{
ApiUrl: endpointUrl,
httpClient: client,
clientId: clientId,
clientSecret: clientSecret,
ExponentialBackOff: backoffDefinition,
autenticationLogger: *logger,
ApiUrl: endpointUrl,
httpClient: client,
clientId: clientId,
clientSecret: clientSecret,
ExponentialBackOff: backoffDefinition,
log: logger,
}

return authenticationObj, nil
Expand Down Expand Up @@ -104,7 +103,7 @@ func (c *AuthenticationObj) GetToken(endpointUrl string, clientId string, client

err = json.Unmarshal([]byte(responseString), &data)
if err != nil {
utils.Logging("ERROR", err.Error(), c.autenticationLogger)
c.log.Error(err.Error())
return "", err
}

Expand Down Expand Up @@ -150,7 +149,7 @@ func (c *AuthenticationObj) SignAppin(endpointUrl string, accessToken string) (e
err = json.Unmarshal(bodyBytes, &userObject)

if err != nil {
utils.Logging("ERROR", err.Error(), c.autenticationLogger)
c.log.Error(err.Error())
return entities.SignApinResponse{}, err
}

Expand All @@ -160,8 +159,7 @@ func (c *AuthenticationObj) SignAppin(endpointUrl string, accessToken string) (e
// SignOut signs out Secret Safe API.
// Warn: should only be called one time for all data sources.
func (c *AuthenticationObj) SignOut(url string) error {

utils.Logging("DEBUG", url, c.autenticationLogger)
c.log.Debug(url)

var technicalError error
var businessError error
Expand All @@ -172,7 +170,7 @@ func (c *AuthenticationObj) SignOut(url string) error {
}, c.ExponentialBackOff)

if businessError != nil {
utils.Logging("ERROR", businessError.Error(), c.autenticationLogger)
c.log.Error(businessError.Error())
return businessError
}

Expand All @@ -184,12 +182,12 @@ func (c *AuthenticationObj) CallSecretSafeAPI(url string, httpMethod string, bod
response, technicalError, businessError, scode := c.HttpRequest(url, httpMethod, body, accesToken)
if technicalError != nil {
messageLog := fmt.Sprintf("Error in %v %v \n", method, technicalError)
utils.Logging("ERROR", messageLog, c.autenticationLogger)
c.log.Error(messageLog)
}

if businessError != nil {
messageLog := fmt.Sprintf("Error in %v: %v \n", method, businessError)
utils.Logging("ERROR", messageLog, c.autenticationLogger)
c.log.Error(messageLog)
}
return response, technicalError, businessError, scode
}
Expand All @@ -211,13 +209,13 @@ func (c *AuthenticationObj) HttpRequest(url string, method string, body bytes.Bu

resp, err := c.httpClient.Do(req)
if err != nil {
utils.Logging("ERROR", err.Error(), c.autenticationLogger)
c.log.Error(err.Error())
return nil, err, nil, 0
}

if resp.StatusCode >= http.StatusInternalServerError || resp.StatusCode == http.StatusRequestTimeout {
err = fmt.Errorf("Error %v: StatusCode: %v, %v, %v", method, scode, err, body)
utils.Logging("ERROR", err.Error(), c.autenticationLogger)
c.log.Error(err.Error())
return nil, err, nil, resp.StatusCode
}

Expand Down
93 changes: 93 additions & 0 deletions api/logging/logging.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,93 @@
package logging

import (
"fmt"
"log"

"github.com/go-logr/logr"
"go.uber.org/zap"
)

// Logger is an interface that defines the logging methods
type Logger interface {
Info(msg string)
Error(msg string)
Debug(msg string)
}

// ZapLogger is a struct that implements the Logger interface using zap
type ZapLogger struct {
logger *zap.Logger
}

// Info logs a message at info level
func (z *ZapLogger) Info(msg string) {
z.logger.Info(msg)
}

// Error logs a message at error level
func (z *ZapLogger) Error(msg string) {
z.logger.Error(msg)
}

// Error logs a message at error level
func (z *ZapLogger) Debug(msg string) {
z.logger.Debug(msg)
}

// logr.logger
type LogrLogger struct {
logger *logr.Logger
}

// Info logs a message at info level
func (r *LogrLogger) Info(msg string) {
r.logger.Info(msg)
}

// Error logs a message at error level
func (r *LogrLogger) Error(msg string) {
r.logger.Error(fmt.Errorf("an error"), msg)
}

func (r *LogrLogger) Debug(msg string) {
r.logger.Info(msg)
}

// log.logger
type LogLogger struct {
logger *log.Logger
}

// Info logs a message at info level
func (l *LogLogger) Info(msg string) {
prefix := fmt.Sprintf("%v :", "Info")
l.logger.SetPrefix(prefix)
l.logger.Println(msg)
}

// Error logs a message at error level
func (l *LogLogger) Error(msg string) {
prefix := fmt.Sprintf("%v :", "Error")
l.logger.SetPrefix(prefix)
l.logger.Println(msg)
}

func (l *LogLogger) Debug(msg string) {
prefix := fmt.Sprintf("%v :", "Debug")
l.logger.SetPrefix(prefix)
l.logger.Println(msg)
}

// NewZapLogger creates a new ZapLogger with the given zap.Logger
func NewZapLogger(logger *zap.Logger) *ZapLogger {
return &ZapLogger{logger: logger}
}

func NewLogrLogger(logger *logr.Logger) *LogrLogger {
return &LogrLogger{logger: logger}
}

func NewLogLogger(logger *log.Logger) *LogLogger {
return &LogLogger{logger: logger}
}
38 changes: 23 additions & 15 deletions api/managed_account/managed_account.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,22 +10,21 @@ import (
"fmt"
"go-client-library-passwordsafe/api/authentication"
"go-client-library-passwordsafe/api/entities"
"go-client-library-passwordsafe/api/utils"
"go-client-library-passwordsafe/api/logging"
"io"
"log"
"strconv"
"strings"

backoff "github.com/cenkalti/backoff/v4"
)

type ManagedAccountstObj struct {
managedAccocuntsLogger log.Logger
managedAccocuntsLogger logging.Logger
authenticationObj authentication.AuthenticationObj
}

// NewManagedAccountObj creates managed account obj
func NewManagedAccountObj(authentication authentication.AuthenticationObj, logger log.Logger) (*ManagedAccountstObj, error) {
func NewManagedAccountObj(authentication authentication.AuthenticationObj, logger logging.Logger) (*ManagedAccountstObj, error) {
managedAccounObj := &ManagedAccountstObj{
managedAccocuntsLogger: logger,
authenticationObj: authentication,
Expand Down Expand Up @@ -74,34 +73,39 @@ func (managedAccounObj *ManagedAccountstObj) ManageAccountFlow(secretsToRetrieve

if systemName == "" {
err = errors.New("Please use a valid system_name value")
utils.Logging("ERROR", err.Error(), managedAccounObj.managedAccocuntsLogger)
managedAccounObj.managedAccocuntsLogger.Error(err.Error())
//utils.Logging("ERROR", err.Error(), managedAccounObj.managedAccocuntsLogger)
return nil, err
}

if accountName == "" {
err = errors.New("Please use a valid system_name value")
utils.Logging("ERROR", err.Error(), managedAccounObj.managedAccocuntsLogger)
managedAccounObj.managedAccocuntsLogger.Error(err.Error())
//utils.Logging("ERROR", err.Error(), managedAccounObj.managedAccocuntsLogger)
return nil, err
}

ManagedAccountGetUrl := managedAccounObj.RequestPath(paths["ManagedAccountGetPath"])
managedAccount, err := managedAccounObj.ManagedAccountGet(systemName, accountName, ManagedAccountGetUrl)
if err != nil {
utils.Logging("ERROR", err.Error(), managedAccounObj.managedAccocuntsLogger)
managedAccounObj.managedAccocuntsLogger.Error(err.Error())
//utils.Logging("ERROR", err.Error(), managedAccounObj.managedAccocuntsLogger)
return nil, err
}

ManagedAccountCreateRequestUrl := managedAccounObj.RequestPath(paths["ManagedAccountCreateRequestPath"])
requestId, err := managedAccounObj.ManagedAccountCreateRequest(managedAccount.SystemId, managedAccount.AccountId, ManagedAccountCreateRequestUrl)
if err != nil {
utils.Logging("ERROR", err.Error(), managedAccounObj.managedAccocuntsLogger)
managedAccounObj.managedAccocuntsLogger.Error(err.Error())
//utils.Logging("ERROR", err.Error(), managedAccounObj.managedAccocuntsLogger)
return nil, err
}

CredentialByRequestIdUrl := managedAccounObj.RequestPath(fmt.Sprintf(paths["CredentialByRequestIdPath"], requestId))
secret, err := managedAccounObj.CredentialByRequestId(requestId, CredentialByRequestIdUrl)
if err != nil {
utils.Logging("ERROR", err.Error(), managedAccounObj.managedAccocuntsLogger)
managedAccounObj.managedAccocuntsLogger.Error(err.Error())
//utils.Logging("ERROR", err.Error(), managedAccounObj.managedAccocuntsLogger)
return nil, err
}

Expand All @@ -110,7 +114,8 @@ func (managedAccounObj *ManagedAccountstObj) ManageAccountFlow(secretsToRetrieve
_, err = managedAccounObj.ManagedAccountRequestCheckIn(requestId, ManagedAccountRequestCheckInUrl)

if err != nil {
utils.Logging("ERROR", err.Error(), managedAccounObj.managedAccocuntsLogger)
managedAccounObj.managedAccocuntsLogger.Error(err.Error())
//utils.Logging("ERROR", err.Error(), managedAccounObj.managedAccocuntsLogger)
return nil, err
}

Expand All @@ -123,7 +128,8 @@ func (managedAccounObj *ManagedAccountstObj) ManageAccountFlow(secretsToRetrieve

func (managedAccounObj *ManagedAccountstObj) ManagedAccountGet(systemName string, accountName string, url string) (entities.ManagedAccount, error) {
messageLog := fmt.Sprintf("%v %v", "GET", url)
utils.Logging("DEBUG", messageLog, managedAccounObj.managedAccocuntsLogger)
managedAccounObj.managedAccocuntsLogger.Debug(messageLog)
//utils.Logging("DEBUG", messageLog, managedAccounObj.managedAccocuntsLogger)

var body io.ReadCloser
var technicalError error
Expand Down Expand Up @@ -162,7 +168,8 @@ func (managedAccounObj *ManagedAccountstObj) ManagedAccountGet(systemName string
// ManagedAccountCreateRequest calls Secret Safe API Requests enpoint and returns a request Id as string.
func (managedAccounObj *ManagedAccountstObj) ManagedAccountCreateRequest(systemName int, accountName int, url string) (string, error) {
messageLog := fmt.Sprintf("%v %v", "POST", url)
utils.Logging("DEBUG", messageLog, managedAccounObj.managedAccocuntsLogger)
managedAccounObj.managedAccocuntsLogger.Debug(messageLog)
//utils.Logging("DEBUG", messageLog, managedAccounObj.managedAccocuntsLogger)

data := fmt.Sprintf(`{"SystemID":%v, "AccountID":%v, "DurationMinutes":5, "Reason":"Tesr", "ConflictOption": "reuse"}`, systemName, accountName)
b := bytes.NewBufferString(data)
Expand Down Expand Up @@ -200,8 +207,8 @@ func (managedAccounObj *ManagedAccountstObj) ManagedAccountCreateRequest(systemN
// enpoint and returns secret value by request Id.
func (managedAccounObj *ManagedAccountstObj) CredentialByRequestId(requestId string, url string) (string, error) {
messageLog := fmt.Sprintf("%v %v", "GET", url)

utils.Logging("DEBUG", messageLog, managedAccounObj.managedAccocuntsLogger)
managedAccounObj.managedAccocuntsLogger.Debug(messageLog)
//utils.Logging("DEBUG", messageLog, managedAccounObj.managedAccocuntsLogger)

var body io.ReadCloser
var technicalError error
Expand Down Expand Up @@ -235,7 +242,8 @@ func (managedAccounObj *ManagedAccountstObj) CredentialByRequestId(requestId str
// ManagedAccountRequestCheckIn calls Secret Safe API "Requests/<request_id>/checkin enpoint.
func (managedAccounObj *ManagedAccountstObj) ManagedAccountRequestCheckIn(requestId string, url string) (string, error) {
messageLog := fmt.Sprintf("%v %v", "PUT", url)
utils.Logging("DEBUG", messageLog, managedAccounObj.managedAccocuntsLogger)
managedAccounObj.managedAccocuntsLogger.Debug(messageLog)
//utils.Logging("DEBUG", messageLog, managedAccounObj.managedAccocuntsLogger)

data := "{}"
b := bytes.NewBufferString(data)
Expand Down
15 changes: 7 additions & 8 deletions api/secrets/secrets.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,24 +9,23 @@ import (
"fmt"
"go-client-library-passwordsafe/api/authentication"
"go-client-library-passwordsafe/api/entities"
"go-client-library-passwordsafe/api/utils"
"go-client-library-passwordsafe/api/logging"
"io"
"log"
"net/url"
"strings"

backoff "github.com/cenkalti/backoff/v4"
)

type SecretObj struct {
secretLogger log.Logger
log logging.Logger
authenticationObj authentication.AuthenticationObj
}

// NewSecretObj creates secret obj
func NewSecretObj(authentication authentication.AuthenticationObj, logger log.Logger) (*SecretObj, error) {
func NewSecretObj(authentication authentication.AuthenticationObj, logger logging.Logger) (*SecretObj, error) {
secretObj := &SecretObj{
secretLogger: logger,
log: logger,
authenticationObj: authentication,
}
return secretObj, nil
Expand Down Expand Up @@ -66,7 +65,7 @@ func (secretObj *SecretObj) GetSecretFlow(secretsToRetrieve []string, separator
if strings.ToUpper(secret.SecretType) == "FILE" {
fileSecretContent, err := secretObj.SecretGetFileSecret(secret.Id, "secrets-safe/secrets/")
if err != nil {
utils.Logging("ERROR", err.Error(), secretObj.secretLogger)
secretObj.log.Error(err.Error())
return nil, err
}

Expand All @@ -82,7 +81,7 @@ func (secretObj *SecretObj) GetSecretFlow(secretsToRetrieve []string, separator
// SecretGetSecretByPath returns secret object for a specific path, title.
func (secretObj *SecretObj) SecretGetSecretByPath(secretPath string, secretTitle string, separator string, endpointPath string) (entities.Secret, error) {
messageLog := fmt.Sprintf("%v %v", "GET", endpointPath)
utils.Logging("DEBUG", messageLog, secretObj.secretLogger)
secretObj.log.Debug(messageLog)

var body io.ReadCloser
var technicalError error
Expand Down Expand Up @@ -134,7 +133,7 @@ func (secretObj *SecretObj) SecretGetSecretByPath(secretPath string, secretTitle
// and returns file secret value.
func (secretObj *SecretObj) SecretGetFileSecret(secretId string, endpointPath string) (string, error) {
messageLog := fmt.Sprintf("%v %v", "GET", endpointPath)
utils.Logging("DEBUG", messageLog, secretObj.secretLogger)
secretObj.log.Debug(messageLog)

var body io.ReadCloser
var technicalError error
Expand Down
Loading

0 comments on commit 323662f

Please sign in to comment.