Skip to content

Commit

Permalink
(log) log via pm2
Browse files Browse the repository at this point in the history
  • Loading branch information
kevincobain2000 committed Dec 23, 2023
1 parent 820e6f2 commit 01600e0
Show file tree
Hide file tree
Showing 10 changed files with 77 additions and 41 deletions.
6 changes: 3 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
<p align="center">
<a href="https://github.com/kevincobain2000/instachart">
<img alt="c2p" src="https://imgur.com/fNESd6h.png" width="620">
<img alt="c2p" src="https://imgur.com/HC5FB7O.png" width="620">
</a>
</p>
<p align="center">
Expand Down Expand Up @@ -68,7 +68,7 @@ https://instachart.coveritup.app/line?title=Single+Line+Series&x_label=dates&y_l
<summary><b>Query URL</b></summary>

```sh
https://instachart.coveritup.app/line??title=Multi+Line+Series&x_label=dates&y_label=amount&data={
https://instachart.coveritup.app/line?title=Multi+Line+Series&x_label=dates&y_label=amount&data={
"x": [["2022-12-23","2022-12-24","2023-12-25"], ["2022-12-23","2022-12-28","2023-12-30"]],
"y": [[1,2,3], [1,5,10]],
"names": ["Series A", "Series B"]
Expand All @@ -87,7 +87,7 @@ https://instachart.coveritup.app/line??title=Multi+Line+Series&x_label=dates&y_l
<summary><b>Query URL</b></summary>

```sh
https://instachart.coveritup.app/line??title=Continuous+Series&x_label=No+of+people&y_label=amount&data={
https://instachart.coveritup.app/line?title=Continuous+Series&x_label=No+of+people&y_label=amount&data={
"x": [["10","20","30"], ["10","20","30"], ["10","20","30"]],
"y": [[1,2,3], [10,20,30], [6,3,9]],
"names": ["Series A", "Series B", "Series C"]
Expand Down
1 change: 1 addition & 0 deletions deploy.sh
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
#! /bin/bash

go build main.go
pm2 delete 3001
pm2 start --name 3001 "./main"
2 changes: 1 addition & 1 deletion go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -3,13 +3,13 @@ module github.com/kevincobain2000/instachart
go 1.21.3

require (
github.com/araddon/dateparse v0.0.0-20210429162001-6b43995a97de
github.com/fvbock/endless v0.0.0-20170109170031-447134032cb6
github.com/go-playground/validator v9.31.0+incompatible
github.com/labstack/echo/v4 v4.11.3
github.com/sirupsen/logrus v1.9.3
github.com/stretchr/testify v1.8.4
github.com/wcharczuk/go-chart/v2 v2.1.1
gopkg.in/natefinch/lumberjack.v2 v2.2.1
)

require (
Expand Down
7 changes: 5 additions & 2 deletions go.sum
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
github.com/araddon/dateparse v0.0.0-20210429162001-6b43995a97de h1:FxWPpzIjnTlhPwqqXc4/vE0f7GvRjuAsbW+HOIe8KnA=
github.com/araddon/dateparse v0.0.0-20210429162001-6b43995a97de/go.mod h1:DCaWoUhZrYW9p1lxo/cm8EmUOOzAPSEZNGF2DK1dJgw=
github.com/blend/go-sdk v1.20220411.3 h1:GFV4/FQX5UzXLPwWV03gP811pj7B8J2sbuq+GJQofXc=
github.com/blend/go-sdk v1.20220411.3/go.mod h1:7lnH8fTi6U4i1fArEXRyOIY2E1X4MALg09qsQqY1+ak=
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
Expand Down Expand Up @@ -28,8 +30,11 @@ github.com/mattn/go-isatty v0.0.14/go.mod h1:7GGIvUiUoEMVVmxf/4nioHXj79iQHKdU27k
github.com/mattn/go-isatty v0.0.16/go.mod h1:kYGgaQfpe5nmfYZH+SKPsOc2e4SrIfOl2e/yFXSvRLM=
github.com/mattn/go-isatty v0.0.19 h1:JITubQf0MOLdlGRuRq+jtsDlekdYPia9ZFsB8h/APPA=
github.com/mattn/go-isatty v0.0.19/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y=
github.com/mattn/go-runewidth v0.0.10/go.mod h1:RAqKPSqVFrSLVXbA8x7dzmKdmGzieGRCM46jaSJTDAk=
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/rivo/uniseg v0.1.0/go.mod h1:J6wj4VEh+S6ZtnVlnTBMWIodfgj8LQOQFoIToxlJtxc=
github.com/scylladb/termtables v0.0.0-20191203121021-c4c0b6d42ff4/go.mod h1:C1a7PQSMz9NShzorzCiG2fk9+xuCgLkPeCvMHYR2OWg=
github.com/sirupsen/logrus v1.9.3 h1:dueUQJ1C2q9oE3F7wvmSGAaVtTmUizReu6fjN8uqzbQ=
github.com/sirupsen/logrus v1.9.3/go.mod h1:naHLuLoDiP4jHNo9R0sCBMtWGeIprob74mVsIT4qYEQ=
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
Expand Down Expand Up @@ -101,8 +106,6 @@ gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/go-playground/assert.v1 v1.2.1 h1:xoYuJVE7KT85PYWrN730RguIQO0ePzVRfFMXadIrXTM=
gopkg.in/go-playground/assert.v1 v1.2.1/go.mod h1:9RXL0bg/zibRAgZUYszZSwO/z8Y/a8bDuhia5mkpMnE=
gopkg.in/natefinch/lumberjack.v2 v2.2.1 h1:bBRl1b0OH9s/DuPhuXpNl+VtCaJXFZ5/uEFST95x9zc=
gopkg.in/natefinch/lumberjack.v2 v2.2.1/go.mod h1:YD8tP3GAjkrDg1eZH7EGmyESg/lsYskCTPBJVb9jqSc=
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
gopkg.in/yaml.v3 v3.0.0-20210107192922-496545a6307b/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
Expand Down
53 changes: 53 additions & 0 deletions pkg/bar_chart_handler_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
package pkg

import (
"net/http"
"net/http/httptest"
"net/url"
"testing"

"github.com/labstack/echo/v4"
"github.com/stretchr/testify/assert"
)

func TestGetBarChart(t *testing.T) {
e := echo.New()

e.GET("/bar", func(c echo.Context) error {
img, err := NewBarChartHandler().Get(c)
if err != nil {
return err
}
return c.Blob(http.StatusOK, "image/png", img)
})

// Start a test HTTP server
server := httptest.NewServer(e)
defer server.Close()

type TestCase struct {
QueryParams string
ExpectedStatus int
}
testCases := []TestCase{
{
QueryParams: `{"x": ["2022-12-23","2022-12-28","2023-12-30"], "y": [1,2,3]}`,
ExpectedStatus: http.StatusOK,
},
{
QueryParams: `{"x": ["2022-12-23,"2022-12-28","2023-12-30"], "y": [1,2,3]}`,
ExpectedStatus: http.StatusInternalServerError,
},
{
QueryParams: `{"x": [["2022-12-23","2022-12-28","2023-12-30"]], "y": [1,2,3]}`,
ExpectedStatus: http.StatusInternalServerError,
},
}

for _, tc := range testCases {
url := server.URL + "/bar?data=" + url.QueryEscape(tc.QueryParams)
resp, err := http.Get(url)
assert.NoError(t, err)
assert.Equal(t, tc.ExpectedStatus, resp.StatusCode)
}
}
21 changes: 4 additions & 17 deletions pkg/echo.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,32 +9,19 @@ import (
"github.com/fvbock/endless"
"github.com/labstack/echo/v4"
"github.com/labstack/echo/v4/middleware"
"github.com/sirupsen/logrus"
)

func NewEcho() *echo.Echo {
e := echo.New()
e.HTTPErrorHandler = HTTPErrorHandler
e.Pre(middleware.RemoveTrailingSlash())
SetupLogger(e)
e.Use(middleware.LoggerWithConfig(middleware.LoggerConfig{
Format: "REQ [${time_custom}] ${method} ${uri} (${latency_human}) ${status}\n",
CustomTimeFormat: "2006-01-02 15:04:05",
}))
SetupRoutes(e)
return e
}
func SetupLogger(e *echo.Echo) {
log := logrus.New()
e.Use(middleware.RequestLoggerWithConfig(middleware.RequestLoggerConfig{
LogURI: true,
LogStatus: true,
LogValuesFunc: func(c echo.Context, values middleware.RequestLoggerValues) error {
log.WithFields(logrus.Fields{
"URI": values.URI,
"status": values.Status,
}).Info("request")

return nil
},
}))
}

// GracefulServerWithPid reloads server with pid
// kill -HUP when binary is changed
Expand Down
9 changes: 5 additions & 4 deletions pkg/line_chart.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import (
"strconv"
"time"

"github.com/araddon/dateparse"
"github.com/wcharczuk/go-chart/v2"
)

Expand Down Expand Up @@ -55,7 +56,7 @@ func (c *LineChart) GetSeries(xData [][]string, yData [][]float64, names []strin
series = append(series, chart.TimeSeries{
Name: name,
Style: c.GetChartStroke(i),
XValues: c.GetXValuesAsTime(xData[i]),
XValues: c.GetXValuesAsDates(xData[i]),
YValues: c.GetYValues(yData[i]),
})
} else {
Expand All @@ -71,10 +72,10 @@ func (c *LineChart) GetSeries(xData [][]string, yData [][]float64, names []strin
return series
}

func (c *LineChart) GetXValuesAsTime(data []string) []time.Time {
func (c *LineChart) GetXValuesAsDates(data []string) []time.Time {
var xValues []time.Time
for _, x := range data {
t, _ := time.Parse("2006-01-02", x)
t, _ := dateparse.ParseAny(x)
xValues = append(xValues, t)
}
return xValues
Expand All @@ -93,7 +94,7 @@ func (c *LineChart) GetXValuesAsFloat(data []string) []float64 {

func (c *LineChart) IsTimeseries(str string) bool {
isTimeSeries := false
if _, err := time.Parse("2006-01-02", str); err == nil {
if _, err := dateparse.ParseAny(str); err == nil {
isTimeSeries = true
}
return isTimeSeries
Expand Down
7 changes: 4 additions & 3 deletions pkg/line_chart_handler.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import (
"bytes"
"encoding/json"
"errors"
"net/http"

"github.com/labstack/echo/v4"
"github.com/wcharczuk/go-chart/v2"
Expand Down Expand Up @@ -37,16 +38,16 @@ type LineChartData struct {
func (h *LineChartHandler) Get(c echo.Context) ([]byte, error) {
req := new(LineChartRequest)
if err := BindRequest(c, req); err != nil {
return nil, err
return nil, echo.NewHTTPError(http.StatusUnprocessableEntity, err.Error())
}

var data LineChartData
if err := json.Unmarshal([]byte(req.ChartData), &data); err != nil {
return nil, err
return nil, echo.NewHTTPError(http.StatusUnprocessableEntity, err.Error())
}

if len(data.XData) == 0 || len(data.XData) != len(data.YData) {
return nil, errors.New("data: invalid data")
return nil, echo.NewHTTPError(http.StatusUnprocessableEntity, errors.New("data: invalid data"))
}

graph := chart.Chart{
Expand Down
2 changes: 1 addition & 1 deletion pkg/line_chart_handler_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ import (
"github.com/stretchr/testify/assert"
)

func TestGetLineRequestChart_ValidRequest(t *testing.T) {
func TestGetLineChart(t *testing.T) {
e := echo.New()

e.GET("/line", func(c echo.Context) error {
Expand Down
10 changes: 0 additions & 10 deletions pkg/logger.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@ import (
"sync"

"github.com/sirupsen/logrus"
"gopkg.in/natefinch/lumberjack.v2"
)

var (
Expand All @@ -29,15 +28,6 @@ func Logger() *logrus.Logger {
})
log.SetReportCaller(false)
log.SetLevel(logrus.InfoLevel)
// set logs to file and log rotate
// Set up lumberjack log file rotation
log.SetOutput(&lumberjack.Logger{
Filename: DEFAULT_LOG_FILE, // specify your log file path
MaxSize: 10, // max size in megabytes
MaxBackups: 5, // max number of old log files to keep
MaxAge: 28, // max age in days to keep a log file
Compress: true, // whether to compress log files
})
})
return log
}

0 comments on commit 01600e0

Please sign in to comment.