From a4b3dedb57bf23e5d670ff67194f49a966abf1a0 Mon Sep 17 00:00:00 2001 From: Joe Chen Date: Mon, 6 Mar 2023 21:50:32 +0800 Subject: [PATCH] WIP --- .editorconfig | 9 ++++++++ .github/workflows/go.yml | 43 ++++++++++++++++++++++++-------------- .github/workflows/lsif.yml | 27 +++++++++++++++++------- .golangci.yml | 19 +++++++++++++++++ README.md | 18 ++++++++-------- clog.go | 18 ++++++++-------- clog_test.go | 14 ++++++------- console.go | 2 +- console_test.go | 2 +- discord.go | 11 +++++----- discord_test.go | 12 +++++------ file.go | 3 +-- file_test.go | 7 +++---- go.mod | 11 ++++++++-- message_test.go | 16 +++++++------- slack.go | 7 +++---- slack_test.go | 10 ++++----- 17 files changed, 141 insertions(+), 88 deletions(-) create mode 100644 .editorconfig create mode 100644 .golangci.yml diff --git a/.editorconfig b/.editorconfig new file mode 100644 index 0000000..f7f3ac7 --- /dev/null +++ b/.editorconfig @@ -0,0 +1,9 @@ +# Docs: http://editorconfig.org + +root = true + +[*] +charset = utf-8 +end_of_line = lf +insert_final_newline = true +trim_trailing_whitespace = true diff --git a/.github/workflows/go.yml b/.github/workflows/go.yml index 61ce240..ecd27af 100644 --- a/.github/workflows/go.yml +++ b/.github/workflows/go.yml @@ -1,8 +1,18 @@ name: Go on: push: - branches: [master] + branches: [ main ] + paths: + - '**.go' + - 'go.mod' + - '.golangci.yml' + - '.github/workflows/go.yml' pull_request: + paths: + - '**.go' + - 'go.mod' + - '.golangci.yml' + - '.github/workflows/go.yml' env: GOPROXY: "https://proxy.golang.org" @@ -11,35 +21,36 @@ jobs: name: Lint runs-on: ubuntu-latest steps: - - uses: actions/checkout@v2 + - name: Install Go + uses: actions/setup-go@v3 + with: + go-version: 1.20.x + - name: Checkout code + uses: actions/checkout@v3 - name: Run golangci-lint - uses: actions-contrib/golangci-lint@v1 + uses: golangci/golangci-lint-action@v3 + with: + version: latest + args: --timeout=30m test: name: Test strategy: matrix: - go-version: [1.14.x, 1.15.x] - platform: [ubuntu-latest, macos-latest, windows-latest] + go-version: [ 1.19.x, 1.20.x ] + platform: [ ubuntu-latest, macos-latest, windows-latest ] runs-on: ${{ matrix.platform }} steps: - name: Install Go - uses: actions/setup-go@v1 + uses: actions/setup-go@v3 with: go-version: ${{ matrix.go-version }} - name: Checkout code - uses: actions/checkout@v2 - - name: Run unit tests + uses: actions/checkout@v3 + - name: Run tests with coverage run: go test -v -race -coverprofile=coverage -covermode=atomic ./... - name: Upload coverage report to Codecov - uses: codecov/codecov-action@v1.0.6 + uses: codecov/codecov-action@v1.5.0 with: file: ./coverage flags: unittests - - name: Cache downloaded modules - uses: actions/cache@v1 - with: - path: ~/go/pkg/mod - key: ${{ runner.os }}-go-${{ hashFiles('**/go.sum') }} - restore-keys: | - ${{ runner.os }}-go- diff --git a/.github/workflows/lsif.yml b/.github/workflows/lsif.yml index dd4d948..f89f816 100644 --- a/.github/workflows/lsif.yml +++ b/.github/workflows/lsif.yml @@ -1,17 +1,28 @@ name: LSIF -on: [push] +on: + push: + paths: + - '**.go' + - 'go.mod' + - '.github/workflows/lsif.yml' +env: + GOPROXY: "https://proxy.golang.org" + jobs: - build: + lsif-go: + if: github.repository == 'go-clog/clog' runs-on: ubuntu-latest steps: - - uses: actions/checkout@v1 + - uses: actions/checkout@v3 - name: Generate LSIF data uses: sourcegraph/lsif-go-action@master + - name: Upload LSIF data to sourcegraph.com + continue-on-error: true + uses: docker://sourcegraph/src-cli:latest with: - verbose: 'true' - - name: Upload LSIF data - uses: sourcegraph/lsif-upload-action@master + args: lsif upload -github-token=${{ secrets.GITHUB_TOKEN }} + - name: Upload LSIF data to cs.unknwon.dev continue-on-error: true + uses: docker://sourcegraph/src-cli:latest with: - endpoint: https://sourcegraph.com - github_token: ${{ secrets.GITHUB_TOKEN }} + args: -endpoint=https://cs.unknwon.dev lsif upload -github-token=${{ secrets.GITHUB_TOKEN }} diff --git a/.golangci.yml b/.golangci.yml new file mode 100644 index 0000000..82dd9ef --- /dev/null +++ b/.golangci.yml @@ -0,0 +1,19 @@ +linters-settings: + nakedret: + max-func-lines: 0 # Disallow any unnamed return statement + +linters: + enable: + - unused + - errcheck + - gosimple + - govet + - ineffassign + - staticcheck + - typecheck + - nakedret + - gofmt + - rowserrcheck + - unconvert + - goimports + - unparam diff --git a/README.md b/README.md index 3f2f6a5..4fe892d 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,4 @@ -# Clog +# Clog [![GitHub Workflow Status](https://img.shields.io/github/workflow/status/go-clog/clog/Go?logo=github&style=for-the-badge)](https://github.com/go-clog/clog/actions?query=workflow%3AGo) [![codecov](https://img.shields.io/codecov/c/github/go-clog/clog/master?logo=codecov&style=for-the-badge)](https://codecov.io/gh/go-clog/clog) @@ -13,10 +13,10 @@ This package supports multiple loggers across different levels of logging. It us ## Installation -The minimum requirement of Go is **1.11**. +The minimum requirement of Go is **1.19**. go get unknwon.dev/clog/v2 - + Please apply `-u` flag to update in the future. ## Getting Started @@ -51,7 +51,7 @@ The code inside `init` function is equivalent to the following: ```go func init() { - err := log.NewConsole(0, + err := log.NewConsole(0, log.ConsoleConfig{ Level: log.LevelTrace, }, @@ -66,7 +66,7 @@ Or expand further: ```go func init() { - err := log.NewConsoleWithName(log.DefaultConsoleName, 0, + err := log.NewConsoleWithName(log.DefaultConsoleName, 0, log.ConsoleConfig{ Level: log.LevelTrace, }, @@ -85,7 +85,7 @@ In production, you may want to make log less verbose and be asynchronous: ```go func init() { - // The buffer size mainly depends on number of logs could be produced at the same time, + // The buffer size mainly depends on number of logs could be produced at the same time, // 100 is a good default. err := log.NewConsole(100, log.ConsoleConfig{ @@ -145,7 +145,7 @@ func main() { ### Caller Location -When using `log.Error` and `log.Fatal` functions, the caller location is written along with logs. +When using `log.Error` and `log.Fatal` functions, the caller location is written along with logs. ```go func main() { @@ -171,10 +171,10 @@ File logger is the single most powerful builtin logger, it has the ability to ro ```go func init() { - err := log.NewFile(100, + err := log.NewFile(100, log.FileConfig{ Level: log.LevelInfo, - Filename: "clog.log", + Filename: "clog.log", FileRotationConfig: log.FileRotationConfig { Rotate: true, Daily: true, diff --git a/clog.go b/clog.go index b8ed751..37e397c 100644 --- a/clog.go +++ b/clog.go @@ -11,7 +11,7 @@ type Level int // Available logging levels. const ( - LevelTrace Level = iota + LevelDebug Level = iota LevelInfo LevelWarn LevelError @@ -20,8 +20,8 @@ const ( func (l Level) String() string { switch l { - case LevelTrace: - return "TRACE" + case LevelDebug: + return "DEBUG" case LevelInfo: return "INFO" case LevelWarn: @@ -36,9 +36,9 @@ func (l Level) String() string { } } -// Trace writes formatted log in Trace level. -func Trace(format string, v ...interface{}) { - mgr.write(LevelTrace, 0, format, v...) +// Debug writes formatted log in Debug level. +func Debug(format string, v ...interface{}) { + mgr.write(LevelDebug, 0, format, v...) } // Info writes formatted log in Info level. @@ -85,9 +85,9 @@ func FatalDepth(skip int, format string, v ...interface{}) { exit() } -// TraceTo writes formatted log in Trace level to the logger with given name. -func TraceTo(name, format string, v ...interface{}) { - mgr.writeTo(name, LevelTrace, 0, format, v...) +// DebugTo writes formatted log in Debug level to the logger with given name. +func DebugTo(name, format string, v ...interface{}) { + mgr.writeTo(name, LevelDebug, 0, format, v...) } // InfoTo writes formatted log in Info level to the logger with given name. diff --git a/clog_test.go b/clog_test.go index 7db9456..95b7509 100644 --- a/clog_test.go +++ b/clog_test.go @@ -62,7 +62,7 @@ func chanLoggerIniter(name string, level Level) Initer { func Test_chanLogger(t *testing.T) { test1 := "mode1" - test1Initer := chanLoggerIniter(test1, LevelTrace) + test1Initer := chanLoggerIniter(test1, LevelDebug) test2 := "mode2" test2Initer := chanLoggerIniter(test2, LevelError) @@ -87,8 +87,8 @@ func Test_chanLogger(t *testing.T) { }{ { name: "trace", - fn: Trace, - containsStr1: "[TRACE] log message", + fn: Debug, + containsStr1: "[DEBUG] log message", containsStr2: "", }, { @@ -133,10 +133,10 @@ func Test_chanLogger(t *testing.T) { func Test_writeToNamedLogger(t *testing.T) { test1 := "alice" - test1Initer := chanLoggerIniter(test1, LevelTrace) + test1Initer := chanLoggerIniter(test1, LevelDebug) test2 := "bob" - test2Initer := chanLoggerIniter(test2, LevelTrace) + test2Initer := chanLoggerIniter(test2, LevelDebug) c1 := make(chan string) c2 := make(chan string) @@ -158,8 +158,8 @@ func Test_writeToNamedLogger(t *testing.T) { }{ { name: "trace", - fn: TraceTo, - containsStr1: "[TRACE] log message", + fn: DebugTo, + containsStr1: "[DEBUG] log message", containsStr2: "", }, { diff --git a/console.go b/console.go index 8fe4258..758c2e4 100644 --- a/console.go +++ b/console.go @@ -8,7 +8,7 @@ import ( // consoleColors is the color set for different levels. var consoleColors = []func(a ...interface{}) string{ - color.New(color.FgBlue).SprintFunc(), // Trace + color.New(color.FgBlue).SprintFunc(), // Debug color.New(color.FgGreen).SprintFunc(), // Info color.New(color.FgYellow).SprintFunc(), // Warn color.New(color.FgRed).SprintFunc(), // Error diff --git a/console_test.go b/console_test.go index d9bcdea..427acfb 100644 --- a/console_test.go +++ b/console_test.go @@ -47,5 +47,5 @@ func Test_consoleLogger(t *testing.T) { assert.Equal(t, DefaultConsoleName, mgr.loggers[0].Name()) assert.Equal(t, LevelInfo, mgr.loggers[0].Level()) assert.Equal(t, testName, mgr.loggers[1].Name()) - assert.Equal(t, LevelTrace, mgr.loggers[1].Level()) + assert.Equal(t, LevelDebug, mgr.loggers[1].Level()) } diff --git a/discord.go b/discord.go index 32d49c5..332d1c9 100644 --- a/discord.go +++ b/discord.go @@ -6,7 +6,6 @@ import ( "errors" "fmt" "io" - "io/ioutil" "net/http" "strings" "time" @@ -28,7 +27,7 @@ type ( var ( discordTitles = []string{ - "Trace", + "Debug", "Information", "Warning", "Error", @@ -36,7 +35,7 @@ var ( } discordColors = []int{ - 0, // Trace + 0, // Debug 3843043, // Info 16761600, // Warn 13041721, // Error @@ -54,10 +53,10 @@ type DiscordConfig struct { // Leave empty to use default as set in the Discord. Username string // Title for different levels, must have exact 5 elements in the order of - // Trace, Info, Warn, Error, and Fatal. + // Debug, Info, Warn, Error, and Fatal. Titles []string // Colors for different levels, must have exact 5 elements in the order of - // Trace, Info, Warn, Error, and Fatal. + // Debug, Info, Warn, Error, and Fatal. Colors []int } @@ -117,7 +116,7 @@ func (l *discordLogger) postMessage(r io.Reader) (int64, error) { return rateLimitMsg.RetryAfter, nil } else if resp.StatusCode/100 != 2 { - data, err := ioutil.ReadAll(resp.Body) + data, err := io.ReadAll(resp.Body) if err != nil { return -1, fmt.Errorf("read HTTP response body: %v", err) } diff --git a/discord_test.go b/discord_test.go index 7998063..2bab260 100644 --- a/discord_test.go +++ b/discord_test.go @@ -4,7 +4,7 @@ import ( "bytes" "encoding/json" "errors" - "io/ioutil" + "io" "net/http" "testing" @@ -85,7 +85,7 @@ func Test_discordLogger(t *testing.T) { assert.Equal(t, DefaultDiscordName, mgr.loggers[0].Name()) assert.Equal(t, LevelInfo, mgr.loggers[0].Level()) assert.Equal(t, testName, mgr.loggers[1].Name()) - assert.Equal(t, LevelTrace, mgr.loggers[1].Level()) + assert.Equal(t, LevelDebug, mgr.loggers[1].Level()) } func Test_discordLogger_buildPayload(t *testing.T) { @@ -105,7 +105,7 @@ func Test_discordLogger_buildPayload(t *testing.T) { { name: "trace", msg: &message{ - level: LevelTrace, + level: LevelDebug, body: "[TRACE] test message", }, wantTitle: discordTitles[0], @@ -186,7 +186,7 @@ func Test_discordLogger_buildPayload(t *testing.T) { { name: "trace", msg: &message{ - level: LevelTrace, + level: LevelDebug, body: "[TRACE] test message", }, wantTitle: l.titles[0], @@ -237,7 +237,7 @@ func Test_discordLogger_buildPayload(t *testing.T) { { name: "trace", msg: &message{ - level: LevelTrace, + level: LevelDebug, body: "test message", }, wantTitle: l.titles[0], @@ -283,7 +283,7 @@ func Test_discordLogger_postMessage(t *testing.T) { return &http.Response{ StatusCode: statusCode, - Body: ioutil.NopCloser(bytes.NewBufferString(respBody)), + Body: io.NopCloser(bytes.NewBufferString(respBody)), Header: make(http.Header), } }), diff --git a/file.go b/file.go index 25c05f3..c5a5c2a 100644 --- a/file.go +++ b/file.go @@ -4,7 +4,6 @@ import ( "bytes" "fmt" "io" - "io/ioutil" "log" "os" "path/filepath" @@ -121,7 +120,7 @@ func (l *fileLogger) initRotation() error { // If there is any content in the file, count the number of lines. if l.rotationConfig.MaxLines > 0 && l.currentSize > 0 { - data, err := ioutil.ReadFile(l.filename) + data, err := os.ReadFile(l.filename) if err != nil { return fmt.Errorf("read file %q: %v", l.filename, err) } diff --git a/file_test.go b/file_test.go index e971a4a..afef277 100644 --- a/file_test.go +++ b/file_test.go @@ -2,7 +2,6 @@ package clog import ( "errors" - "io/ioutil" "os" "path/filepath" "runtime" @@ -65,7 +64,7 @@ func Test_fileLogger(t *testing.T) { assert.Equal(t, DefaultFileName, mgr.loggers[0].Name()) assert.Equal(t, LevelInfo, mgr.loggers[0].Level()) assert.Equal(t, testName, mgr.loggers[1].Name()) - assert.Equal(t, LevelTrace, mgr.loggers[1].Level()) + assert.Equal(t, LevelDebug, mgr.loggers[1].Level()) } func Test_rotateFilename(t *testing.T) { @@ -74,11 +73,11 @@ func Test_rotateFilename(t *testing.T) { filename := rotateFilename("test/Test_rotateFilename.log", "2017-03-05") assert.Equal(t, "test/Test_rotateFilename.log.2017-03-05", filename) - assert.Nil(t, ioutil.WriteFile(filename, []byte(""), os.ModePerm)) + assert.Nil(t, os.WriteFile(filename, []byte(""), os.ModePerm)) filename = rotateFilename("test/Test_rotateFilename.log", "2017-03-05") assert.Equal(t, "test/Test_rotateFilename.log.2017-03-05.001", filename) - assert.Nil(t, ioutil.WriteFile(filename, []byte(""), os.ModePerm)) + assert.Nil(t, os.WriteFile(filename, []byte(""), os.ModePerm)) filename = rotateFilename("test/Test_rotateFilename.log", "2017-03-05") assert.Equal(t, "test/Test_rotateFilename.log.2017-03-05.002", filename) diff --git a/go.mod b/go.mod index 3779a03..0c27728 100644 --- a/go.mod +++ b/go.mod @@ -1,10 +1,17 @@ module unknwon.dev/clog/v2 -go 1.11 +go 1.19 require ( github.com/fatih/color v1.7.0 + github.com/stretchr/testify v1.4.0 +) + +require ( + github.com/davecgh/go-spew v1.1.0 // indirect github.com/mattn/go-colorable v0.1.4 // indirect github.com/mattn/go-isatty v0.0.10 // indirect - github.com/stretchr/testify v1.4.0 + github.com/pmezard/go-difflib v1.0.0 // indirect + golang.org/x/sys v0.0.0-20191008105621-543471e840be // indirect + gopkg.in/yaml.v2 v2.2.2 // indirect ) diff --git a/message_test.go b/message_test.go index 6355df2..d5ba948 100644 --- a/message_test.go +++ b/message_test.go @@ -16,11 +16,11 @@ func Test_newMessage(t *testing.T) { want string }{ { - name: "trace", - level: LevelTrace, - format: "a trace log: %v", + name: "debug", + level: LevelDebug, + format: "a debug log: %v", v: []interface{}{"value"}, - want: "[TRACE] a trace log: value", + want: "[DEBUG] a debug log: value", }, { name: "info", @@ -69,11 +69,11 @@ func Test_newMessage(t *testing.T) { contains string }{ { - name: "trace", - level: LevelTrace, - format: "a trace log: %v", + name: "debug", + level: LevelDebug, + format: "a debug log: %v", v: []interface{}{"value"}, - contains: "[TRACE] a trace log: value", + contains: "[DEBUG] a debug log: value", }, { name: "info", diff --git a/slack.go b/slack.go index 6f38666..e882962 100644 --- a/slack.go +++ b/slack.go @@ -6,7 +6,6 @@ import ( "errors" "fmt" "io" - "io/ioutil" "net/http" ) @@ -20,7 +19,7 @@ type slackPayload struct { } var slackColors = []string{ - "", // Trace + "", // Debug "#3aa3e3", // Info "warning", // Warn "danger", // Error @@ -34,7 +33,7 @@ type SlackConfig struct { // Slack webhook URL. URL string // Colors for different levels, must have exact 5 elements in the order of - // Trace, Info, Warn, Error, and Fatal. + // Debug, Info, Warn, Error, and Fatal. Colors []string } @@ -73,7 +72,7 @@ func (l *slackLogger) postMessage(r io.Reader) error { defer resp.Body.Close() if resp.StatusCode/100 != 2 { - data, err := ioutil.ReadAll(resp.Body) + data, err := io.ReadAll(resp.Body) if err != nil { return fmt.Errorf("read HTTP response body: %v", err) } diff --git a/slack_test.go b/slack_test.go index 48b35f7..a50940d 100644 --- a/slack_test.go +++ b/slack_test.go @@ -3,7 +3,7 @@ package clog import ( "bytes" "errors" - "io/ioutil" + "io" "net/http" "testing" @@ -75,7 +75,7 @@ func Test_slackLogger(t *testing.T) { assert.Equal(t, DefaultSlackName, mgr.loggers[0].Name()) assert.Equal(t, LevelInfo, mgr.loggers[0].Level()) assert.Equal(t, testName, mgr.loggers[1].Name()) - assert.Equal(t, LevelTrace, mgr.loggers[1].Level()) + assert.Equal(t, LevelDebug, mgr.loggers[1].Level()) } func Test_slackLogger_buildPayload(t *testing.T) { @@ -92,7 +92,7 @@ func Test_slackLogger_buildPayload(t *testing.T) { { name: "trace", msg: &message{ - level: LevelTrace, + level: LevelDebug, body: "test message", }, want: `{"attachments":[{"text":"test message","color":""}]}`, @@ -152,7 +152,7 @@ func Test_slackLogger_buildPayload(t *testing.T) { { name: "trace", msg: &message{ - level: LevelTrace, + level: LevelDebug, body: "test message", }, want: `{"attachments":[{"text":"test message","color":"#1"}]}`, @@ -223,7 +223,7 @@ func Test_slackLogger_postMessage(t *testing.T) { return &http.Response{ StatusCode: statusCode, - Body: ioutil.NopCloser(bytes.NewBufferString(respBody)), + Body: io.NopCloser(bytes.NewBufferString(respBody)), Header: make(http.Header), } }),