Browse Source

initial

123.abc
ldf 3 years ago
parent
commit
e8b11de310
  1. 25
      LICENSE
  2. 5
      cmd/conf/cfg.toml
  3. 32
      cmd/conf/log.yml
  4. 0
      cmd/logs/cmd.error
  5. 5
      cmd/logs/cmd.log
  6. 11
      cmd/print.go
  7. 23
      config.go
  8. 9
      go.mod
  9. 45
      go.sum
  10. 161
      logger.go
  11. 26
      logging.go

25
LICENSE

@ -0,0 +1,25 @@
Copyright (c) 2011, Deusty, LLC
All rights reserved.
Redistribution and use of this software in source and binary forms, with or
without modification, are permitted provided that the following conditions
are met:
* Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
* Neither the name of Deusty nor the names of its contributors may be used
to endorse or promote products derived from this software without specific
prior written permission of Deusty, LLC.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

5
cmd/conf/cfg.toml

@ -0,0 +1,5 @@
[logger]
conf = "./conf/log.yml"
path = "./logs/"
app_name = "cmd"

32
cmd/conf/log.yml

@ -0,0 +1,32 @@
level: "info"
development: false
disableCaller: false
disableStacktrace: false
sampling:
encoding: "console"
# encoder
encoderConfig:
messageKey: "message"
levelKey: "level"
timeKey: "time"
nameKey: "logger"
callerKey: "caller"
stacktraceKey: "stacktrace"
lineEnding: ""
# levelEncoder: "capitalColor"
timeEncoder: "iso8601"
durationEncoder: "seconds"
callerEncoder: "short"
nameEncoder: ""
outputPaths:
# - "../logs/yuanex.log"
# - "./logs/yuanex.log"
- "stderr"
errorOutputPaths:
# - "../logs/yuanex.error"
# - "./logs/yuanex.error"
- "stderr"
initialFields:

0
cmd/logs/cmd.error

5
cmd/logs/cmd.log

@ -0,0 +1,5 @@
2020-07-30T03:46:39.626+0800 cmd/print.go:6 hahah
2020-07-30T22:16:28.944+0800 cmd/print.go:6 hahah
2020-08-03T16:01:50.178+0800 cmd/print.go:6 hahah
2020-08-03T16:02:58.721+0800 cmd/print.go:6 hahah
2020-08-03T16:02:58.725+0800 cmd/print.go:9 reloaded.

11
cmd/print.go

@ -0,0 +1,11 @@
package main
import "git.drinkme.beer/yinghe/log"
func main() {
log.Infof("hahah")
log.ReloadLogger("./conf/cfg.toml")
log.Infof(" reloaded.")
return
}

23
config.go

@ -0,0 +1,23 @@
package log
type LogCfg struct {
LogConf string `toml:"conf"`
LogPath string `toml:"path"`
APPName string `toml:"app_name"`
DInfo string
DError string
OutputPaths string
ErrorOutputPaths string
}
type GlobalCfg struct {
Logs LogCfg `toml:"logger"`
}
var cfg LogCfg
const (
// ConfigFile is the default configuration file name.
ConfigFile = "./conf/cfg.toml"
)

9
go.mod

@ -0,0 +1,9 @@
module git.drinkme.beer/yinghe/log
go 1.14
require (
github.com/BurntSushi/toml v0.3.1
go.uber.org/zap v1.15.0
gopkg.in/yaml.v2 v2.3.0
)

45
go.sum

@ -0,0 +1,45 @@
github.com/BurntSushi/toml v0.3.1 h1:WXkYYl6Yr3qBf1K79EBnL4mak0OimBfB0XUf9Vl28OQ=
github.com/BurntSushi/toml v0.3.1/go.mod h1:xHWCNGjB5oqiDr8zfno3MHue2Ht5sIBksp03qcyfWMU=
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/google/renameio v0.1.0/go.mod h1:KWCgfxg9yswjAJkECMjeO8J8rahYeXnNhOm40UhjYkI=
github.com/kisielk/gotool v1.0.0/go.mod h1:XhKaO+MFFWcvkIS/tQcRk01m1F5IRFswLeQ+oQHNcck=
github.com/kr/pretty v0.1.0/go.mod h1:dAy3ld7l9f0ibDNOQOHHMYYIIbhfbHSm3C4ZsoJORNo=
github.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ=
github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI=
github.com/pkg/errors v0.8.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0=
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/rogpeppe/go-internal v1.3.0/go.mod h1:M8bDsm7K2OlrFYOpmOWEs/qY81heoFRclV5y23lUDJ4=
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=
github.com/stretchr/testify v1.4.0/go.mod h1:j7eGeouHqKxXV5pUuKE4zz7dFj8WfuZ+81PSLYec5m4=
go.uber.org/atomic v1.6.0 h1:Ezj3JGmsOnG1MoRWQkPBsKLe9DwWD9QeXzTRzzldNVk=
go.uber.org/atomic v1.6.0/go.mod h1:sABNBOSYdrvTF6hTgEIbc7YasKWGhgEQZyfxyTvoXHQ=
go.uber.org/multierr v1.5.0 h1:KCa4XfM8CWFCpxXRGok+Q0SS/0XBhMDbHHGABQLvD2A=
go.uber.org/multierr v1.5.0/go.mod h1:FeouvMocqHpRaaGuG9EjoKcStLC43Zu/fmqdUMPcKYU=
go.uber.org/tools v0.0.0-20190618225709-2cfd321de3ee/go.mod h1:vJERXedbb3MVM5f9Ejo0C68/HhF8uaILCdgjnY+goOA=
go.uber.org/zap v1.15.0 h1:ZZCA22JRF2gQE5FoNmhmrf7jeJJ2uhqDUNRYKm8dvmM=
go.uber.org/zap v1.15.0/go.mod h1:Mb2vm2krFEG5DV0W9qcHBYFtp/Wku1cvYaqPsS/WYfc=
golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
golang.org/x/crypto v0.0.0-20190510104115-cbcb75029529/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI=
golang.org/x/lint v0.0.0-20190930215403-16217165b5de/go.mod h1:6SW0HCj/g11FgYtHlgUYUwCkIfeOF89ocIRzGO/8vkc=
golang.org/x/mod v0.0.0-20190513183733-4bf6d317e70e/go.mod h1:mXi4GBBbnImb6dmsKGUJ2LatrhH/nqhxcFungHvyanc=
golang.org/x/net v0.0.0-20190311183353-d8887717615a/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg=
golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg=
golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=
golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
golang.org/x/tools v0.0.0-20190311212946-11955173bddd/go.mod h1:LCzVGOaR6xXOjkQ3onu1FJEFr0SW1gC7cKk1uF8kGRs=
golang.org/x/tools v0.0.0-20190621195816-6e04913cbbac/go.mod h1:/rFqwRUd4F7ZHNgwSSTFct+R/Kf4OFW1sUzUTQQTgfc=
golang.org/x/tools v0.0.0-20191029041327-9cc4af7d6b2c/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo=
golang.org/x/tools v0.0.0-20191029190741-b9c20aec41a5/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo=
golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/errgo.v2 v2.1.0/go.mod h1:hNsd1EY+bozCKY1Ytp96fpM3vjJbqLJn88ws8XvfDNI=
gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
gopkg.in/yaml.v2 v2.3.0 h1:clyUAQHOM3G0M3f5vQj7LuJrETvjVot3Z5el9nffUtU=
gopkg.in/yaml.v2 v2.3.0/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
honnef.co/go/tools v0.0.1-2019.2.3/go.mod h1:a3bituU0lyd329TUQxRnasdCoJDkEUEAqEt0JzvZhAg=

161
logger.go

@ -0,0 +1,161 @@
package log
import (
"fmt"
"io/ioutil"
"log"
"path"
"github.com/BurntSushi/toml"
"go.uber.org/zap"
"go.uber.org/zap/zapcore"
"gopkg.in/yaml.v2"
)
var (
logger Logger
//OutputPaths = ""
//ErrOutputPaths = ""
)
type YLogger struct {
Logger
dynamicLevel zap.AtomicLevel
}
type Logger interface {
Info(args ...interface{})
Warn(args ...interface{})
Error(args ...interface{})
Debug(args ...interface{})
Infof(fmt string, args ...interface{})
Warnf(fmt string, args ...interface{})
Errorf(fmt string, args ...interface{})
Debugf(fmt string, args ...interface{})
}
func init() {
var (
logCfg GlobalCfg
)
log.Println("config file name -->", ConfigFile)
if _, err := toml.DecodeFile(ConfigFile, &logCfg); err != nil {
log.Fatalf("Read config file err:%s", err.Error())
}
cfg = logCfg.Logs
cfg.OutputPaths = cfg.LogPath + cfg.APPName + ".log"
cfg.ErrorOutputPaths = cfg.LogPath + cfg.APPName + ".error"
err := InitLog(cfg.LogConf)
if err != nil {
log.Printf("[InitLog] warn: %v", err)
}
}
func ReloadLogger(configFile string) {
var (
logCfg GlobalCfg
)
log.Println("config file name -->", configFile)
if _, err := toml.DecodeFile(configFile, &logCfg); err != nil {
log.Fatalf("Read config file err:%s", err.Error())
}
cfg = logCfg.Logs
cfg.OutputPaths = cfg.LogPath + cfg.APPName + ".log"
cfg.ErrorOutputPaths = cfg.LogPath + cfg.APPName + ".error"
err := InitLog(cfg.LogConf)
if err != nil {
log.Printf("[ReloadLogger] warn: %v", err)
}
}
func InitLog(logConfFile string) error {
if logConfFile == "" {
InitLogger(nil)
return fmt.Errorf("log configure file name is nil")
}
if path.Ext(logConfFile) != ".yml" {
InitLogger(nil)
return fmt.Errorf("log configure file name{%s} suffix must be .yml", logConfFile)
}
confFileStream, err := ioutil.ReadFile(logConfFile)
if err != nil {
InitLogger(nil)
return fmt.Errorf("ioutil.ReadFile(file:%s) = error:%v", logConfFile, err)
}
conf := &zap.Config{}
err = yaml.Unmarshal(confFileStream, conf)
if err != nil {
InitLogger(nil)
return fmt.Errorf("[Unmarshal]init logger error: %v", err)
}
log.Println("to set yuanex logger ...")
conf.OutputPaths = append(conf.OutputPaths, cfg.OutputPaths)
conf.ErrorOutputPaths = append(conf.ErrorOutputPaths, cfg.ErrorOutputPaths)
log.Println("ErrorOutputPahts -->", conf.ErrorOutputPaths)
InitLogger(conf)
return nil
}
func InitLogger(conf *zap.Config) {
var zapLoggerConfig zap.Config
if conf == nil {
zapLoggerConfig = zap.NewDevelopmentConfig()
zapLoggerEncoderConfig := zapcore.EncoderConfig{
TimeKey: "time",
LevelKey: "level",
NameKey: "logger",
CallerKey: "caller",
MessageKey: "message",
StacktraceKey: "stacktrace",
EncodeTime: zapcore.ISO8601TimeEncoder,
EncodeDuration: zapcore.SecondsDurationEncoder,
EncodeCaller: zapcore.ShortCallerEncoder,
}
zapLoggerConfig.EncoderConfig = zapLoggerEncoderConfig
} else {
zapLoggerConfig = *conf
}
zapLogger, _ := zapLoggerConfig.Build(zap.AddCallerSkip(1))
//logger = zapLogger.Sugar()
logger = &YLogger{Logger: zapLogger.Sugar(), dynamicLevel: zapLoggerConfig.Level}
}
func SetLogger(log Logger) {
logger = log
}
func GetLogger() Logger {
return logger
}
func SetLoggerLevel(level string) bool {
if l, ok := logger.(OpsLogger); ok {
l.SetLoggerLevel(level)
return true
}
return false
}
type OpsLogger interface {
Logger
SetLoggerLevel(level string)
}
func (dl *YLogger) SetLoggerLevel(level string) {
l := new(zapcore.Level)
l.Set(level)
dl.dynamicLevel.SetLevel(*l)
}

26
logging.go

@ -0,0 +1,26 @@
package log
func Info(args ...interface{}) {
logger.Info(args...)
}
func Warn(args ...interface{}) {
logger.Warn(args...)
}
func Error(args ...interface{}) {
logger.Error(args...)
}
func Debug(args ...interface{}) {
logger.Debug(args...)
}
func Infof(fmt string, args ...interface{}) {
logger.Infof(fmt, args...)
}
func Warnf(fmt string, args ...interface{}) {
logger.Warnf(fmt, args...)
}
func Errorf(fmt string, args ...interface{}) {
logger.Errorf(fmt, args...)
}
func Debugf(fmt string, args ...interface{}) {
logger.Debugf(fmt, args...)
}
Loading…
Cancel
Save