pax_global_header00006660000000000000000000000064146061727560014530gustar00rootroot0000000000000052 comment=e7e671d3a673890ee38392540079196cef61e3d6 go-logrotate-0.2.1/000077500000000000000000000000001460617275600141335ustar00rootroot00000000000000go-logrotate-0.2.1/.github/000077500000000000000000000000001460617275600154735ustar00rootroot00000000000000go-logrotate-0.2.1/.github/dependabot.yml000066400000000000000000000015411460617275600203240ustar00rootroot00000000000000# ----------------------------------------------------------------------------- # 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" go-logrotate-0.2.1/.github/workflows/000077500000000000000000000000001460617275600175305ustar00rootroot00000000000000go-logrotate-0.2.1/.github/workflows/test.yml000066400000000000000000000013201460617275600212260ustar00rootroot00000000000000name: test on: push: branches: - main - 'release/**' pull_request: jobs: golangci-lint: runs-on: ubuntu-20.04 timeout-minutes: 20 steps: - uses: actions/checkout@v4.1.2 with: fetch-depth: 1 - uses: actions/setup-go@v5 with: go-version: 1.18.x - name: golangci-lint uses: golangci/golangci-lint-action@v4.0.0 with: version: v1.45.0 args: --verbose test-unit: runs-on: ubuntu-20.04 timeout-minutes: 20 steps: - uses: actions/setup-go@v5 with: go-version: 1.18.x - uses: actions/checkout@v4.1.2 with: fetch-depth: 1 - name: "Run unit tests" run: go test -v .go-logrotate-0.2.1/.gitignore000066400000000000000000000004021460617275600161170ustar00rootroot00000000000000# 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 *.testgo-logrotate-0.2.1/.golangci.yml000066400000000000000000000046661460617275600165330ustar00rootroot00000000000000--- 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 - unnecessaryBlockgo-logrotate-0.2.1/LICENSE000066400000000000000000000261351460617275600151470ustar00rootroot00000000000000 Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS APPENDIX: How to apply the Apache License to your work. To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. Copyright [yyyy] [name of copyright owner] Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. go-logrotate-0.2.1/README.md000066400000000000000000000024071460617275600154150ustar00rootroot00000000000000# go-logrotate ## go-logrotate is a Go package for writing logs to rolling files. 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`. - Supporting multiple backups file names : - standard file name : `foo.log.1` - time file name: `foo-2014-05-04T14-44-33.555.log` ## Example 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(&logrotate.Logger{ Filename: "/var/log/myapp/foo.log", MaxBytes: 500, // bytes MaxBackups: 3, MaxAge: 28, //days Compress: true, // disabled by default }) ``` 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 }) ``` go-logrotate-0.2.1/examples/000077500000000000000000000000001460617275600157515ustar00rootroot00000000000000go-logrotate-0.2.1/examples/rotate_test.go000066400000000000000000000005771460617275600206460ustar00rootroot00000000000000//go:build linux // +build linux package logrotate import ( "log" "os" "os/signal" "syscall" "github.com/fahedouch/go-logrotate" ) // Example of how to rotate in response to SIGHUP. func ExampleLogger_Rotate() { l := &logrotate.Logger{} log.SetOutput(l) c := make(chan os.Signal, 1) signal.Notify(c, syscall.SIGHUP) go func() { for { <-c l.Rotate() } }() } go-logrotate-0.2.1/go.mod000066400000000000000000000003461460617275600152440ustar00rootroot00000000000000module github.com/fahedouch/go-logrotate go 1.21 require ( github.com/BurntSushi/toml v1.3.2 github.com/djherbis/times v1.6.0 gopkg.in/yaml.v2 v2.4.0 ) require golang.org/x/sys v0.0.0-20220615213510-4f61da869c0c // indirect go-logrotate-0.2.1/go.sum000066400000000000000000000016131460617275600152670ustar00rootroot00000000000000github.com/BurntSushi/toml v1.3.2 h1:o7IhLm0Msx3BaB+n3Ag7L8EVlByGnpq14C4YWiu/gL8= github.com/BurntSushi/toml v1.3.2/go.mod h1:CxXYINrC8qIiEnFrOxCa7Jy5BFHlXnUU2pbicEuybxQ= github.com/djherbis/times v1.6.0 h1:w2ctJ92J8fBvWPxugmXIv7Nz7Q3iDMKNx9v5ocVH20c= github.com/djherbis/times v1.6.0/go.mod h1:gOHeRAz2h+VJNZ5Gmc/o7iD9k4wW7NMVqieYCY99oc0= golang.org/x/sys v0.0.0-20220615213510-4f61da869c0c h1:aFV+BgZ4svzjfabn8ERpuB4JI4N6/rdy1iusx77G3oU= golang.org/x/sys v0.0.0-20220615213510-4f61da869c0c/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM= gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= gopkg.in/yaml.v2 v2.4.0 h1:D8xgwECY7CYvx+Y2n4sBz93Jn9JRvxdiyyo8CTfuKaY= gopkg.in/yaml.v2 v2.4.0/go.mod h1:RDklbk79AGWmwhnvt/jBztapEOGDOx6ZbXqjP6csGnQ= go-logrotate-0.2.1/logrotate.go000066400000000000000000000413111460617275600164620ustar00rootroot00000000000000// logrotate.go micmics https://github.com/natefinch/lumberjack/blob/v2.0/lumberjack.go package logrotate import ( "compress/gzip" "errors" "fmt" "io" "os" "path/filepath" "sort" "strconv" "strings" "sync" "time" "github.com/djherbis/times" ) const ( compressSuffix = ".gz" defaultMaxSize = 100 ) var mutex sync.Mutex // ensure we always implement io.WriteCloser var _ io.WriteCloser = (*Logger)(nil) // Logger is an io.WriteCloser that writes to the specified filename. // // Logger opens or creates the logfile on first Write. If the file exists and // is less than MaxBytes, logrotate will open and append to that file. // If the file exists and its size is >= MaxBytes, the file is renamed // by putting an incremental number after the file's extension or // the current time in a timestamp in the name immediately before the // file's extension (or the end of the filename if there's no extension). // A new log file is then created using original filename. // // Whenever a write would cause the current log file exceed MaxBytes, // the current file is closed, renamed, and a new log file created with the // original name. Thus, the filename you give Logger is always the "current" log // file. // // Backups uses the log file name given to Logger, in the form // `name.ext.num` or `name-timestamp.ext` where name is the filename without the extension, // timestamp is the birth time at which the log was rotated formatted with the // time.Time format of `2006-01-02T15-04-05.000` and the extension is the // original extension. // if Logger.FilenameTimeFormat is not empty the backup name format is `name-timestamp.ext` // if Logger.FilenameTimeFormat is empty the backup name format is `name.ext.num` // For example, if your Logger.Filename is `/var/log/foo/server.log` and Logger.FilenameTimeFormat // is not empty, a backup created at 6:30pm on Nov 11 2016 would // use the filename `/var/log/foo/server-2016-11-04T18-30-00.000.log` // // # Cleaning Up Old Log Files // // Whenever a new logfile gets created, old log files may be deleted. The most // recent files according to their birth time will be retained, up to a // number equal to MaxBackups (or all of them if MaxBackups is 0). Any files // birth time older than MaxAge days are deleted, regardless of // MaxBackups.Note that the file's birth time is the rotation // time, which may differ from the last time that file was written to. // // If MaxBackups and MaxAge are both 0, no old log files will be deleted. type Logger struct { // Filename is the file to write logs to. Backup log files will be retained // in the same directory. It uses .log in // os.TempDir() if empty. Filename string `json:"filename" yaml:"filename"` // FilenameTimeFormat determines whether the rotated log file name contains // timestamp or not and defines its format. It doesn't contain timestamp if empty. // (e.g `2006-01-02T15-04-05.000`) FilenameTimeFormat string `json:"filenameTimeFormat" yaml:"filenameTimeFormat"` // FileOrder is the starting order of old log file FileOrder int `json:"fileOrder" yaml:"fileOrder"` // MaxBytes is the maximum size in bytes of the log file before it gets // rotated. It defaults to 104857600 (100 megabytes). MaxBytes int64 `json:"maxbytes" yaml:"maxbytes"` // MaxAge is the maximum number of days to retain old log files based on the // timestamp encoded in their filename. Note that a day is defined as 24 // hours and may not exactly correspond to calendar days due to daylight // savings, leap seconds, etc. The default is not to remove old log files // based on age. MaxAge int `json:"maxage" yaml:"maxage"` // MaxBackups is the maximum number of old log files to retain. The default // is to retain all old log files (though MaxAge may still cause them to get // deleted.) MaxBackups int `json:"maxbackups" yaml:"maxbackups"` // LocalTime determines if the time used for formatting the timestamps in // backup files is the computer's local time. The default is to use UTC // time. LocalTime bool `json:"localtime" yaml:"localtime"` // Compress determines if the rotated log files should be compressed // using gzip. The default is not to perform compression. Compress bool `json:"compress" yaml:"compress"` size int64 file *os.File mu sync.Mutex } var ( // currentTime exists so it can be mocked out by tests. currentTime = time.Now // os_Stat exists so it can be mocked out by tests. osStat = os.Stat // megabyte is the conversion factor between MaxSize and bytes. It is a // variable so tests can mock it out and not need to write megabytes of data // to disk. megabyte = 1024 * 1024 ) // Write implements io.Writer. If a write would cause the log file to be larger // than MaxBytes, the file is closed, renamed and a new log file is created using the original log file name. // If the length of the write is greater than MaxBytes, an error is returned. func (l *Logger) Write(p []byte) (n int, err error) { l.mu.Lock() defer l.mu.Unlock() writeLen := int64(len(p)) if writeLen > l.max(writeLen) { return 0, fmt.Errorf( "write length %d exceeds maximum file size %d", writeLen, l.max(writeLen), ) } if l.file == nil { if err = l.openExistingOrNew(len(p)); err != nil { return 0, err } } if l.size+writeLen > l.max(writeLen) { if err := l.rotate(); err != nil { return 0, err } } n, err = l.file.Write(p) l.size += int64(n) return n, err } // Close implements io.Closer, and closes the current logfile. func (l *Logger) Close() error { l.mu.Lock() defer l.mu.Unlock() return l.close() } // close closes the file if it is open. func (l *Logger) close() error { if l.file == nil { return nil } err := l.file.Close() l.file = nil return err } // Rotate causes Logger to close the existing log file and immediately create a // new one. This is a helper function for applications that want to initiate // rotations outside of the normal rotation rules, such as in response to // SIGHUP. After rotating, this initiates compression and removal of old log // files according to the configuration. func (l *Logger) Rotate() error { l.mu.Lock() defer l.mu.Unlock() return l.rotate() } // rotate closes the current file, moves it aside with either a timestamp // in the name or number at the end of the name, (if it exists), // opens a new file with the original filename, and then runs post-rotation processing and removal. func (l *Logger) rotate() error { if err := l.close(); err != nil { return err } if err := l.openNew(); err != nil { return err } if err := l.millRun(); err != nil { return err } return nil } // openNew opens a new log file for writing, moving any old log file out of the // way. This methods assumes the file has already been closed. func (l *Logger) openNew() error { err := os.MkdirAll(l.dir(), 0755) if err != nil { return fmt.Errorf("can't make directories for new logfile: %s", err) } name := l.filename() mode := os.FileMode(0600) info, err := osStat(name) if err == nil { // Copy the mode off the old logfile. mode = info.Mode() // move the existing file newname, err := l.backupName(name, l.FilenameTimeFormat, l.LocalTime) if err != nil { return err } if err := os.Rename(name, newname); err != nil { 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 } } // we use truncate here because this should only get called when we've moved // the file ourselves. if someone else creates the file in the meantime, // just wipe out the contents. f, err := os.OpenFile(name, os.O_CREATE|os.O_WRONLY|os.O_TRUNC, mode) 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 (l *Logger) backupName(name, nameTimeFormat string, local bool) (string, error) { dir := filepath.Dir(name) prefix, ext := l.prefixAndExt() var filename string if nameTimeFormat != "" { t := currentTime() if !local { t = t.UTC() } timestamp := t.Format(nameTimeFormat) filename = fmt.Sprintf("%s%s%s", prefix, timestamp, ext) } else { mutex.Lock() l.FileOrder += 1 filename = fmt.Sprintf("%s%s.%d", prefix, ext, l.FileOrder) mutex.Unlock() } return filepath.Join(dir, filename), nil } // openExistingOrNew opens the logfile if it exists and if the current write // would not put it over MaxBytes. If there is no such file or the write would // put it over the MaxBytes, a new file is created. func (l *Logger) openExistingOrNew(writeLen int) error { l.millRun() filename := l.filename() info, err := osStat(filename) if os.IsNotExist(err) { return l.openNew() } if err != nil { return fmt.Errorf("error getting log file info: %s", err) } if info.Size()+int64(writeLen) >= l.max(int64(writeLen)) { return l.rotate() } file, err := os.OpenFile(filename, os.O_APPEND|os.O_WRONLY, 0644) if err != nil { // if we fail to open the old log file for some reason, just ignore // it and open a new log file. return l.openNew() } l.file = file l.size = info.Size() return nil } // filename generates the name of the logfile. func (l *Logger) filename() string { if l.Filename != "" { return l.Filename } name := filepath.Base(os.Args[0]) + ".log" return filepath.Join(os.TempDir(), name) } // millRun performs post-rotation compression and removal of stale log files, // Log files are compressed if enabled via configuration and old log // files are removed, keeping at most l.MaxBackups files, as long as // none of them are older than MaxAge. func (l *Logger) millRun() error { if l.MaxBackups == 0 && l.MaxAge == 0 && !l.Compress { return nil } files, err := l.oldLogFiles() if err != nil { return err } var compress, remove []logInfo if l.MaxBackups > 0 && l.MaxBackups < len(files) { preserved := make(map[string]bool) var remaining []logInfo for _, f := range files { // Only count the uncompressed log file or the // compressed log file, not both. fn := strings.TrimSuffix(f.Name(), compressSuffix) preserved[fn] = true if len(preserved) > l.MaxBackups { remove = append(remove, f) } else { remaining = append(remaining, f) } } files = remaining } if l.MaxAge > 0 { diff := time.Duration(int64(24*time.Hour) * int64(l.MaxAge)) cutoff := currentTime().Add(-1 * diff) var remaining []logInfo for _, f := range files { if f.timestamp.Before(cutoff) { remove = append(remove, f) } else { remaining = append(remaining, f) } } files = remaining } if l.Compress { for _, f := range files { if !strings.HasSuffix(f.Name(), compressSuffix) { compress = append(compress, f) } } } for _, f := range remove { errRemove := os.Remove(filepath.Join(l.dir(), f.Name())) if err == nil && errRemove != nil { err = errRemove } } for _, f := range compress { fn := filepath.Join(l.dir(), f.Name()) errCompress := compressLogFile(fn, fn+compressSuffix) if err == nil && errCompress != nil { err = errCompress } } return err } // oldLogFiles returns the list of backup log files stored in the same // directory as the current log file, sorted by bTime func (l *Logger) oldLogFiles() ([]logInfo, error) { files, err := os.ReadDir(l.dir()) if err != nil { return nil, fmt.Errorf("can't read log file directory: %s", err) } logFiles := []logInfo{} prefix, ext := l.prefixAndExt() for _, f := range files { if f.IsDir() { continue } fInfo, err := f.Info() if err != nil { return nil, err } switch { case l.FilenameTimeFormat != "": if t, err := l.timeFromName(f.Name(), prefix, ext); err == nil { logFiles = append(logFiles, logInfo{t, fInfo}) continue } if t, err := l.timeFromName(f.Name(), prefix, ext+compressSuffix); err == nil { logFiles = append(logFiles, logInfo{t, fInfo}) continue } default: if _, err := l.orderFromName(f.Name(), prefix, ext); err == nil { logInfoTime, err := l.getFileTimeInfo(f.Name()) if err != nil { return nil, err } logFiles = append(logFiles, logInfo{logInfoTime, fInfo}) continue } if _, err := l.orderFromName(f.Name(), prefix, ext+compressSuffix); err == nil { logInfoTime, err := l.getFileTimeInfo(f.Name()) if err != nil { return nil, err } logFiles = append(logFiles, logInfo{logInfoTime, fInfo}) continue } } } sort.Sort(byBirthTime(logFiles)) return logFiles, nil } // timeFromName extracts the formatted time from the filename by stripping off // the filename's prefix and extension. This prevents someone's filename from // confusing time.parse. func (l *Logger) timeFromName(filename, prefix, ext string) (time.Time, error) { if !strings.HasPrefix(filename, prefix) { return time.Time{}, errors.New("mismatched prefix") } if !strings.HasSuffix(filename, ext) { return time.Time{}, errors.New("mismatched extension") } ts := filename[len(prefix) : len(filename)-len(ext)] return time.Parse(l.FilenameTimeFormat, ts) } // orderFromName extracts the order from the filename func (l *Logger) orderFromName(filename string, prefix, ext string) (int, error) { if !strings.HasPrefix(filename, prefix) { return 0, errors.New("mismatched prefix") } if !strings.HasSuffix(filename, ext) { 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") } return order, nil } // 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 { return time.Time{}, err } var logInfoTime time.Time 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 } // max returns the maximum size in bytes of log files before rolling. func (l *Logger) max(writeLen int64) int64 { if l.MaxBytes != 0 { if l.MaxBytes == -1 { return writeLen + l.size + 1 } return l.MaxBytes } return int64(defaultMaxSize * megabyte) } // dir returns the directory for the current filename. func (l *Logger) dir() string { return filepath.Dir(l.filename()) } // prefixAndExt returns the filename part and extension part from the Logger's // filename. func (l *Logger) prefixAndExt() (string, string) { var prefix, ext string filename := filepath.Base(l.filename()) switch { case l.FilenameTimeFormat != "": 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 ext = "" prefix = filename } return prefix, ext } // compressLogFile compresses the given log file, removing the // uncompressed log file if successful. func compressLogFile(src, dst string) (err error) { f, err := os.Open(src) if err != nil { return fmt.Errorf("failed to open log file: %v", err) } defer f.Close() fi, err := osStat(src) if err != nil { return fmt.Errorf("failed to stat log file: %v", err) } if err := chown(dst, fi); err != nil { return fmt.Errorf("failed to chown compressed log file: %v", err) } // If this file already exists, we presume it was created by // a previous attempt to compress the log file. gzf, err := os.OpenFile(dst, os.O_CREATE|os.O_TRUNC|os.O_WRONLY, fi.Mode()) if err != nil { return fmt.Errorf("failed to open compressed log file: %v", err) } defer gzf.Close() gz := gzip.NewWriter(gzf) defer func() { if err != nil { os.Remove(dst) err = fmt.Errorf("failed to compress log file: %v", err) } }() if _, err := io.Copy(gz, f); err != nil { return err } if err := gz.Close(); err != nil { return err } if err := gzf.Close(); err != nil { return err } if err := f.Close(); err != nil { return err } if err := os.Remove(src); err != nil { return err } return nil } // logInfo is a convenience struct to return the filename and its embedded // timestamp. type logInfo struct { timestamp time.Time os.FileInfo } // byBirthTime sorts by newest birth time. type byBirthTime []logInfo func (b byBirthTime) Less(i, j int) bool { return b[i].timestamp.After(b[j].timestamp) } func (b byBirthTime) Swap(i, j int) { b[i], b[j] = b[j], b[i] } func (b byBirthTime) Len() int { return len(b) } go-logrotate-0.2.1/logrotate_freebsd.go000066400000000000000000000001371460617275600201550ustar00rootroot00000000000000package logrotate import ( "os" ) func chown(_ string, _ os.FileInfo) error { return nil } go-logrotate-0.2.1/logrotate_linux.go000066400000000000000000000006101460617275600176760ustar00rootroot00000000000000package 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)) } go-logrotate-0.2.1/logrotate_test.go000066400000000000000000000635001460617275600175250ustar00rootroot00000000000000package logrotate import ( "bytes" "compress/gzip" "encoding/json" "fmt" "os" "path/filepath" "testing" "time" "github.com/BurntSushi/toml" "gopkg.in/yaml.v2" ) // !!!NOTE!!! // // Running these tests in parallel will almost certainly cause sporadic (or even // regular) failures, because they're all messing with the same global variable // that controls the logic's mocked time.Now. So... don't do that. // Since some tests uses the time to determine filenames etc, we need to // control the wall clock as much as possible, which means having a wall clock // that doesn't change unless we want it to. const ( backupTimeFormat = "2006-01-02T15-04-05.000" ) var fakeCurrentTime = time.Now() func fakeTime() time.Time { return fakeCurrentTime } func TestNewFile(t *testing.T) { currentTime = fakeTime dir := makeTempDir("TestNewFile", t) defer os.RemoveAll(dir) l := &Logger{ Filename: logFile(dir), } defer l.Close() b := []byte("boo!") n, err := l.Write(b) isNil(err, t) equals(len(b), n, t) existsWithContent(logFile(dir), b, t) fileCount(dir, 1, t) } func TestOpenExisting(t *testing.T) { currentTime = fakeTime dir := makeTempDir("TestOpenExisting", t) defer os.RemoveAll(dir) filename := logFile(dir) data := []byte("foo!") err := os.WriteFile(filename, data, 0644) isNil(err, t) existsWithContent(filename, data, t) l := &Logger{ Filename: filename, } defer l.Close() b := []byte("boo!") n, err := l.Write(b) isNil(err, t) equals(len(b), n, t) // make sure the file got appended existsWithContent(filename, append(data, b...), t) // make sure no other files were created fileCount(dir, 1, t) } func TestWriteTooLong(t *testing.T) { currentTime = fakeTime dir := makeTempDir("TestWriteTooLong", t) defer os.RemoveAll(dir) l := &Logger{ Filename: logFile(dir), MaxBytes: 1, } defer l.Close() b := []byte("booooooooooooooo!") n, err := l.Write(b) notNil(err, t) equals(0, n, t) equals(err.Error(), fmt.Sprintf("write length %d exceeds maximum file size %d", len(b), l.MaxBytes), t) _, err = os.Stat(logFile(dir)) assert(os.IsNotExist(err), t, "File exists, but should not have been created") } func TestMakeLogDir(t *testing.T) { currentTime = fakeTime dir := "TestMakeLogDir" dir = filepath.Join(os.TempDir(), dir) defer os.RemoveAll(dir) filename := logFile(dir) l := &Logger{ Filename: filename, } defer l.Close() b := []byte("boo!") n, err := l.Write(b) isNil(err, t) equals(len(b), n, t) existsWithContent(logFile(dir), b, t) fileCount(dir, 1, t) } func TestDefaultFilename(t *testing.T) { currentTime = fakeTime dir := os.TempDir() filename := filepath.Join(dir, filepath.Base(os.Args[0])+".log") t.Log(filename) defer os.Remove(filename) l := &Logger{} defer l.Close() b := []byte("boo!") n, err := l.Write(b) isNil(err, t) equals(len(b), n, t) existsWithContent(filename, b, t) } func TestAutoRotateBackupWithTime(t *testing.T) { currentTime = fakeTime dir := makeTempDir("TestAutoRotateBackupWithTime", t) defer os.RemoveAll(dir) filename := logFile(dir) l := &Logger{ Filename: filename, FilenameTimeFormat: backupTimeFormat, MaxBytes: 10, } defer l.Close() b := []byte("boo!") n, err := l.Write(b) isNil(err, t) equals(len(b), n, t) existsWithContent(filename, b, t) fileCount(dir, 1, t) newFakeTime() b2 := []byte("foooooo!") n, err = l.Write(b2) isNil(err, t) equals(len(b2), n, t) // the old logfile should be moved aside and the main logfile should have // only the last write in it. existsWithContent(filename, b2, t) // the backup file will use the current fake time and have the old contents. existsWithContent(backupFileWithTime(dir, backupTimeFormat), b, t) fileCount(dir, 2, t) } func TestAutoRotateBackupWithOrder(t *testing.T) { currentTime = time.Now dir := makeTempDir("TestAutoRotateBackupWithOrder", t) defer os.RemoveAll(dir) filename := logFile(dir) l := &Logger{ Filename: filename, MaxBytes: 10, } defer l.Close() b := []byte("boo!") n, err := l.Write(b) isNil(err, t) equals(len(b), n, t) existsWithContent(filename, b, t) fileCount(dir, 1, t) b2 := []byte("foooooo!") n, err = l.Write(b2) isNil(err, t) equals(len(b2), n, t) // the old logfile should be moved aside and the main logfile should have // only the last write in it. existsWithContent(filename, b2, t) // the backup file will use the current fake time and have the old contents. existsWithContent(backupFileWithOrder(dir, 1), b, t) fileCount(dir, 2, t) } func TestFirstWriteRotateBackupWithTime(t *testing.T) { currentTime = fakeTime dir := makeTempDir("TestFirstWriteRotateBackupWithTime", t) defer os.RemoveAll(dir) filename := logFile(dir) l := &Logger{ Filename: filename, FilenameTimeFormat: backupTimeFormat, MaxBytes: 10, } defer l.Close() start := []byte("boooooo!") err := os.WriteFile(filename, start, 0600) isNil(err, t) newFakeTime() // this would make us rotate b := []byte("fooo!") n, err := l.Write(b) isNil(err, t) equals(len(b), n, t) existsWithContent(filename, b, t) existsWithContent(backupFileWithTime(dir, backupTimeFormat), start, t) fileCount(dir, 2, t) } func TestFirstWriteRotateBackupWithOrder(t *testing.T) { currentTime = time.Now dir := makeTempDir("TestFirstWriteRotateBackupWithOrder", t) defer os.RemoveAll(dir) filename := logFile(dir) l := &Logger{ Filename: filename, MaxBytes: 10, } defer l.Close() start := []byte("boooooo!") err := os.WriteFile(filename, start, 0600) isNil(err, t) // this would make us rotate b := []byte("fooo!") n, err := l.Write(b) isNil(err, t) equals(len(b), n, t) existsWithContent(filename, b, t) existsWithContent(backupFileWithOrder(dir, 1), start, t) fileCount(dir, 2, t) } func TestMaxBackupsWithTime(t *testing.T) { currentTime = fakeTime dir := makeTempDir("TestMaxBackupsWithTime", t) defer os.RemoveAll(dir) filename := logFile(dir) l := &Logger{ Filename: filename, FilenameTimeFormat: backupTimeFormat, MaxBytes: 10, MaxBackups: 1, } defer l.Close() b := []byte("boo!") n, err := l.Write(b) isNil(err, t) equals(len(b), n, t) existsWithContent(filename, b, t) fileCount(dir, 1, t) newFakeTime() // this will put us over the max b2 := []byte("foooooo!") n, err = l.Write(b2) isNil(err, t) equals(len(b2), n, t) // this will use the new fake time secondFilename := backupFileWithTime(dir, backupTimeFormat) existsWithContent(secondFilename, b, t) // make sure the old file still exists with the same content. existsWithContent(filename, b2, t) fileCount(dir, 2, t) newFakeTime() // this will make us rotate again b3 := []byte("baaaaaar!") n, err = l.Write(b3) isNil(err, t) equals(len(b3), n, t) // this will use the new fake time thirdFilename := backupFileWithTime(dir, backupTimeFormat) existsWithContent(thirdFilename, b2, t) existsWithContent(filename, b3, t) // should only have two files in the dir still fileCount(dir, 2, t) // second file name should still exist existsWithContent(thirdFilename, b2, t) // should have deleted the first backup notExist(secondFilename, t) // now test that we don't delete directories or non-logfile files newFakeTime() // 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 = 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 := backupFileWithTime(dir, backupTimeFormat) err = os.Mkdir(notlogfiledir, 0700) isNil(err, t) newFakeTime() // this will use the new fake time fourthFilename := backupFileWithTime(dir, backupTimeFormat) // 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 = os.WriteFile(compLogFile, []byte("compress"), 0644) isNil(err, t) // this will make us rotate again b4 := []byte("baaaaaaz!") n, err = l.Write(b4) isNil(err, t) equals(len(b4), n, t) existsWithContent(fourthFilename, b3, t) existsWithContent(fourthFilename+compressSuffix, []byte("compress"), t) // We should have four things in the directory now - the 2 log files, the // not log file, and the directory fileCount(dir, 5, t) // third file name should still exist existsWithContent(filename, b4, t) existsWithContent(fourthFilename, b3, t) // should have deleted the first filename notExist(thirdFilename, t) // the not-a-logfile should still exist exists(notlogfile, t) // the directory exists(notlogfiledir, t) } func TestMaxBackupsWithOrder(t *testing.T) { // TODO fix this test when https://github.com/fahedouch/go-logrotate/issues/11 is resolved t.Skip() currentTime = time.Now dir := makeTempDir("TestMaxBackupsWithOrder", t) defer os.RemoveAll(dir) filename := logFile(dir) l := &Logger{ Filename: filename, MaxBytes: 10, MaxBackups: 1, } defer l.Close() b := []byte("boo!") n, err := l.Write(b) isNil(err, t) equals(len(b), n, t) existsWithContent(filename, b, t) fileCount(dir, 1, t) // this will put us over the max b2 := []byte("foooooo!") n, err = l.Write(b2) isNil(err, t) equals(len(b2), n, t) secondFilename := backupFileWithOrder(dir, 1) existsWithContent(secondFilename, b, t) // make sure the old file still exists with the same content. existsWithContent(filename, b2, t) fileCount(dir, 2, t) // this will make us rotate again b3 := []byte("baaaaaar!") n, err = l.Write(b3) isNil(err, t) equals(len(b3), n, t) thirdFilename := backupFileWithOrder(dir, 2) existsWithContent(thirdFilename, b2, t) existsWithContent(filename, b3, t) // should only have two files in the dir still fileCount(dir, 2, t) // second file name should still exist existsWithContent(thirdFilename, b2, t) // should have deleted the first backup notExist(secondFilename, t) // now test that we don't delete directories or non-logfile files // 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) + ".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, 4) err = os.Mkdir(notlogfiledir, 0700) isNil(err, t) // this will use the new fake time 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 = os.WriteFile(compLogFile, []byte("compress"), 0644) isNil(err, t) // this will make us rotate again b4 := []byte("baaaaaaz!") n, err = l.Write(b4) isNil(err, t) equals(len(b4), n, t) existsWithContent(fourthFilename, b3, t) existsWithContent(fourthFilename+compressSuffix, []byte("compress"), t) // We should have four things in the directory now - the 2 log files, the // not log file, and the directory fileCount(dir, 5, t) // third file name should still exist existsWithContent(filename, b4, t) existsWithContent(fourthFilename, b3, t) // should have deleted the first filename notExist(thirdFilename, t) // the not-a-logfile should still exist exists(notlogfile, t) // the directory exists(notlogfiledir, 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 dir := makeTempDir("TestCleanupExistingBackupsWithTime", t) defer os.RemoveAll(dir) // make 3 backup files data := []byte("data") backup := backupFileWithTime(dir, backupTimeFormat) err := os.WriteFile(backup, data, 0644) isNil(err, t) newFakeTime() backup = backupFileWithTime(dir, backupTimeFormat) err = os.WriteFile(backup+compressSuffix, data, 0644) isNil(err, t) newFakeTime() backup = backupFileWithTime(dir, backupTimeFormat) err = os.WriteFile(backup, data, 0644) isNil(err, t) // now create a primary log file with some data filename := logFile(dir) err = os.WriteFile(filename, data, 0644) isNil(err, t) l := &Logger{ Filename: filename, FilenameTimeFormat: backupTimeFormat, MaxBytes: 10, MaxBackups: 1, } defer l.Close() newFakeTime() b2 := []byte("foooooo!") n, err := l.Write(b2) isNil(err, t) equals(len(b2), n, t) // now we should only have 2 files left - the primary and one backup fileCount(dir, 2, 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 = time.Now dir := makeTempDir("TestCleanupExistingBackupsWithOrder", t) defer os.RemoveAll(dir) // make 3 backup files data := []byte("data") backup := backupFileWithOrder(dir, 1) err := os.WriteFile(backup, data, 0644) isNil(err, t) backup = backupFileWithOrder(dir, 2) err = os.WriteFile(backup+compressSuffix, data, 0644) isNil(err, t) backup = backupFileWithOrder(dir, 3) err = os.WriteFile(backup, data, 0644) isNil(err, t) // now create a primary log file with some data filename := logFile(dir) err = os.WriteFile(filename, data, 0644) isNil(err, t) l := &Logger{ Filename: filename, MaxBytes: 10, MaxBackups: 1, } defer l.Close() b2 := []byte("foooooo!") n, err := l.Write(b2) isNil(err, t) equals(len(b2), n, t) // now we should only have 2 files left - the primary and one backup fileCount(dir, 2, t) } func TestMaxAgeOfBackupsWithTime(t *testing.T) { currentTime = fakeTime dir := makeTempDir(identifier(t), t) defer os.RemoveAll(dir) filename := logFile(dir) l := &Logger{ Filename: filename, FilenameTimeFormat: backupTimeFormat, MaxBytes: 10, MaxAge: 1, } defer l.Close() b := []byte("boo!") n, err := l.Write(b) isNil(err, t) equals(len(b), n, t) existsWithContent(filename, b, t) fileCount(dir, 1, t) // two days later newFakeTime() b2 := []byte("foooooo!") n, err = l.Write(b2) isNil(err, t) equals(len(b2), n, t) existsWithContent(backupFileWithTime(dir, backupTimeFormat), b, t) // We should still have 2 log files, since the most recent backup was just // created. fileCount(dir, 2, t) existsWithContent(filename, b2, t) // we should have deleted the old file due to being too old existsWithContent(backupFileWithTime(dir, backupTimeFormat), b, t) // two days later newFakeTime() b3 := []byte("baaaaar!") n, err = l.Write(b3) isNil(err, t) equals(len(b3), n, t) existsWithContent(backupFileWithTime(dir, backupTimeFormat), b2, t) // We should have 2 log files - the main log file, and the most recent // backup. The earlier backup is past the cutoff and should be gone. fileCount(dir, 2, t) existsWithContent(filename, b3, t) // we should have deleted the old file due to being too old existsWithContent(backupFileWithTime(dir, backupTimeFormat), b2, t) } // TODO TestMaxAgeOfBackupsWithOrder func TestOldLogFiles(t *testing.T) { currentTime = fakeTime dir := makeTempDir(identifier(t), t) defer os.RemoveAll(dir) filename := logFile(dir) data := []byte("data") err := os.WriteFile(filename, data, 07) isNil(err, t) backup := backupFileWithOrder(dir, 1) err = os.WriteFile(backup, data, 07) isNil(err, t) time.Sleep(1 * time.Second) backup2 := backupFileWithOrder(dir, 2) err = os.WriteFile(backup2, data, 07) isNil(err, t) l := &Logger{Filename: filename} files, err := l.oldLogFiles() isNil(err, t) equals(2, len(files), t) // should be sorted by newest file first assert(files[1].timestamp.Before(files[0].timestamp), t, "log files should be sorted by newest file first") } func TestTimeFromFileName(t *testing.T) { l := &Logger{Filename: "/var/log/myfoo/foo.log", FilenameTimeFormat: backupTimeFormat} prefix, ext := l.prefixAndExt() tests := []struct { filename string want time.Time wantErr bool }{ {"foo-2014-05-04T14-44-33.555.log", time.Date(2014, 5, 4, 14, 44, 33, 555000000, time.UTC), false}, {"foo-2014-05-04T14-44-33.555", time.Time{}, true}, {"2014-05-04T14-44-33.555.log", time.Time{}, true}, {"foo.log", time.Time{}, true}, } for _, test := range tests { got, err := l.timeFromName(test.filename, prefix, ext) equals(got, test.want, t) equals(err != nil, test.wantErr, t) } } func TestOrderFromFileName(t *testing.T) { l := &Logger{Filename: "/var/log/myfoo/foo.log"} prefix, ext := l.prefixAndExt() tests := []struct { filename string want int wantErr bool }{ {"foo.log.1", 1, false}, {"foo", 0, true}, {".log", 0, true}, {"foo.xls", 0, true}, } for _, test := range tests { got, err := l.orderFromName(test.filename, prefix, ext) equals(got, test.want, t) equals(err != nil, test.wantErr, t) } } func TestLocalTime(t *testing.T) { currentTime = fakeTime dir := makeTempDir(identifier(t), t) defer os.RemoveAll(dir) l := &Logger{ Filename: logFile(dir), FilenameTimeFormat: backupTimeFormat, MaxBytes: 10, LocalTime: true, } defer l.Close() b := []byte("boo!") n, err := l.Write(b) isNil(err, t) equals(len(b), n, t) b2 := []byte("fooooooo!") n2, err := l.Write(b2) isNil(err, t) equals(len(b2), n2, t) existsWithContent(logFile(dir), b2, t) existsWithContent(backupFileLocal(dir, backupTimeFormat), b, t) } func TestRotateBackupsWithTime(t *testing.T) { currentTime = fakeTime dir := makeTempDir(identifier(t), t) defer os.RemoveAll(dir) filename := logFile(dir) l := &Logger{ Filename: filename, FilenameTimeFormat: backupTimeFormat, MaxBackups: 1, MaxBytes: 100, // bytes } defer l.Close() b := []byte("boo!") n, err := l.Write(b) isNil(err, t) equals(len(b), n, t) existsWithContent(filename, b, t) fileCount(dir, 1, t) newFakeTime() err = l.Rotate() isNil(err, t) filename2 := backupFileWithTime(dir, backupTimeFormat) existsWithContent(filename2, b, t) existsWithContent(filename, []byte{}, t) fileCount(dir, 2, t) newFakeTime() err = l.Rotate() isNil(err, t) filename3 := backupFileWithTime(dir, backupTimeFormat) existsWithContent(filename3, []byte{}, t) existsWithContent(filename, []byte{}, t) fileCount(dir, 2, t) b2 := []byte("foooooo!") n, err = l.Write(b2) isNil(err, t) equals(len(b2), n, t) // this will use the new fake time existsWithContent(filename, b2, t) } func TestRotateBackupsWithOrder(t *testing.T) { currentTime = time.Now dir := makeTempDir(identifier(t), t) defer os.RemoveAll(dir) filename := logFile(dir) l := &Logger{ Filename: filename, MaxBackups: 3, MaxBytes: 100, // bytes } defer l.Close() b := []byte("boo!") n, err := l.Write(b) isNil(err, t) equals(len(b), n, t) existsWithContent(filename, b, t) fileCount(dir, 1, t) err = l.Rotate() isNil(err, t) filename1 := backupFileWithOrder(dir, 1) existsWithContent(filename1, b, t) existsWithContent(filename, []byte{}, t) fileCount(dir, 2, t) err = l.Rotate() isNil(err, t) filename2 := backupFileWithOrder(dir, 2) existsWithContent(filename1, b, t) existsWithContent(filename2, []byte{}, t) existsWithContent(filename, []byte{}, t) fileCount(dir, 3, t) b2 := []byte("foooooo!") n, err = l.Write(b2) isNil(err, t) equals(len(b2), n, t) // this will use the new fake time existsWithContent(filename, b2, t) } func TestCompressBackupsWithTimeOnRotate(t *testing.T) { currentTime = fakeTime dir := makeTempDir(identifier(t), t) defer os.RemoveAll(dir) filename := logFile(dir) l := &Logger{ Compress: true, Filename: filename, FilenameTimeFormat: backupTimeFormat, MaxBytes: 10, } defer l.Close() b := []byte("boo!") n, err := l.Write(b) isNil(err, t) equals(len(b), n, t) existsWithContent(filename, b, t) fileCount(dir, 1, t) newFakeTime() err = l.Rotate() isNil(err, t) // the old logfile should be moved aside and the main logfile should have // nothing in it. existsWithContent(filename, []byte{}, t) // a compressed version of the log file should now exist and the original // should have been removed. bc := new(bytes.Buffer) gz := gzip.NewWriter(bc) _, err = gz.Write(b) isNil(err, t) err = gz.Close() isNil(err, t) existsWithContent(backupFileWithTime(dir, backupTimeFormat)+compressSuffix, bc.Bytes(), t) notExist(backupFileWithTime(dir, backupTimeFormat), t) fileCount(dir, 2, t) } func TestCompressBackupsWithOrderOnRotate(t *testing.T) { currentTime = time.Now dir := makeTempDir(identifier(t), t) defer os.RemoveAll(dir) filename := logFile(dir) l := &Logger{ Compress: true, Filename: filename, MaxBytes: 10, } defer l.Close() b := []byte("boo!") n, err := l.Write(b) isNil(err, t) equals(len(b), n, t) existsWithContent(filename, b, t) fileCount(dir, 1, t) err = l.Rotate() isNil(err, t) // the old logfile should be moved aside and the main logfile should have // nothing in it. existsWithContent(filename, []byte{}, t) // a compressed version of the log file should now exist and the original // should have been removed. bc := new(bytes.Buffer) gz := gzip.NewWriter(bc) _, err = gz.Write(b) isNil(err, t) err = gz.Close() isNil(err, t) existsWithContent(backupFileWithOrder(dir, 1)+compressSuffix, bc.Bytes(), t) notExist(backupFileWithOrder(dir, 1), t) fileCount(dir, 2, t) } func TestCompressOnResume(t *testing.T) { currentTime = fakeTime dir := makeTempDir(identifier(t), t) defer os.RemoveAll(dir) filename := logFile(dir) l := &Logger{ FilenameTimeFormat: backupTimeFormat, Compress: true, Filename: filename, MaxBytes: 10, } defer l.Close() // Create a backup file and empty "compressed" file. filename2 := backupFileWithTime(dir, backupTimeFormat) b := []byte("foo!") err := os.WriteFile(filename2, b, 0644) isNil(err, t) err = os.WriteFile(filename2+compressSuffix, []byte{}, 0644) isNil(err, t) newFakeTime() b2 := []byte("boo!") n, err := l.Write(b2) isNil(err, t) equals(len(b2), n, t) existsWithContent(filename, b2, t) // we need to wait a little bit since the files get compressed on a different // goroutine. <-time.After(300 * time.Millisecond) // The write should have started the compression - a compressed version of // the log file should now exist and the original should have been removed. bc := new(bytes.Buffer) gz := gzip.NewWriter(bc) _, err = gz.Write(b) isNil(err, t) err = gz.Close() isNil(err, t) existsWithContent(filename2+compressSuffix, bc.Bytes(), t) notExist(filename2, t) fileCount(dir, 2, t) } func TestJson(t *testing.T) { data := []byte(` { "filename": "foo", "maxbytes": 5, "maxage": 10, "maxbackups": 3, "localtime": true, "compress": true }`[1:]) l := Logger{} err := json.Unmarshal(data, &l) isNil(err, t) equals("foo", l.Filename, t) equals(int64(5), l.MaxBytes, t) equals(10, l.MaxAge, t) equals(3, l.MaxBackups, t) equals(true, l.LocalTime, t) equals(true, l.Compress, t) } func TestYaml(t *testing.T) { data := []byte(` filename: foo maxbytes: 5 maxage: 10 maxbackups: 3 localtime: true compress: true`[1:]) l := Logger{} err := yaml.Unmarshal(data, &l) isNil(err, t) equals("foo", l.Filename, t) equals(int64(5), l.MaxBytes, t) equals(10, l.MaxAge, t) equals(3, l.MaxBackups, t) equals(true, l.LocalTime, t) equals(true, l.Compress, t) } func TestToml(t *testing.T) { data := ` filename = "foo" maxbytes = 5 maxage = 10 maxbackups = 3 localtime = true compress = true`[1:] l := Logger{} md, err := toml.Decode(data, &l) isNil(err, t) equals("foo", l.Filename, t) equals(int64(5), l.MaxBytes, t) equals(10, l.MaxAge, t) equals(3, l.MaxBackups, t) equals(true, l.LocalTime, t) equals(true, l.Compress, t) equals(0, len(md.Undecoded()), t) } // makeTempDir creates a temporary directory func makeTempDir(name string, t testing.TB) string { dir := filepath.Join(os.TempDir(), name) isNilUp(os.Mkdir(dir, 0700), t, 1) return dir } // existsWithContent checks that the given file exists and has the correct content. func existsWithContent(path string, content []byte, t testing.TB) { info, err := os.Stat(path) isNilUp(err, t, 1) equalsUp(int64(len(content)), info.Size(), t, 1) b, err := os.ReadFile(path) isNilUp(err, t, 1) equalsUp(content, b, t, 1) } // logFile returns the current log file name in the given directory. func logFile(dir string) string { return filepath.Join(dir, "foobar.log") } func backupFileWithOrder(dir string, order int) string { return filepath.Join(dir, fmt.Sprintf("foobar.log.%d", order)) } func backupFileWithTime(dir string, timeFormat string) string { return filepath.Join(dir, "foobar-"+fakeTime().UTC().Format(timeFormat)+".log") } func backupFileLocal(dir string, timeFormat string) string { return filepath.Join(dir, "foobar-"+fakeTime().Format(timeFormat)+".log") } // logFileLocal returns the log file name in the given directory for the current // fake time using the local timezone. /*func logFileLocal(dir string) string { return filepath.Join(dir, fakeTime().Format(backupTimeFormat)) }*/ // fileCount checks that the number of files in the directory is exp. func fileCount(dir string, exp int, t testing.TB) { files, err := os.ReadDir(dir) isNilUp(err, t, 1) // Make sure no other files were created. equalsUp(exp, len(files), t, 1) } // newFakeTime sets the fake "current time" to two days later. func newFakeTime() { fakeCurrentTime = fakeCurrentTime.Add(time.Hour * 24 * 2) } func notExist(path string, t testing.TB) { _, err := os.Stat(path) assertUp(os.IsNotExist(err), t, 1, "expected to get os.IsNotExist, but instead got %v", err) } func exists(path string, t testing.TB) { _, err := os.Stat(path) assertUp(err == nil, t, 1, "expected file to exist, but got error from os.Stat: %v", err) } go-logrotate-0.2.1/logrotate_windows.go000066400000000000000000000001371460617275600202350ustar00rootroot00000000000000package logrotate import ( "os" ) func chown(_ string, _ os.FileInfo) error { return nil } go-logrotate-0.2.1/testing_test.go000066400000000000000000000060331460617275600172000ustar00rootroot00000000000000package logrotate import ( "fmt" "path/filepath" "reflect" "runtime" "strings" "testing" ) // identifier can be used as a name of folder(s) etc. func identifier(t testing.TB) string { s := t.Name() s = strings.ReplaceAll(s, " ", "_") s = strings.ReplaceAll(s, "/", "-") s = strings.ToLower(s) s = "logrotate-" + s return s } // assert will log the given message if condition is false. func assert(condition bool, t testing.TB, msg string, v ...interface{}) { assertUp(condition, t, 1, msg, v...) } // assertUp is like assert, but used inside helper functions, to ensure that // the file and line number reported by failures corresponds to one or more // levels up the stack. func assertUp(condition bool, t testing.TB, caller int, msg string, v ...interface{}) { if !condition { _, file, line, _ := runtime.Caller(caller + 1) v = append([]interface{}{filepath.Base(file), line}, v...) fmt.Printf("%s:%d: "+msg+"\n", v...) t.FailNow() } } // equals tests that the two values are equal according to reflect.DeepEqual. func equals(exp, act interface{}, t testing.TB) { equalsUp(exp, act, t, 1) } // equalsUp is like equals, but used inside helper functions, to ensure that the // file and line number reported by failures corresponds to one or more levels // up the stack. func equalsUp(exp, act interface{}, t testing.TB, caller int) { if !reflect.DeepEqual(exp, act) { _, file, line, _ := runtime.Caller(caller + 1) fmt.Printf("%s:%d: exp: %v (%T), got: %v (%T)\n", filepath.Base(file), line, exp, exp, act, act) t.FailNow() } } // isNil reports a failure if the given value is not nil. Note that values // which cannot be nil will always fail this check. func isNil(obtained interface{}, t testing.TB) { isNilUp(obtained, t, 1) } // isNilUp is like isNil, but used inside helper functions, to ensure that the // file and line number reported by failures corresponds to one or more levels // up the stack. func isNilUp(obtained interface{}, t testing.TB, caller int) { if !_isNil(obtained) { _, file, line, _ := runtime.Caller(caller + 1) fmt.Printf("%s:%d: expected nil, got: %v\n", filepath.Base(file), line, obtained) t.FailNow() } } // notNil reports a failure if the given value is nil. func notNil(obtained interface{}, t testing.TB) { notNilUp(obtained, t, 1) } // notNilUp is like notNil, but used inside helper functions, to ensure that the // file and line number reported by failures corresponds to one or more levels // up the stack. func notNilUp(obtained interface{}, t testing.TB, caller int) { if _isNil(obtained) { _, file, line, _ := runtime.Caller(caller + 1) fmt.Printf("%s:%d: expected non-nil, got: %v\n", filepath.Base(file), line, obtained) t.FailNow() } } // _isNil is a helper function for isNil and notNil, and should not be used // directly. func _isNil(obtained interface{}) bool { if obtained == nil { return true } switch v := reflect.ValueOf(obtained); v.Kind() { case reflect.Chan, reflect.Func, reflect.Interface, reflect.Map, reflect.Ptr, reflect.Slice: return v.IsNil() } return false }