Browse Source

inital

master v0.1.3
ldf 3 years ago
parent
commit
f93005533d
  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. 161
      logger.go
  10. 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
)

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