2022-11-26 20:45:32 +00:00
|
|
|
package file
|
|
|
|
|
|
|
|
import (
|
|
|
|
"fmt"
|
2022-12-06 21:45:50 +00:00
|
|
|
"io"
|
2022-11-26 20:45:32 +00:00
|
|
|
"os"
|
|
|
|
"path/filepath"
|
|
|
|
"time"
|
|
|
|
|
|
|
|
"github.com/juju/errors"
|
|
|
|
"github.com/sirupsen/logrus"
|
2022-12-06 21:45:50 +00:00
|
|
|
|
|
|
|
rotatelogs "github.com/lestrrat-go/file-rotatelogs"
|
2022-11-26 20:45:32 +00:00
|
|
|
)
|
|
|
|
|
2022-12-06 21:45:50 +00:00
|
|
|
// NewHook will create a File Hook for logrus.
|
2022-11-26 20:45:32 +00:00
|
|
|
func NewHook(c *ConfigStruct) (logrus.Hook, error) {
|
|
|
|
|
|
|
|
err := c.IsValid()
|
|
|
|
if err != nil {
|
|
|
|
return nil, errors.Trace(err)
|
|
|
|
}
|
|
|
|
|
2022-12-06 21:45:50 +00:00
|
|
|
var w io.Writer
|
|
|
|
if c.Rotate {
|
|
|
|
rotateTime, _ := time.ParseDuration(*c.RotateTime)
|
2022-11-26 20:45:32 +00:00
|
|
|
|
2022-12-06 21:45:50 +00:00
|
|
|
// let's construct log rotator options
|
|
|
|
rotateOptions := []rotatelogs.Option{
|
|
|
|
rotatelogs.WithLinkName(c.Filename),
|
|
|
|
rotatelogs.WithRotationTime(rotateTime),
|
|
|
|
}
|
2022-11-26 20:45:32 +00:00
|
|
|
|
2022-12-06 21:45:50 +00:00
|
|
|
if c.RotateMaxAge != nil {
|
|
|
|
rotateMaxAge, _ := time.ParseDuration(*c.RotateMaxAge)
|
|
|
|
rotateOptions = append(rotateOptions, rotatelogs.WithMaxAge(rotateMaxAge))
|
|
|
|
} else if c.RotateMaxFile != nil {
|
|
|
|
rotateOptions = append(
|
|
|
|
rotateOptions,
|
|
|
|
rotatelogs.WithRotationCount(uint(*c.RotateMaxFile)),
|
|
|
|
rotatelogs.WithMaxAge(-1),
|
|
|
|
)
|
|
|
|
}
|
2022-11-26 20:45:32 +00:00
|
|
|
|
2022-12-06 21:45:50 +00:00
|
|
|
w, err = rotatelogs.New(
|
|
|
|
fmt.Sprintf("%s.%%Y%%m%%d%%H%%M", c.Filename),
|
|
|
|
rotateOptions...,
|
|
|
|
)
|
|
|
|
if err != nil {
|
|
|
|
return nil, errors.Trace(err)
|
2022-11-26 20:45:32 +00:00
|
|
|
}
|
|
|
|
|
2022-12-06 21:45:50 +00:00
|
|
|
} else {
|
|
|
|
dirname := filepath.Dir(c.Filename)
|
|
|
|
if err := os.MkdirAll(dirname, 0750); err != nil {
|
|
|
|
return nil, errors.NewNotSupported(err, fmt.Sprintf("failed to create directory %s", dirname))
|
|
|
|
}
|
2022-11-26 20:45:32 +00:00
|
|
|
|
2022-12-06 21:45:50 +00:00
|
|
|
// if we got here, then we need to create a file
|
|
|
|
fh, err := os.OpenFile(c.Filename, os.O_CREATE|os.O_APPEND|os.O_WRONLY, 0600)
|
|
|
|
if err != nil {
|
|
|
|
return nil, errors.NewNotSupported(err, fmt.Sprintf("failed to open file %s", c.Filename))
|
|
|
|
}
|
2022-11-26 20:45:32 +00:00
|
|
|
|
2022-12-06 21:45:50 +00:00
|
|
|
w = fh
|
2022-11-26 20:45:32 +00:00
|
|
|
}
|
|
|
|
|
2022-12-06 21:45:50 +00:00
|
|
|
h := NewAsyncFileHook(w)
|
|
|
|
|
|
|
|
return h, nil
|
2022-11-26 20:45:32 +00:00
|
|
|
}
|