Skip to content

Commit

Permalink
feat: finer log level (#206)
Browse files Browse the repository at this point in the history
* feat: finer log level

* fix: make dist

* fix: tests
  • Loading branch information
lucassabreu authored Jul 26, 2022
1 parent 9bbc984 commit 991e568
Show file tree
Hide file tree
Showing 12 changed files with 125 additions and 17 deletions.
3 changes: 3 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -22,11 +22,14 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0

- `api.Client` changed into a interface to easy testing
- user reports now show the user timezone
- flag `debug` dropped in favor of `log-level` to allow a finer control of the output for reporting
bugs.

### Fixed

- `Client.WorkspaceUsers` was not paginating over the results, this created bugs on `config init`
and `user list`
- `make dist` was building all system to the same file

## [v0.38.1] - 2022-07-05

Expand Down
15 changes: 11 additions & 4 deletions api/client.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,12 @@ import (

// Client will help to access Clockify API
type Client interface {
// SetDebugLogger when set will output the responses of requests to the
// logger
SetDebugLogger(logger Logger) Client
// SetInfoLogger when set will output which requests and params are used to
// the logger
SetInfoLogger(logger Logger) Client

GetWorkspace(GetWorkspace) (dto.Workspace, error)
GetWorkspaces(GetWorkspaces) ([]dto.Workspace, error)
Expand Down Expand Up @@ -61,6 +66,7 @@ type client struct {
baseURL *url.URL
http.Client
debugLogger Logger
infoLogger Logger
}

// baseURL is the Clockify API base URL
Expand Down Expand Up @@ -307,7 +313,7 @@ type LogParam struct {

// Log list time entries from a date
func (c *client) Log(p LogParam) ([]dto.TimeEntry, error) {
c.debugf("Log - Date Param: %s", p.Date)
c.infof("Log - Date Param: %s", p.Date)

d := p.Date.Round(time.Hour)
d = d.Add(time.Hour * time.Duration(d.Hour()) * -1)
Expand All @@ -334,7 +340,7 @@ type LogRangeParam struct {

// LogRange list time entries by date range
func (c *client) LogRange(p LogRangeParam) ([]dto.TimeEntry, error) {
c.debugf("LogRange - First Date Param: %s | Last Date Param: %s", p.FirstDate, p.LastDate)
c.infof("LogRange - First Date Param: %s | Last Date Param: %s", p.FirstDate, p.LastDate)

return c.GetUsersHydratedTimeEntries(GetUserTimeEntriesParam{
Workspace: p.Workspace,
Expand Down Expand Up @@ -438,8 +444,9 @@ func (c *client) getUserTimeEntriesImpl(
}
}

c.debugf(
"GetUserTimeEntries - Workspace: %s | User: %s | In Progress: %s | Description: %s | Project: %s",
c.infof(
"GetUserTimeEntries - Workspace: %s | User: %s | In Progress: %s "+
"| Description: %s | Project: %s",
p.Workspace,
p.UserID,
inProgressFilter,
Expand Down
13 changes: 10 additions & 3 deletions api/httpClient.go
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,7 @@ func (c *client) NewRequest(method, uri string, body interface{}) (*http.Request
if err != nil {
return nil, err
}
c.debugf("request body: %s", buf.(*bytes.Buffer))
c.infof("request body: %s", buf.(*bytes.Buffer))
}

req, err := http.NewRequest(method, u.String(), buf)
Expand All @@ -72,7 +72,8 @@ func (c *client) NewRequest(method, uri string, body interface{}) (*http.Request
}

// Do executes a http.Request inside the Clockify's Client
func (c *client) Do(req *http.Request, v interface{}, name string) (*http.Response, error) {
func (c *client) Do(
req *http.Request, v interface{}, name string) (*http.Response, error) {
r, err := c.Client.Do(req)
if err != nil {
return r, err
Expand All @@ -86,7 +87,13 @@ func (c *client) Do(req *http.Request, v interface{}, name string) (*http.Respon
return nil, errors.WithStack(err)
}

c.debugf("name: %s, method: %s, url: %s, status: %d, response: \"%s\"", name, req.Method, req.URL.String(), r.StatusCode, buf)
if c.debugLogger != nil {
c.debugf("name: %s, method: %s, url: %s, status: %d, response: \"%s\"",
name, req.Method, req.URL.String(), r.StatusCode, buf)
} else {
c.infof("name: %s, method: %s, url: %s, status: %d",
name, req.Method, req.URL.String(), r.StatusCode)
}

decoder := json.NewDecoder(buf)

Expand Down
14 changes: 14 additions & 0 deletions api/logger.go
Original file line number Diff line number Diff line change
Expand Up @@ -20,3 +20,17 @@ func (c *client) debugf(format string, v ...interface{}) {

c.debugLogger.Printf(format, v...)
}

// SetInfoLogger info logger
func (c *client) SetInfoLogger(logger Logger) Client {
c.infoLogger = logger
return c
}

func (c *client) infof(format string, v ...interface{}) {
if c.infoLogger == nil {
return
}

c.infoLogger.Printf(format, v...)
}
3 changes: 2 additions & 1 deletion cmd/clockify-cli/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -105,7 +105,8 @@ func bindViper(rootCmd *cobra.Command) error {
return err
}

if err = bind(l("debug"), cmdutil.CONF_DEBUG, "DEBUG"); err != nil {
err = bind(l("log-level"), cmdutil.CONF_LOG_LEVEL, "LOG_LEVEL")
if err != nil {
return err
}

Expand Down
16 changes: 16 additions & 0 deletions internal/mocks/mock_Client.go

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

14 changes: 14 additions & 0 deletions internal/mocks/mock_Config.go

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

3 changes: 2 additions & 1 deletion pkg/cmd/config/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,8 @@ var validParameters = cmdcompl.ValidArgsMap{
"for the description autocomplete",
cmdutil.CONF_SHOW_TOTAL_DURATION: "adds a totals line on time entry " +
"reports with the sum of the time entries duration",
cmdutil.CONF_DEBUG: "if extra logs should be shown",
cmdutil.CONF_LOG_LEVEL: "how much logs should be shown values: " +
"none , error , info and debug",
}

// NewCmdConfig represents the config command
Expand Down
11 changes: 9 additions & 2 deletions pkg/cmd/root.go
Original file line number Diff line number Diff line change
Expand Up @@ -39,15 +39,22 @@ func NewCmdRoot(f cmdutil.Factory) *cobra.Command {
_ = cmdcompl.AddSuggestionsToFlag(cmd, "user-id",
cmdcomplutil.NewUserAutoComplete(f))

cmd.PersistentFlags().Bool("debug", false, "show debug log")

cmd.PersistentFlags().BoolP("interactive", "i", false,
"will prompt you to confirm/complement commands input before "+
"executing the action ")

cmd.PersistentFlags().BoolP("allow-name-for-id", "", false,
"allow use of project/client/tag's name when id is asked")

cmd.PersistentFlags().String(
"log-level", cmdutil.LOG_LEVEL_NONE, "set log level")
_ = cmdcompl.AddFixedSuggestionsToFlag(cmd, "log-level",
cmdcompl.ValidArgsSlide{
cmdutil.LOG_LEVEL_NONE,
cmdutil.LOG_LEVEL_DEBUG,
cmdutil.LOG_LEVEL_INFO,
})

_ = cmd.MarkFlagRequired("token")

cmd.AddCommand(version.NewCmdVersion(f))
Expand Down
4 changes: 4 additions & 0 deletions pkg/cmdcompl/flags.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,10 @@ import (
// AddFixedSuggestionsToFlag add fixed suggestions to a flag
func AddFixedSuggestionsToFlag(cmd *cobra.Command, flagName string, va ValidArgs) error {
f := cmd.Flags().Lookup(flagName)
if f == nil {
f = cmd.PersistentFlags().Lookup(flagName)
}

f.Usage = va.IntoUse() + " " + f.Usage
return cmd.RegisterFlagCompletionFunc(
f.Name,
Expand Down
23 changes: 21 additions & 2 deletions pkg/cmdutil/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,13 @@ const (
CONF_DESCR_AUTOCOMP = "description-autocomplete"
CONF_DESCR_AUTOCOMP_DAYS = "description-autocomplete-days"
CONF_SHOW_TOTAL_DURATION = "show-total-duration"
CONF_DEBUG = "debug"
CONF_LOG_LEVEL = "log-level"
)

const (
LOG_LEVEL_NONE = "none"
LOG_LEVEL_DEBUG = "debug"
LOG_LEVEL_INFO = "info"
)

// Config manages configs and parameters used locally by the CLI
Expand All @@ -47,11 +53,24 @@ type Config interface {
Get(string) interface{}
All() map[string]interface{}

LogLevel() string

Save() error
}

type config struct{}

func (c *config) LogLevel() string {
l := c.GetString(CONF_LOG_LEVEL)
switch l {
case LOG_LEVEL_INFO, LOG_LEVEL_DEBUG:
return l
default:
return LOG_LEVEL_NONE
}

}

func (*config) GetBool(param string) bool {
return viper.GetBool(param)
}
Expand Down Expand Up @@ -85,7 +104,7 @@ func (*config) SetStringSlice(p string, ss []string) {
}

func (c *config) IsDebuging() bool {
return c.GetBool(CONF_DEBUG)
return c.LogLevel() == LOG_LEVEL_DEBUG
}

func (c *config) GetWorkWeekdays() []string {
Expand Down
23 changes: 19 additions & 4 deletions pkg/cmdutil/factory.go
Original file line number Diff line number Diff line change
Expand Up @@ -164,12 +164,27 @@ func clientFunc(f Factory) func() (api.Client, error) {
}

c, err = api.NewClient(f.Config().GetString(CONF_TOKEN))
if f.Config().IsDebuging() {
c.SetDebugLogger(
log.New(os.Stdout, "DEBUG ", log.LstdFlags),
)
if err != nil {
return c, err
}

ll := f.Config().LogLevel()
if ll == LOG_LEVEL_NONE {
return c, err
}

c.SetInfoLogger(
log.New(os.Stdout, "INFO ", log.LstdFlags),
)

if ll == LOG_LEVEL_INFO {
return c, err
}

c.SetDebugLogger(
log.New(os.Stdout, "DEBUG ", log.LstdFlags),
)

return c, err
}
}

0 comments on commit 991e568

Please sign in to comment.