From 53bd330c2d2fdddff190e7cf90b9e4f8b1721f9f Mon Sep 17 00:00:00 2001 From: Fahed DORGAA Date: Thu, 7 Jul 2022 16:11:34 +0200 Subject: [PATCH] repo imporve Signed-off-by: fahed dorgaa --- .github/dependabot.yml | 22 ++++++ .github/workflows/test.yml | 38 ++++++++++ .gitignore | 23 +++++++ .golangci.yml | 138 +++++++++++++++++++++++++++++++++++++ README.md | 24 ++++++- chown.go | 9 --- examples/rotate_test.go | 26 +++++++ go.mod | 2 +- logrotate.go | 84 +++++++++++++--------- logrotate_linux.go | 19 +++++ logrotate_test.go | 93 ++++++++++++------------- testing_test.go | 2 +- 12 files changed, 383 insertions(+), 97 deletions(-) create mode 100644 .github/dependabot.yml create mode 100644 .github/workflows/test.yml create mode 100644 .gitignore create mode 100644 .golangci.yml delete mode 100644 chown.go create mode 100644 examples/rotate_test.go create mode 100644 logrotate_linux.go diff --git a/.github/dependabot.yml b/.github/dependabot.yml new file mode 100644 index 0000000..44dd1eb --- /dev/null +++ b/.github/dependabot.yml @@ -0,0 +1,22 @@ +# ----------------------------------------------------------------------------- +# Forked from https://raw.githubusercontent.com/opencontainers/runc/2888e6e54339e52ae45710daa9e47cdb2e1926f9/.github/dependabot.yml +# Copyright The runc Authors. +# Licensed under the Apache License, Version 2.0 +# ----------------------------------------------------------------------------- + +# Please see the documentation for all configuration options: +# https://help.github.com/github/administering-a-repository/configuration-options-for-dependency-updates + +version: 2 +updates: + # Dependencies listed in go.mod + - package-ecosystem: "gomod" + directory: "/" # Location of package manifests + schedule: + interval: "weekly" + + # Dependencies listed in .github/workflows/*.yml + - package-ecosystem: "github-actions" + directory: "/" + schedule: + interval: "weekly" diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml new file mode 100644 index 0000000..a05b3ce --- /dev/null +++ b/.github/workflows/test.yml @@ -0,0 +1,38 @@ +name: test + +on: + push: + branches: + - main + - 'release/**' + pull_request: + +jobs: + golangci-lint: + runs-on: ubuntu-20.04 + timeout-minutes: 20 + steps: + - uses: actions/checkout@v3.0.2 + with: + fetch-depth: 1 + - uses: actions/setup-go@v3 + with: + go-version: 1.18.x + - name: golangci-lint + uses: golangci/golangci-lint-action@v3.2.0 + with: + version: v1.45.0 + args: --verbose + + test-unit: + runs-on: ubuntu-20.04 + timeout-minutes: 20 + steps: + - uses: actions/setup-go@v3 + with: + go-version: 1.18.x + - uses: actions/checkout@v3.0.2 + with: + fetch-depth: 1 + - name: "Run unit tests" + run: go test -v . \ No newline at end of file diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..9d96717 --- /dev/null +++ b/.gitignore @@ -0,0 +1,23 @@ +# Compiled Object files, Static and Dynamic libs (Shared Objects) +*.o +*.a +*.so + +# Folders +_obj +_test + +# Architecture specific extensions/prefixes +*.[568vq] +[568vq].out + +*.cgo1.go +*.cgo2.c +_cgo_defun.c +_cgo_gotypes.go +_cgo_export.* + +_testmain.go + +*.exe +*.test \ No newline at end of file diff --git a/.golangci.yml b/.golangci.yml new file mode 100644 index 0000000..f509e05 --- /dev/null +++ b/.golangci.yml @@ -0,0 +1,138 @@ +--- +run: + concurrency: 6 + deadline: 5m +linters: + disable-all: true + enable: + - deadcode + - depguard + - gofmt + - goimports + - govet + - ineffassign + - misspell + - nakedret + - prealloc + - structcheck + - typecheck + - varcheck + # - asciicheck + # - bodyclose + # - dogsled + # - dupl + # - errcheck + # - errorlint + # - exhaustive + # - exhaustivestruct + # - exportloopref + # - funlen + # - gci + # - gochecknoglobals + # - gochecknoinits + # - gocognit + # - goconst + # - gocritic + # - gocyclo + # - godot + # - godox + # - goerr113 + # - gofumpt + # - goheader + # - golint + # - gomnd + # - gomodguard + # - goprintffuncname + # - gosec (gas) + - gosimple # (megacheck) + # - interfacer + # - lll + # - maligned + # - nestif + # - nlreturn + # - noctx + # - nolintlint + # - rowserrcheck + # - scopelint + # - sqlclosecheck + - staticcheck + - stylecheck + # - testpackage + # - tparallel + # - unconvert + # - unparam + # - unused + # - whitespace + # - wrapcheck + # - wsl +linters-settings: + gocritic: + enabled-checks: + # Diagnostic + - appendAssign + - argOrder + - badCond + - caseOrder + - codegenComment + - commentedOutCode + - deprecatedComment + - dupArg + - dupBranchBody + - dupCase + - dupSubExpr + - exitAfterDefer + - flagDeref + - flagName + - nilValReturn + - offBy1 + - sloppyReassign + - weakCond + - octalLiteral + + # Performance + - appendCombine + - equalFold + - hugeParam + - indexAlloc + - rangeExprCopy + - rangeValCopy + + # Style + - assignOp + - boolExprSimplify + - captLocal + - commentFormatting + - commentedOutImport + - defaultCaseOrder + - docStub + - elseif + - emptyFallthrough + - emptyStringTest + - hexLiteral + - ifElseChain + - methodExprCall + - regexpMust + - singleCaseSwitch + - sloppyLen + - stringXbytes + - switchTrue + - typeAssertChain + - typeSwitchVar + - underef + - unlabelStmt + - unlambda + - unslice + - valSwap + - wrapperFunc + - yodaStyleExpr + + # Opinionated + - builtinShadow + - importShadow + - initClause + - nestingReduce + - paramTypeCombine + - ptrToRefParam + - typeUnparen + - unnamedResult + - unnecessaryBlock \ No newline at end of file diff --git a/README.md b/README.md index 72ad8ae..b862a69 100644 --- a/README.md +++ b/README.md @@ -3,6 +3,10 @@ go-logrotate is based on [lumberjack](https://github.com/natefinch/lumberjack). +to import go-logrotate : + + import "github.com/fahedouch/go-logrotate" + go-logrotate add new features to Lumberjack: - Supporting MaxBytes to specify the log size in bytes. - Supporting unlimited MaxBytes with `-1`. @@ -13,16 +17,30 @@ go-logrotate add new features to Lumberjack: ## Example -To use go-logrotate with the standard library's log package, just pass it into the SetOutput function when your application starts. +To use go-logrotate with the standard library's log package and with file name standard format, just pass it into the SetOutput function when your application starts. Code: ``` -log.SetOutput(&go_logrotate.Logger{ +log.SetOutput(&logrotate.Logger{ Filename: "/var/log/myapp/foo.log", MaxBytes: 500, // bytes MaxBackups: 3, MaxAge: 28, //days Compress: true, // disabled by default }) -``` \ No newline at end of file +``` + +To use go-logrotate with file name time format. +File name time format takes precedence over the standard format. + +``` +log.SetOutput(&logrotate.Logger{ + Filename: "/var/log/myapp/foo.log", + FilenameTimeFormat: "2006-01-02T15-04-05.000", + MaxBytes: 500, // bytes + MaxBackups: 3, + MaxAge: 28, //days + Compress: true, // disabled by default +}) +``` diff --git a/chown.go b/chown.go deleted file mode 100644 index ff0c103..0000000 --- a/chown.go +++ /dev/null @@ -1,9 +0,0 @@ -package go_logrotate - -import ( - "os" -) - -func chown(_ string, _ os.FileInfo) error { - return nil -} diff --git a/examples/rotate_test.go b/examples/rotate_test.go new file mode 100644 index 0000000..aa5f406 --- /dev/null +++ b/examples/rotate_test.go @@ -0,0 +1,26 @@ +//go:build linux +// +build linux + +package logrotate + +import ( + "log" + "os" + "os/signal" + "syscall" +) + +// Example of how to rotate in response to SIGHUP. +func ExampleLogger_Rotate() { + l := &Logger{} + log.SetOutput(l) + c := make(chan os.Signal, 1) + signal.Notify(c, syscall.SIGHUP) + + go func() { + for { + <-c + l.Rotate() + } + }() +} diff --git a/go.mod b/go.mod index 70de3fc..3097661 100644 --- a/go.mod +++ b/go.mod @@ -1,4 +1,4 @@ -module github.com/fahedouch/log-rotate +module github.com/fahedouch/go-logrotate go 1.18 diff --git a/logrotate.go b/logrotate.go index 5a9d4b3..733b27f 100644 --- a/logrotate.go +++ b/logrotate.go @@ -1,7 +1,6 @@ -// Package go_logrotate // logrotate.go micmics https://github.com/natefinch/lumberjack/blob/v2.0/lumberjack.go -package go_logrotate +package logrotate import ( "compress/gzip" @@ -11,6 +10,7 @@ import ( "os" "path/filepath" "sort" + "strconv" "strings" "sync" "time" @@ -207,7 +207,7 @@ func (l *Logger) openNew() error { // Copy the mode off the old logfile. mode = info.Mode() // move the existing file - newname, err := backupName(name, l.FilenameTimeFormat, l.LocalTime) + newname, err := l.backupName(name, l.FilenameTimeFormat, l.LocalTime) if err != nil { return err } @@ -215,6 +215,14 @@ func (l *Logger) openNew() error { return fmt.Errorf("can't rename log file: %s", err) } + // Set both access time and modified time of the backup file to the current time + // We will use the file Mod time to get time informations of backup file with standard name format + if l.FilenameTimeFormat == "" { + err := os.Chtimes(newname, currentTime(), currentTime()) + if err != nil { + return err + } + } // this is a no-op anywhere but linux if err := chown(name, info); err != nil { return err @@ -228,32 +236,40 @@ func (l *Logger) openNew() error { if err != nil { return fmt.Errorf("can't open new logfile: %s", err) } + l.file = f l.size = 0 return nil } // backupName creates a new filename -func backupName(name, nameTimeFormat string, local bool) (string, error) { +func (l *Logger) backupName(name, nameTimeFormat string, local bool) (string, error) { dir := filepath.Dir(name) - base := filepath.Base(name) - ext := filepath.Ext(base) - prefix := base[:len(base)-len(ext)] + prefix, ext := l.prefixAndExt() var filename string - filename = fmt.Sprintf("%s%s", prefix, ext) if nameTimeFormat != "" { t := currentTime() if !local { t = t.UTC() } timestamp := t.Format(nameTimeFormat) - filename = fmt.Sprintf("%s-%s%s", prefix, timestamp, ext) + filename = fmt.Sprintf("%s%s%s", prefix, timestamp, ext) } else { - logFiles, err := os.ReadDir(dir) + oldFiles, err := l.oldLogFiles() if err != nil { return "", err } - filename = fmt.Sprintf("%s%s.%d", prefix, ext, len(logFiles)) + var maxBackupOrder int + for _, f := range oldFiles { + if !strings.HasSuffix(f.Name(), compressSuffix) { + if order, err := l.orderFromName(f.Name(), prefix, ext); err == nil { + if maxBackupOrder < order { + maxBackupOrder = order + } + } + } + } + filename = fmt.Sprintf("%s%s.%d", prefix, ext, maxBackupOrder+1) } return filepath.Join(dir, filename), nil @@ -319,10 +335,7 @@ func (l *Logger) millRunOnce() error { for _, f := range files { // Only count the uncompressed log file or the // compressed log file, not both. - fn := f.Name() - if strings.HasSuffix(fn, compressSuffix) { - fn = fn[:len(fn)-len(compressSuffix)] - } + fn := strings.TrimSuffix(f.Name(), compressSuffix) preserved[fn] = true if len(preserved) > l.MaxBackups { @@ -433,7 +446,7 @@ func (l *Logger) oldLogFiles() ([]logInfo, error) { logFiles = append(logFiles, logInfo{logInfoTime, fInfo}) continue } - if _, err := l.orderFromName(strings.TrimSuffix(f.Name(), compressSuffix), prefix, ext); err == nil { + if _, err := l.orderFromName(f.Name(), prefix, ext+compressSuffix); err == nil { logInfoTime, err := l.getFileTimeInfo(f.Name()) if err != nil { return nil, err @@ -464,22 +477,31 @@ func (l *Logger) timeFromName(filename, prefix, ext string) (time.Time, error) { } // orderFromName extracts the order from the filename -func (l *Logger) orderFromName(filename string, prefix, ext string) (string, error) { - var order string - if filename == prefix { - return "", errors.New("mismatched file name") - } +func (l *Logger) orderFromName(filename string, prefix, ext string) (int, error) { if !strings.HasPrefix(filename, prefix) { - return "", errors.New("mismatched prefix") + return 0, errors.New("mismatched prefix") } if !strings.HasSuffix(filename, ext) { - return "", errors.New("mismatched extension") + return 0, errors.New("mismatched extension") + } + + var strOrder string + if ext != "" { + // compressed file(s) + strOrder = filename[len(prefix) : len(filename)-len(ext)] + } else { + strOrder = filepath.Ext(filename) + } + var err error + + order, err := strconv.Atoi(strings.TrimPrefix(strOrder, ".")) + if err != nil { + return 0, errors.New("mismatched order") } - order = filepath.Ext(filename) return order, nil } -// retreive file time informations +// retrieve file time informations func (l *Logger) getFileTimeInfo(fileName string) (time.Time, error) { t, err := times.Stat(filepath.Join(l.dir(), fileName)) if err != nil { @@ -489,6 +511,7 @@ func (l *Logger) getFileTimeInfo(fileName string) (time.Time, error) { if t.HasBirthTime() { logInfoTime = t.BirthTime() } else { + // we use change time which is fix during the log file life logInfoTime = t.ModTime() } return logInfoTime, nil @@ -520,15 +543,10 @@ func (l *Logger) prefixAndExt() (string, string) { ext = filepath.Ext(filename) prefix = filename[:len(filename)-len(ext)] + "-" default: + // case of file with standard file format // set prefix and ext for Filename to write logs to - if filepath.Ext(filename) == ".log" { - prefix = filename - ext = "" - } else { - order := filepath.Ext(filename) - prefix = strings.TrimSuffix(filename, order) - ext = "" - } + ext = "" + prefix = filename } return prefix, ext } diff --git a/logrotate_linux.go b/logrotate_linux.go new file mode 100644 index 0000000..249fa90 --- /dev/null +++ b/logrotate_linux.go @@ -0,0 +1,19 @@ +package logrotate + +import ( + "os" + "syscall" +) + +// osChown is a var so we can mock it out during tests. +var osChown = os.Chown + +func chown(name string, info os.FileInfo) error { + f, err := os.OpenFile(name, os.O_CREATE|os.O_WRONLY|os.O_TRUNC, info.Mode()) + if err != nil { + return err + } + f.Close() + stat := info.Sys().(*syscall.Stat_t) + return osChown(name, int(stat.Uid), int(stat.Gid)) +} diff --git a/logrotate_test.go b/logrotate_test.go index 2913e98..cbedb05 100644 --- a/logrotate_test.go +++ b/logrotate_test.go @@ -1,11 +1,10 @@ -package go_logrotate +package logrotate import ( "bytes" "compress/gzip" "encoding/json" "fmt" - "io/ioutil" "os" "path/filepath" "testing" @@ -59,7 +58,7 @@ func TestOpenExisting(t *testing.T) { filename := logFile(dir) data := []byte("foo!") - err := ioutil.WriteFile(filename, data, 0644) + err := os.WriteFile(filename, data, 0644) isNil(err, t) existsWithContent(filename, data, t) @@ -132,10 +131,10 @@ func TestDefaultFilename(t *testing.T) { existsWithContent(filename, b, t) } -func TestAutoRotateWithTime(t *testing.T) { +func TestAutoRotateBackupWithTime(t *testing.T) { currentTime = fakeTime - dir := makeTempDir("TestAutoRotateWithTime", t) + dir := makeTempDir("TestAutoRotateBackupWithTime", t) defer os.RemoveAll(dir) filename := logFile(dir) @@ -170,8 +169,8 @@ func TestAutoRotateWithTime(t *testing.T) { fileCount(dir, 2, t) } -func TestAutoRotateWithOrder(t *testing.T) { - dir := makeTempDir("TestAutoRotateWithOrder", t) +func TestAutoRotateBackupWithOrder(t *testing.T) { + dir := makeTempDir("TestAutoRotateBackupWithOrder", t) defer os.RemoveAll(dir) filename := logFile(dir) @@ -205,8 +204,8 @@ func TestAutoRotateWithOrder(t *testing.T) { fileCount(dir, 2, t) } -func TestFirstWriteRotateWithTime(t *testing.T) { - dir := makeTempDir("TestFirstWriteRotateWithTime", t) +func TestFirstWriteRotateBackupWithTime(t *testing.T) { + dir := makeTempDir("TestFirstWriteRotateBackupWithTime", t) defer os.RemoveAll(dir) filename := logFile(dir) @@ -218,7 +217,7 @@ func TestFirstWriteRotateWithTime(t *testing.T) { defer l.Close() start := []byte("boooooo!") - err := ioutil.WriteFile(filename, start, 0600) + err := os.WriteFile(filename, start, 0600) isNil(err, t) newFakeTime() @@ -235,8 +234,8 @@ func TestFirstWriteRotateWithTime(t *testing.T) { fileCount(dir, 2, t) } -func TestFirstWriteRotateWithOrder(t *testing.T) { - dir := makeTempDir("TestFirstWriteRotateWithOrder", t) +func TestFirstWriteRotateBackupWithOrder(t *testing.T) { + dir := makeTempDir("TestFirstWriteRotateBackupWithOrder", t) defer os.RemoveAll(dir) filename := logFile(dir) @@ -247,7 +246,7 @@ func TestFirstWriteRotateWithOrder(t *testing.T) { defer l.Close() start := []byte("boooooo!") - err := ioutil.WriteFile(filename, start, 0600) + err := os.WriteFile(filename, start, 0600) isNil(err, t) newFakeTime() @@ -336,7 +335,7 @@ func TestMaxBackupsWithTime(t *testing.T) { // create a file that is close to but different from the logfile name. // It shouldn't get caught by our deletion filters. notlogfile := logFile(dir) + ".foo" - err = ioutil.WriteFile(notlogfile, []byte("data"), 0644) + err = os.WriteFile(notlogfile, []byte("data"), 0644) isNil(err, t) // Make a directory that exactly matches our log file filters... it still @@ -354,7 +353,7 @@ func TestMaxBackupsWithTime(t *testing.T) { // not be counted since both the compressed and the uncompressed // log files still exist. compLogFile := fourthFilename + compressSuffix - err = ioutil.WriteFile(compLogFile, []byte("compress"), 0644) + err = os.WriteFile(compLogFile, []byte("compress"), 0644) isNil(err, t) // this will make us rotate again @@ -461,26 +460,26 @@ func TestMaxBackupsWithOrder(t *testing.T) { // create a file that is close to but different from the logfile name. // It shouldn't get caught by our deletion filters. - notlogfile := logFile(dir) + ".foo" - err = ioutil.WriteFile(notlogfile, []byte("data"), 0644) + notlogfile := logFile(dir) + ".4.foo" + err = os.WriteFile(notlogfile, []byte("data"), 0644) isNil(err, t) // Make a directory that exactly matches our log file filters... it still // shouldn't get caught by the deletion filter since it's a directory. - notlogfiledir := backupFileWithOrder(dir, 3) + notlogfiledir := backupFileWithOrder(dir, 4) err = os.Mkdir(notlogfiledir, 0700) isNil(err, t) newFakeTime() // this will use the new fake time - fourthFilename := backupFileWithOrder(dir, 2) + fourthFilename := backupFileWithOrder(dir, 3) // Create a log file that is/was being compressed - this should // not be counted since both the compressed and the uncompressed // log files still exist. compLogFile := fourthFilename + compressSuffix - err = ioutil.WriteFile(compLogFile, []byte("compress"), 0644) + err = os.WriteFile(compLogFile, []byte("compress"), 0644) isNil(err, t) // this will make us rotate again @@ -518,9 +517,7 @@ func TestMaxBackupsWithOrder(t *testing.T) { func TestCleanupExistingBackupsWithTime(t *testing.T) { // test that if we start with more backup files than we're supposed to have // in total, that extra ones get cleaned up when we rotate. - currentTime = fakeTime - megabyte = 1 dir := makeTempDir("TestCleanupExistingBackupsWithTime", t) defer os.RemoveAll(dir) @@ -529,24 +526,24 @@ func TestCleanupExistingBackupsWithTime(t *testing.T) { data := []byte("data") backup := backupFileWithTime(dir, backupTimeFormat) - err := ioutil.WriteFile(backup, data, 0644) + err := os.WriteFile(backup, data, 0644) isNil(err, t) newFakeTime() backup = backupFileWithTime(dir, backupTimeFormat) - err = ioutil.WriteFile(backup+compressSuffix, data, 0644) + err = os.WriteFile(backup+compressSuffix, data, 0644) isNil(err, t) newFakeTime() backup = backupFileWithTime(dir, backupTimeFormat) - err = ioutil.WriteFile(backup, data, 0644) + err = os.WriteFile(backup, data, 0644) isNil(err, t) // now create a primary log file with some data filename := logFile(dir) - err = ioutil.WriteFile(filename, data, 0644) + err = os.WriteFile(filename, data, 0644) isNil(err, t) l := &Logger{ @@ -575,9 +572,7 @@ func TestCleanupExistingBackupsWithTime(t *testing.T) { func TestCleanupExistingBackupsWithOrder(t *testing.T) { // test that if we start with more backup files than we're supposed to have // in total, that extra ones get cleaned up when we rotate. - currentTime = fakeTime - megabyte = 1 dir := makeTempDir("TestCleanupExistingBackupsWithOrder", t) defer os.RemoveAll(dir) @@ -586,24 +581,24 @@ func TestCleanupExistingBackupsWithOrder(t *testing.T) { data := []byte("data") backup := backupFileWithOrder(dir, 1) - err := ioutil.WriteFile(backup, data, 0644) + err := os.WriteFile(backup, data, 0644) isNil(err, t) newFakeTime() backup = backupFileWithOrder(dir, 2) - err = ioutil.WriteFile(backup+compressSuffix, data, 0644) + err = os.WriteFile(backup+compressSuffix, data, 0644) isNil(err, t) newFakeTime() backup = backupFileWithOrder(dir, 3) - err = ioutil.WriteFile(backup, data, 0644) + err = os.WriteFile(backup, data, 0644) isNil(err, t) // now create a primary log file with some data filename := logFile(dir) - err = ioutil.WriteFile(filename, data, 0644) + err = os.WriteFile(filename, data, 0644) isNil(err, t) l := &Logger{ @@ -631,7 +626,7 @@ func TestCleanupExistingBackupsWithOrder(t *testing.T) { func TestMaxAgeOfBackupsWithTime(t *testing.T) { currentTime = fakeTime - dir := makeTempDir("TestMaxAgeOfBackupsWithTime", t) + dir := makeTempDir(identifier(t), t) defer os.RemoveAll(dir) filename := logFile(dir) @@ -699,7 +694,6 @@ func TestMaxAgeOfBackupsWithTime(t *testing.T) { func TestOldLogFiles(t *testing.T) { currentTime = fakeTime - megabyte = 1 dir := makeTempDir(identifier(t), t) defer os.RemoveAll(dir) @@ -754,13 +748,13 @@ func TestOrderFromFileName(t *testing.T) { prefix, ext := l.prefixAndExt() tests := []struct { filename string - want string + want int wantErr bool }{ - {"foo.log.1", ".1", false}, - {"foo", "", true}, - {".log", "", true}, - {"foo.xls", "", true}, + {"foo.log.1", 1, false}, + {"foo", 0, true}, + {".log", 0, true}, + {"foo.xls", 0, true}, } for _, test := range tests { @@ -773,7 +767,7 @@ func TestOrderFromFileName(t *testing.T) { func TestLocalTime(t *testing.T) { currentTime = fakeTime - dir := makeTempDir("TestLocalTime", t) + dir := makeTempDir(identifier(t), t) defer os.RemoveAll(dir) l := &Logger{ @@ -799,7 +793,7 @@ func TestLocalTime(t *testing.T) { func TestRotateBackupsWithTime(t *testing.T) { currentTime = fakeTime - dir := makeTempDir("TestRotateBackupsWithTime", t) + dir := makeTempDir(identifier(t), t) defer os.RemoveAll(dir) filename := logFile(dir) @@ -857,7 +851,7 @@ func TestRotateBackupsWithTime(t *testing.T) { func TestRotateBackupsWithOrder(t *testing.T) { currentTime = fakeTime - dir := makeTempDir("TestRotateBackupsWithOrder", t) + dir := makeTempDir(identifier(t), t) defer os.RemoveAll(dir) filename := logFile(dir) @@ -915,7 +909,7 @@ func TestRotateBackupsWithOrder(t *testing.T) { func TestCompressBackupsWithTimeOnRotate(t *testing.T) { currentTime = fakeTime - dir := makeTempDir("TestCompressBackupsWithTimeOnRotate", t) + dir := makeTempDir(identifier(t), t) defer os.RemoveAll(dir) filename := logFile(dir) @@ -964,7 +958,7 @@ func TestCompressBackupsWithTimeOnRotate(t *testing.T) { func TestCompressBackupsWithOrderOnRotate(t *testing.T) { currentTime = fakeTime - dir := makeTempDir("TestCompressBackupsWithOrderOnRotate", t) + dir := makeTempDir(identifier(t), t) defer os.RemoveAll(dir) filename := logFile(dir) @@ -1011,9 +1005,8 @@ func TestCompressBackupsWithOrderOnRotate(t *testing.T) { func TestCompressOnResume(t *testing.T) { currentTime = fakeTime - megabyte = 1 - dir := makeTempDir("TestCompressOnResume", t) + dir := makeTempDir(identifier(t), t) defer os.RemoveAll(dir) filename := logFile(dir) @@ -1028,9 +1021,9 @@ func TestCompressOnResume(t *testing.T) { // Create a backup file and empty "compressed" file. filename2 := backupFileWithTime(dir, backupTimeFormat) b := []byte("foo!") - err := ioutil.WriteFile(filename2, b, 0644) + err := os.WriteFile(filename2, b, 0644) isNil(err, t) - err = ioutil.WriteFile(filename2+compressSuffix, []byte{}, 0644) + err = os.WriteFile(filename2+compressSuffix, []byte{}, 0644) isNil(err, t) newFakeTime() @@ -1135,7 +1128,7 @@ func existsWithContent(path string, content []byte, t testing.TB) { isNilUp(err, t, 1) equalsUp(int64(len(content)), info.Size(), t, 1) - b, err := ioutil.ReadFile(path) + b, err := os.ReadFile(path) isNilUp(err, t, 1) equalsUp(content, b, t, 1) } @@ -1165,7 +1158,7 @@ func backupFileLocal(dir string, timeFormat string) string { // fileCount checks that the number of files in the directory is exp. func fileCount(dir string, exp int, t testing.TB) { - files, err := ioutil.ReadDir(dir) + files, err := os.ReadDir(dir) isNilUp(err, t, 1) // Make sure no other files were created. equalsUp(exp, len(files), t, 1) diff --git a/testing_test.go b/testing_test.go index 4d7dee0..75158da 100644 --- a/testing_test.go +++ b/testing_test.go @@ -1,4 +1,4 @@ -package go_logrotate +package logrotate import ( "fmt"