rotatelog

package
v2.1.1+incompatible Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jun 4, 2024 License: MIT, MIT Imports: 12 Imported by: 0

README

Rotatelog Hooks for Logrus

Usage

import (
  "time"

  "github.com/surryaadii/logrus"
  rlog "github.com/surryaadii/logrus/hooks/rotatelog"
)

func main() {
  log := logrus.New()
  hook, err := rlog.NewHook("./access_log.%Y%m%d",
    //rotatelog.WithLinkName("./access_log"),
    rotatelog.WithMaxAge(24 * time.Hour),
    rotatelog.WithRotationTime(time.Hour),
    rotatelog.WithClock(rotatelog.UTC))

  if err != nil {
    log.Hooks.Add(hook)
  }
}

DESCRIPTION

When you integrate this to to you app, it automatically write to logs that are rotated from within the app: No more disk-full alerts because you forgot to setup logrotate!

To install, simply issue a go get:

go get "github.com/surryaadii/logrus/hooks/rotatelog

OPTIONS

Pattern (Required)

The pattern used to generate actual log file names. You should use patterns using the strftime (3) format. For example:

  rotatelog.New("/var/log/myapp/log.%Y%m%d")

Clock (default: rotatelog.Local)

You may specify an object that implements the roatatelogs.Clock interface. When this option is supplied, it's used to determine the current time to base all of the calculations on. For example, if you want to base your calculations in UTC, you may specify rotatelog.UTC

  rotatelog.New(
    "/var/log/myapp/log.%Y%m%d",
    rotatelog.WithClock(rotatelog.UTC),
  )

Location

This is an alternative to the WithClock option. Instead of providing an explicit clock, you can provide a location for you times. We will create a Clock object that produces times in your specified location, and configure the rotatelog to respect it.

LinkName (default: "")

Path where a symlink for the actual log file is placed. This allows you to always check at the same location for log files even if the logs were rotated

  rotatelog.New(
    "/var/log/myapp/log.%Y%m%d",
    rotatelog.WithLinkName("/var/log/myapp/current"),
  )
  // Else where
  $ tail -f /var/log/myapp/current

If not provided, no link will be written.

RotationTime (default: 86400 sec)

Interval between file rotation. By default logs are rotated every 86400 seconds. Note: Remember to use time.Duration values.

  // Rotate every hour
  rotatelog.New(
    "/var/log/myapp/log.%Y%m%d",
    rotatelog.WithRotationTime(time.Hour),
  )

MaxAge (default: 7 days)

Time to wait until old logs are purged. By default no logs are purged, which certainly isn't what you want. Note: Remember to use time.Duration values.

  // Purge logs older than 1 hour
  rotatelog.New(
    "/var/log/myapp/log.%Y%m%d",
    rotatelog.WithMaxAge(time.Hour),
  )

RotationCount (default: -1)

The number of files should be kept. By default, this option is disabled.

Note: MaxAge should be disabled by specifing WithMaxAge(-1) explicitly.

  // Purge logs except latest 7 files
  rotatelog.New(
    "/var/log/myapp/log.%Y%m%d",
    rotatelog.WithMaxAge(-1),
    rotatelog.WithRotationCount(7),
  )

Handler (default: nil)

Sets the event handler to receive event notifications from the RotateLog object. Currently only supported event type is FiledRotated

  rotatelog.New(
    "/var/log/myapp/log.%Y%m%d",
    rotatelog.Handler(rotatelog.HandlerFunc(func(e Event) {
      if e.Type() != rotatelog.FileRotatedEventType {
        return
      }

      // Do what you want with the data. This is just an idea:
      storeLogFileToRemoteStorage(e.(*FileRotatedEvent).PreviousFile())
    })),
  )

Rotating files forcefully

If you want to rotate files forcefully before the actual rotation time has reached, you may use the Rotate() method. This method forcefully rotates the logs, but if the generated file name clashes, then a numeric suffix is added so that the new file will forcefully appear on disk.

For example, suppose you had a pattern of '%Y.log' with a rotation time of 86400 so that it only gets rotated every year, but for whatever reason you wanted to rotate the logs now, you could install a signal handler to trigger this rotation:

rl := rotatelog.New(...)

signal.Notify(ch, syscall.SIGHUP)

go func(ch chan os.Signal) {
  <-ch
  rl.Rotate()
}()

And you will get a log file name in like 2018.log.1, 2018.log.2, etc.

Other

Thanks lestrrat-go.

Documentation

Overview

package rotatelog is a port of File-RotateLog from Perl (https://metacpan.org/release/File-RotateLog), and it allows you to automatically rotate output files when you write to them according to the filename pattern that you can specify.

Index

Constants

View Source
const (
	OptKeyClock         = "clock"
	OptKeyLinkName      = "link-name"
	OptKeyMaxAge        = "max-age"
	OptKeyRotationTime  = "rotation-time"
	OptKeyRotationCount = "rotation-count"
)

Variables

View Source
var Local = clockFn(time.Now)

Local is an object satisfying the Clock interface, which returns the current time in the local timezone

View Source
var UTC = clockFn(func() time.Time { return time.Now().UTC() })

UTC is an object satisfying the Clock interface, which returns the current time in UTC

Functions

This section is empty.

Types

type Clock

type Clock interface {
	Now() time.Time
}

Clock is the interface used by the RotateLog object to determine the current time

type Option

type Option interface {
	Name() string
	Value() interface{}
}

Option is used to pass optional arguments to the RotateLog constructor

func WithClock

func WithClock(c Clock) Option

WithClock creates a new Option that sets a clock that the RotateLogs object will use to determine the current time.

By default rotatelogs.Local, which returns the current time in the local time zone, is used. If you would rather use UTC, use rotatelogs.UTC as the argument to this option, and pass it to the constructor.

func WithLinkName

func WithLinkName(s string) Option

WithLinkName creates a new Option that sets the symbolic link name that gets linked to the current file name being used.

func WithLocation

func WithLocation(loc *time.Location) Option

WithLocation creates a new Option that sets up a "Clock" interface that the RotateLogs object will use to determine the current time.

This optin works by always returning the in the given location.

func WithMaxAge

func WithMaxAge(d time.Duration) Option

WithMaxAge creates a new Option that sets the max age of a log file before it gets purged from the file system.

func WithRotationCount

func WithRotationCount(n uint) Option

WithRotationCount creates a new Option that sets the number of files should be kept before it gets purged from the file system.

func WithRotationTime

func WithRotationTime(d time.Duration) Option

WithRotationTime creates a new Option that sets the time between rotation.

type RotateLog

type RotateLog struct {
	// contains filtered or unexported fields
}

RotateLog represents a log file that gets automatically rotated as you write to it.

func New

func New(p string, options ...Option) (*RotateLog, error)

New creates a new RotateLog object. A log filename pattern must be passed. Optional `Option` parameters may be passed

func (*RotateLog) Close

func (rl *RotateLog) Close() error

Close satisfies the io.Closer interface. You must call this method if you performed any writes to the object.

func (*RotateLog) CurrentFileName

func (rl *RotateLog) CurrentFileName() string

CurrentFileName returns the current file name that the RotateLog object is writing to

func (*RotateLog) Rotate

func (rl *RotateLog) Rotate() error

Rotate forcefully rotates the log files. If the generated file name clash because file already exists, a numeric suffix of the form ".1", ".2", ".3" and so forth are appended to the end of the log file

Thie method can be used in conjunction with a signal handler so to emulate servers that generate new log files when they receive a SIGHUP

func (*RotateLog) Write

func (rl *RotateLog) Write(p []byte) (n int, err error)

Write satisfies the io.Writer interface. It writes to the appropriate file handle that is currently being used. If we have reached rotation time, the target file gets automatically rotated, and also purged if necessary.

type RotatelogHook

type RotatelogHook struct {
	// contains filtered or unexported fields
}

SyslogHook to send logs via syslog.

func NewHook

func NewHook(p string, options ...Option) (*RotatelogHook, error)

Creates a hook to be added to an instance of logger. This is called with `hook, err := NewHook("./access_log.%Y%m%d",

WithLinkName("./access_log"),
WithMaxAge(24 * time.Hour),
WithRotationTime(time.Hour),
WithClock(UTC))`

`if err == nil { log.Hooks.Add(hook.SetFormatter(&logrus.JSONFormatter{})) }`

func (*RotatelogHook) Close

func (hook *RotatelogHook) Close() error

func (*RotatelogHook) Fire

func (hook *RotatelogHook) Fire(entry *logrus.Entry) error

func (*RotatelogHook) Levels

func (hook *RotatelogHook) Levels() []logrus.Level

func (*RotatelogHook) SetFormatter

func (hook *RotatelogHook) SetFormatter(formatter logrus.Formatter) *RotatelogHook

Directories

Path Synopsis
internal

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL