diff --git a/.gitignore b/.gitignore index 5761abc..afebcf2 100644 --- a/.gitignore +++ b/.gitignore @@ -1 +1,2 @@ *.o +fs/logs/** diff --git a/dateconv/duration.go b/dateconv/duration.go new file mode 100644 index 0000000..7bea142 --- /dev/null +++ b/dateconv/duration.go @@ -0,0 +1,11 @@ +package dateconv + +import "time" + +func ParseDuration(s string) (time.Duration, error) { + if len(s) == 0 { + return time.Duration(0), nil + } + + return time.ParseDuration(s) +} diff --git a/dateconv/duration_test.go b/dateconv/duration_test.go new file mode 100644 index 0000000..770bbc1 --- /dev/null +++ b/dateconv/duration_test.go @@ -0,0 +1,10 @@ +package dateconv + +import ( + "testing" +) + +func TestParseDuration(t *testing.T) { + t.Log(ParseDuration("")) + t.Log(ParseDuration("abc")) +} diff --git a/fs/fs.go b/fs/fs.go index 88cb0ab..f0eae3a 100644 --- a/fs/fs.go +++ b/fs/fs.go @@ -1,7 +1,9 @@ package fs import ( + "io" "os" + "path/filepath" ) func IsExist(path string) bool { @@ -17,3 +19,14 @@ func IsDir(path string) bool { return file.IsDir() } + +// 打开或新建文件,目录不存在时创建目录 +func OpenOrNew(filename string) (io.Writer, error) { + dir := filepath.Dir(filename) + if !IsExist(dir) { + os.MkdirAll(dir, 0744) + } + + mode := os.FileMode(0644) + return os.OpenFile(filename, os.O_CREATE|os.O_WRONLY|os.O_APPEND, mode) +} diff --git a/fs/fs_test.go b/fs/fs_test.go new file mode 100644 index 0000000..5265227 --- /dev/null +++ b/fs/fs_test.go @@ -0,0 +1,7 @@ +package fs + +import "testing" + +func TestOpenFile(t *testing.T) { + OpenOrNew("logs/aaa.log") +} diff --git a/json/jsoniter.go b/json/jsoniter.go index c460b42..1deabf3 100644 --- a/json/jsoniter.go +++ b/json/jsoniter.go @@ -8,7 +8,7 @@ import ( "github.com/json-iterator/go/extra" ) -func init() { +func RegisterFuzzyDecoders() { extra.RegisterFuzzyDecoders() } diff --git a/logx/logrus_options.go b/logx/logrus_options.go index 0c09145..fa06663 100644 --- a/logx/logrus_options.go +++ b/logx/logrus_options.go @@ -5,6 +5,7 @@ import ( "log" "os" + "github.com/charlienet/go-mixed/fs" "github.com/sirupsen/logrus" "gopkg.in/natefinch/lumberjack.v2" ) @@ -68,9 +69,10 @@ func WithOutput(options LogrusOutputOptions) logrusOption { return func(l *logrus.Logger) { var writer io.Writer switch { - case options.Output == File, len(options.FileName) > 0: + case options.Output == File && len(options.FileName) > 0: + // 设置输出为文件,并且已经设置文件名 writer = createFileWriter(options) - case options.Output == Both: + case options.Output == Both && len(options.FileName) > 0: writer = io.MultiWriter(os.Stdout, createFileWriter(options)) default: writer = os.Stdout @@ -92,7 +94,7 @@ func createFileWriter(options LogrusOutputOptions) io.Writer { } } - f, err := os.OpenFile(options.FileName, os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0666) + f, err := fs.OpenOrNew(options.FileName) if err != nil { log.Panic(err) }