Skip to content

Commit

Permalink
update metric agent and add logger
Browse files Browse the repository at this point in the history
  • Loading branch information
dieofcode committed Jan 15, 2024
1 parent 42d65da commit 16a353a
Show file tree
Hide file tree
Showing 4 changed files with 32 additions and 12 deletions.
10 changes: 5 additions & 5 deletions cmd/agent/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ func main() {
httpClient := &http.Client{
Timeout: time.Minute,
}

metricsAgent := agent.NewMetricsAgent(logger)
poolTicker := time.NewTicker(time.Duration(config.PollInterval) * time.Second)
reportTicker := time.NewTicker(time.Duration(config.ReportInterval) * time.Second)

Expand All @@ -40,15 +40,15 @@ loop:
select {
case <-reportTicker.C:
metrics = append(metrics, m.Metrics{MType: m.Counter, ID: m.PoolCount, Delta: &counter})
err := agent.SendMetric(ctx, httpClient, metrics, config.ServerAddress)
err := metricsAgent.SendMetric(ctx, httpClient, metrics, config.ServerAddress)
if err != nil {
logger.Fatal().Err(err).Msg("Send metrics error")
logger.Fatal().Err(err).Msg("SEND METRIC ERROR")
} else {
logger.Info().Interface("metrics", metrics).Msg("Metrics sent")
logger.Info().Interface("metrics", metrics).Msgf("METRICS SEND %d", len(metrics))
}
case <-poolTicker.C:
counter++
metrics = agent.CollectGaudeMetrics()
metrics = metricsAgent.CollectGaudeMetrics()
random := rand.Float64()
metrics = append(metrics, m.Metrics{MType: m.Gauge, ID: m.RandomValue, Value: &random})
logger.Info().Interface("metrics", metrics).Msg("Metrics collected")
Expand Down
26 changes: 20 additions & 6 deletions internal/agent/agent.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,18 +3,32 @@ package agent
import (
"context"
"fmt"
"log"
"net/http"
"reflect"
"runtime"
"sync"

m "github.com/DieOfCode/go-alert-service/internal/metrics"
"github.com/rs/zerolog"
)

// TODO replace with real metric type
type Agent interface {
CollectGaudeMetrics() []m.Metrics
SendMetric(ctx context.Context, client *http.Client, metrics []m.Metrics, address string) error
}

type MetricsAgent struct {
//TODO: replace to loger interface
logger zerolog.Logger
}

func NewMetricsAgent(logger zerolog.Logger) *MetricsAgent {
return &MetricsAgent{
logger: logger,
}
}

func CollectGaudeMetrics() []m.Metrics {
func (metricAgent *MetricsAgent) CollectGaudeMetrics() []m.Metrics {
var collectedMerics []m.Metrics
var stat runtime.MemStats

Expand Down Expand Up @@ -43,7 +57,7 @@ func CollectGaudeMetrics() []m.Metrics {
return collectedMerics
}

func SendMetric(ctx context.Context, client *http.Client, metrics []m.Metrics, address string) error {
func (metricAgent *MetricsAgent) SendMetric(ctx context.Context, client *http.Client, metrics []m.Metrics, address string) error {
wg := sync.WaitGroup{}

for _, element := range metrics {
Expand All @@ -53,13 +67,13 @@ func SendMetric(ctx context.Context, client *http.Client, metrics []m.Metrics, a
request := fmt.Sprintf("http://%s/update/%s/%s/%v", address, element.MType, element.ID, element.Value)
req, err := http.NewRequestWithContext(ctx, http.MethodPost, request, nil)
if err != nil {
log.Println(err)
metricAgent.logger.Err(err).Msgf("REQUEST CREATE ERROR")
return
}
req.Header.Set("Content-Type", "text/plain")
resp, err := client.Do(req)
if err != nil {
log.Println(err)
metricAgent.logger.Err(err).Msgf("UPDATE METRIC VALUE ERROR %s", element.ID)
return
}
resp.Body.Close()
Expand Down
3 changes: 2 additions & 1 deletion internal/handler/handler.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,8 @@ import (

type Handler struct {
repository s.Repository
logger zerolog.Logger
//TODO: replace to loger interface
logger zerolog.Logger
}

func NewHandler(repository s.Repository, logger zerolog.Logger) *Handler {
Expand Down
5 changes: 5 additions & 0 deletions internal/storage/storage.go
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,7 @@ func (storage *MemStorage) UpdateMetric(metricType string, metricName string, va
storage.metrics[key] = metrics.Metrics{Value: &newValue}
storage.logger.Info().Msgf("STORAGE GAUDE UPDATE: %s %s %s %v", metricType, metricName, key, newValue)
} else {
storage.logger.Error().Msgf("STORAGE GAUDE UPDATE ERROR: %s %s %s %v", metricType, metricName, key, newValue)
return fmt.Errorf("некорректное значение для типа counter: %v", value)

}
Expand All @@ -48,6 +49,8 @@ func (storage *MemStorage) UpdateMetric(metricType string, metricName string, va
existingValue := existingMetric.Delta
newValue, err := strconv.ParseInt(value, 10, 64)
if err != nil {
storage.logger.Error().Msgf("STORAGE COUNTER UPDATE ERROR: %s %s %s %v", metricType, metricName, key, newValue)

return fmt.Errorf("некорректное значение для типа counter: %v", value)

}
Expand All @@ -62,11 +65,13 @@ func (storage *MemStorage) UpdateMetric(metricType string, metricName string, va
if newValue, err := strconv.ParseInt(value, 10, 64); err == nil {
storage.metrics[key] = metrics.Metrics{Delta: &newValue}
} else {
storage.logger.Error().Msgf("STORAGE COUNTER UPDATE ERROR: %s %s %s %v", metricType, metricName, key, newValue)
return fmt.Errorf("некорректное значение для типа counter: %v", value)
}

}
default:
storage.logger.Error().Msgf("STORAGE COUNTER UPDATE ERROR: %s %s %s", metricType, metricName, key)
return fmt.Errorf("некорректный тип метрики: %s", metricType)
}

Expand Down

0 comments on commit 16a353a

Please sign in to comment.