Giter Site home page Giter Site logo

logrus_mate's Introduction

Logrus Mate :walrus:

Logrus mate is a tool for Logrus, it will help you to initial logger by config, including Formatter, HookLevel and Output .

If you more prefer old version, you could checkout tag v1.0.0

Example

Example 1:

Hijack logrus.StandardLogger()

package main

import (
    "github.com/sirupsen/logrus"
    "github.com/gogap/logrus_mate"
)

func main() {
    logrus_mate.Hijack(
        logrus.StandardLogger(),
        logrus_mate.ConfigString(
            `{formatter.name = "json"}`,
        ),
    )
    
    logrus.WithField("Field", "A").Debugln("Hello JSON")
}

Example 2:

Create new logger from mate:

package main

import (
    "github.com/gogap/logrus_mate"
)

func main() {
    mate, _ := logrus_mate.NewLogrusMate(
        logrus_mate.ConfigString(
            `{ mike {formatter.name = "json"} }`,
        ),
    )
    
    mikeLoger := mate.Logger("mike")
    mikeLoger.Errorln("Hello Error Level from Mike and my formatter is json")
}

Example 3:

Hi jack logger by mate

package main

import (
    "github.com/sirupsen/logrus"
    "github.com/gogap/logrus_mate"
)

func main() {
    mate, _ := logrus_mate.NewLogrusMate(
        logrus_mate.ConfigString(
            `{ mike {formatter.name = "json"} }`,
        ),
    )

    mate.Hijack(
        logrus.StandardLogger(),
        "mike",
    )
    
    logrus.Println("hello std logger is hijack by mike")
}

Example 4:

Fallback the ConfigString

package main

import (
    "github.com/sirupsen/logrus"
    "github.com/gogap/logrus_mate"
)

func main() {
    mate, _ := logrus_mate.NewLogrusMate(
        logrus_mate.ConfigString(
            `{ mike {formatter.name = "json"} }`,
        ),
        logrus_mate.ConfigFile(
            "mate.conf", // { mike {formatter.name = "text"} }
        ),
    )

    mate.Hijack(
        logrus.StandardLogger(),
        "mike",
    )
    
    logrus.Println("hello std logger is hijack by mike")
}

the json formatter is used

Example 5:

Fallback config while hijack

package main

import (
    "github.com/sirupsen/logrus"
    "github.com/gogap/logrus_mate"
)

func main() {
    mate, _ := logrus_mate.NewLogrusMate(
        logrus_mate.ConfigFile(
            "mate.conf", // { mike {formatter.name = "text"} }
        ),
    )

    mate.Hijack(logrus.StandardLogger(),
        "mike",
        logrus_mate.ConfigString(
            `{formatter.name = "json"}`,
        ),
    )

    logrus.Errorln("hello std logger is hijack by mike")
}

the json formatter is used

currently we are using https://github.com/go-akka/configuration for logger config, it will more powerful config format for human read, you also could set your own config provider

Hooks

Hook Options
Airbrake project-id api-key env
Syslog network address priority tag
BugSnag api-key
Slackrus url levels channel emoji username
Graylog address facility extra
Mail app-name host port from to username password
File filename max-lines max-size daily max-days rotate level
BearyChat url levels channel user markdown async
LFSHook path-map { error = "logs/error.log" ... }
sls README

When we need use above hooks, we need import these package as follow:

import _ "github.com/gogap/logrus_mate/hooks/syslog"
import _ "github.com/gogap/logrus_mate/hooks/mail"

If you want write your own hook, you just need todo as follow:

package myhook

import (
    "github.com/gogap/logrus_mate"
)

type MyHookConfig struct {
    Address  string
}

func init() {
    logrus_mate.RegisterHook("myhook", NewMyHook)
}

func NewMyHook(config logrus_mate.Configuration) (hook logrus.Hook, err error) {
    conf := MyHookConfig{}
    if config!=nil {
        conf.Address = config.GetString("address")
    }

    // write your hook logic code here

    return
}

Formatters

internal formatters:

Formatter Options Output Example
null
text force-colors disable-colors disable-timestamp full-timestamp timestamp-format disable-sorting DEBU[0000] Hello Default Logrus Mate
json timestamp-format {"level":"info","msg":"Hello, I am A Logger from jack","time":"2015-10-18T21:24:19+08:00"}

3rd formatters:

Formatter Output Example
logstash [Removed]

When we need use 3rd formatter, we need import these package as follow:

import _ "github.com/gogap/logrus_mate/formatters/xxx"

If you want write your own formatter, you just need todo as follow:

package myformatter

import (
    "github.com/gogap/logrus_mate"
)

type MyFormatterConfig struct {
    Address  string `json:"address"`
}

func init() {
    logrus_mate.RegisterFormatter("myformatter", NewMyFormatter)
}

func NewMyFormatter(config logrus_mate.Configuration) (formatter logrus.Formatter, err error) {
    conf := MyFormatterConfig{}
    if config!=nil {
        conf.Address=config.GetString("address")
    }

    // write your formatter logic code here

    return
}

Writers

internal writers (output):

  • stdout
  • stderr
  • null

3rd writers:

Writer Description
redisio just for demo, it will output into redis, the key type is list
rotatelogs write log to file , configs: clock location link-name rotation-time max-age

When we need use 3rd writer, we need import these package as follow:

import _ "github.com/gogap/logrus_mate/writers/redisio"

If you want write your own writer, you just need todo as follow:

package mywriter

import (
    "io"

    "github.com/gogap/logrus_mate"
)

type MyWriterConfig struct {
    Address  string `json:"address"`
}

func init() {
    logrus_mate.RegisterWriter("mywriter", NewMyWriter)
}

func NewMyWriter(config logrus_mate.Configuration) (writer io.Writer, err error) {
    conf := MyWriterConfig{}
    if config!=nil {
        conf.Address=config.GetString("address")
    }

    // write your writer logic code here

    return
}

Config Provider

The default config provider is HOCON, you could use your own config provider, just implement the following interface{}

type ConfigurationProvider interface {
    LoadConfig(filename string) Configuration
    ParseString(cfgStr string) Configuration
}

type Configuration interface {
    GetBoolean(path string, defaultVal ...bool) bool
    GetByteSize(path string) *big.Int
    GetInt32(path string, defaultVal ...int32) int32
    GetInt64(path string, defaultVal ...int64) int64
    GetString(path string, defaultVal ...string) string
    GetFloat32(path string, defaultVal ...float32) float32
    GetFloat64(path string, defaultVal ...float64) float64
    GetTimeDuration(path string, defaultVal ...time.Duration) time.Duration
    GetTimeDurationInfiniteNotAllowed(path string, defaultVal ...time.Duration) time.Duration
    GetBooleanList(path string) []bool
    GetFloat32List(path string) []float32
    GetFloat64List(path string) []float64
    GetInt32List(path string) []int32
    GetInt64List(path string) []int64
    GetByteList(path string) []byte
    GetStringList(path string) []string
    GetConfig(path string) Configuration
    WithFallback(fallback Configuration)
    HasPath(path string) bool
    Keys() []string
}

set your own config provider

package main

import (
    "github.com/gogap/config"
    "github.com/gogap/logrus_mate"
    "github.com/sirupsen/logrus"
)

func main() {
    mate, _ := logrus_mate.NewLogrusMate(
        logrus_mate.ConfigString(
            `{ mike {formatter.name = "json"} }`,
        ),
        logrus_mate.ConfigFile(
            "mate.conf", // { mike {formatter.name = "text"} }
        ),
        logrus_mate.ConfigProvider(
            &config.HOCONConfigProvider{}, // this is defualt provider if you did not configurate
        ),
    )

    mate.Hijack(
        logrus.StandardLogger(),
        "mike",
    )

    logrus.Println("hello std logger is hijack by mike")
}

logrus_mate's People

Contributors

alexsn avatar anton-sergeev avatar ibradypod avatar recallsong avatar sintell avatar xujinzheng avatar ydcool avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

logrus_mate's Issues

按日切割和按大小切割同时打开的时候,历史Log日期错误

_20180703100818

if w.MaxLines > 0 || w.MaxSize > 0 {
		for ; err == nil && num <= 999; num++ {
			fName = w.fileNameOnly + fmt.Sprintf(".%s.%03d%s", logTime.Format("2006-01-02"), num, w.suffix)//这块用的Logtime 是新一天的日期 应该用dailyOpenTime?
			_, err = os.Lstat(fName)
		}
	} else {
		fName = fmt.Sprintf("%s.%s%s", w.fileNameOnly, w.dailyOpenTime.Format("2006-01-02"), w.suffix)
		_, err = os.Lstat(fName)
		for ; err == nil && num <= 999; num++ {
			fName = w.fileNameOnly + fmt.Sprintf(".%s.%03d%s", w.dailyOpenTime.Format("2006-01-02"), num, w.suffix)
			_, err = os.Lstat(fName)
		}
	}

how to set config directly rather than string or file

I found it is impossible to merge more than one configString like this (last config string will override previous one):

const defaultConfig = `
{
        formatter.name = "text"
        formatter.options  {
                            force-colors      = false
                            full-timestamp    = false
                            timestamp-format  = "01/02 15:04:05.000"
        }
}
`

opts := make([]logrus_mate.Option, 0)
opts = append(opts, logrus_mate.ConfigString(defaultConfig))

if (someCondition){
    opts = append(opts, logrus_mate.ConfigString(fmt.Sprintf(`{ level = "%s" }`, myLevel)))
}
if (anotherCondition){
   opts = append(opts, logrus_mate.ConfigString(`hook { file { filename = "my.log" } }`)
}
logrus_mate.Hijack(logrus.StandardLogger(),opts...)

so, is there any approach to set up configuration (in struct or sth else) directly rather than using string or a file?

那个example跑不通啊

和main.go放在同一个目录下,报找不到文件, 给出绝对路径呢,24行那又报错"logurs mate: hook not registerd"
搞不懂,搞不懂

License v1 and v2

Hi!

Thank you for library! Can you add a license file on v2 and v1 please?

Thank you,

Alexandre

如何按天生成日志文件?

我按照example/main.go中的代码和mate.conf.example,但运行时报这个错:
logurs mate: hook not registerd

我的代码:
` mate, err := logrus_mate.NewLogrusMate(logrus_mate.ConfigFile("mate.conf"))

newLoger := logrus.New()

if err = mate.Hijack(newLoger, "mike"); err != nil {
	fmt.Println(err)
	return
}

// newLogger is Hijackt by mike config
newLoger.Debug("You could not see me")
newLoger.Errorln("Hello Error Level")

mike {

    level = "error"

    formatter.name = "text"
    formatter.options  {
                        force-colors      = false
                        disable-colors    = true
                        disable-timestamp = false
                        full-timestamp    = false
                        timestamp-format  = "2006-01-02 15:04:05"
                        disable-sorting   = false
    }

    hooks {

            file {
                filename = "1.log"
                daily = true
                rotate = true
            }
    }

}

`

请帮忙看一下是怎么回事?

按日切割功能有缺陷

func (w *FileLogWriter) docheck(size int) {
	w.startLock.Lock()
	defer w.startLock.Unlock()
	if w.Rotate && ((w.Maxlines > 0 && w.maxlines_curlines >= w.Maxlines) ||
		(w.Maxsize > 0 && w.maxsize_cursize >= w.Maxsize) ||
		(w.Daily && time.Now().Day() != w.daily_opendate)) {
		if err := w.DoRotate(); err != nil {
			fmt.Fprintf(os.Stderr, "FileLogWriter(%q): %s\n", w.Filename, err)
			return
		}
	}
	w.maxlines_curlines++
	w.maxsize_cursize += size
}

这里比如当前log文件都是记录19号的,20号0点重启了服务,这时候20号记录的日志还是记录在log文件中,因为time.Now().Day() != w.daily_opendate,w.daily_opendate因为重启服务重新生成了,导致走不到下面的日志切割方法

请问graylog的conf应该如何设置?能否举个例子?

mike {

    level = "error"

    formatter.name = "text"
    formatter.options  {
                        force-colors      = false
                        disable-colors    = false
                        disable-timestamp = false
                        full-timestamp    = false
                        timestamp-format  = "2006-01-02 15:04:05"
                        disable-sorting   = false
    }

    hooks {
            expander {}

            graylog {
                address = ""
                extra = ""
            }
    }

}

应该如何填写?

Update Logstash dependency

Logstash support in formatters/logstash/logstash_formatter.go support depends on github.com/Sirupsen/logrus/formatters/logstash which no longer exists. Seems that it was moved to another repository sirupsen/logrus#382

Can you please update the dependency and README? Thanks!

name conflict with Logrus

The github.com/sirupsen/logrus/ is now lower case. All the imports in this repo has Cpitalized github.com/Sirupsen/logrus/ version.
Can you change it to lowercase as indicated by README of github.com/Sirupsen/logrus.

Bump version for Go 1.11 module

Currently, the only tagged release version is v1.0.0, which is relatively old, and still using the Sirupsen/logrus import path instead of the new sirupsen/logrus one. This is causing build errors (case-insensitive conflict between the import paths) under Go 1.11 module system.

Would you consider marking a more recent commit as a new release version?

写文件log,按天记录

自己写了个第三方文件Writers,写log前能否调用Writers里面的方法(比如before_write)判断下生成新的io.Writer

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.