Skip to content

Commit

Permalink
chore: make several improvements for logger
Browse files Browse the repository at this point in the history
  • Loading branch information
panjf2000 committed Nov 24, 2021
1 parent 4db46da commit 58d2031
Show file tree
Hide file tree
Showing 8 changed files with 54 additions and 34 deletions.
4 changes: 2 additions & 2 deletions acceptor_unix.go
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,7 @@ func (svr *server) acceptNewConnection(_ netpoll.IOEvent) error {
netAddr := socket.SockaddrToTCPOrUnixAddr(sa)
if svr.opts.TCPKeepAlive > 0 && svr.ln.network == "tcp" {
err = socket.SetKeepAlive(nfd, int(svr.opts.TCPKeepAlive/time.Second))
logging.LogErr(err)
logging.Error(err)
}

el := svr.lb.next(netAddr)
Expand Down Expand Up @@ -79,7 +79,7 @@ func (el *eventloop) loopAccept(_ netpoll.IOEvent) error {
netAddr := socket.SockaddrToTCPOrUnixAddr(sa)
if el.svr.opts.TCPKeepAlive > 0 && el.svr.ln.network == "tcp" {
err = socket.SetKeepAlive(nfd, int(el.svr.opts.TCPKeepAlive/time.Second))
logging.LogErr(err)
logging.Error(err)
}

c := newTCPConn(nfd, el, sa, el.svr.opts.Codec, el.ln.lnaddr, netAddr)
Expand Down
15 changes: 7 additions & 8 deletions client.go
Original file line number Diff line number Diff line change
Expand Up @@ -143,24 +143,23 @@ func (cli *Client) Dial(network, address string) (Conn, error) {
return nil, e
}

opts := cli.el.svr.opts
if opts.TCPNoDelay == TCPNoDelay {
if cli.opts.TCPNoDelay == TCPNoDelay {
if err = socket.SetNoDelay(DupFD, 1); err != nil {
return nil, err
}
}
if opts.TCPKeepAlive > 0 {
if err = socket.SetKeepAlive(DupFD, int(opts.TCPKeepAlive/time.Second)); err != nil {
if cli.opts.TCPKeepAlive > 0 {
if err = socket.SetKeepAlive(DupFD, int(cli.opts.TCPKeepAlive/time.Second)); err != nil {
return nil, err
}
}
if opts.SocketSendBuffer > 0 {
if err = socket.SetSendBuffer(DupFD, opts.SocketSendBuffer); err != nil {
if cli.opts.SocketSendBuffer > 0 {
if err = socket.SetSendBuffer(DupFD, cli.opts.SocketSendBuffer); err != nil {
return nil, err
}
}
if opts.SocketRecvBuffer > 0 {
if err = socket.SetRecvBuffer(DupFD, opts.SocketRecvBuffer); err != nil {
if cli.opts.SocketRecvBuffer > 0 {
if err = socket.SetRecvBuffer(DupFD, cli.opts.SocketRecvBuffer); err != nil {
return nil, err
}
}
Expand Down
6 changes: 3 additions & 3 deletions client_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -28,8 +28,8 @@ import (

"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"go.uber.org/zap/zapcore"

"github.com/panjf2000/gnet/logging"
"github.com/panjf2000/gnet/pool/goroutine"
)

Expand Down Expand Up @@ -265,7 +265,7 @@ func testCodecServeWithGnetClient(
codec: codec, workerPool: goroutine.Default(),
}
ts.clientEV = &clientEvents{}
ts.client, err = NewClient(ts.clientEV, WithLogLevel(zapcore.DebugLevel), WithCodec(codec))
ts.client, err = NewClient(ts.clientEV, WithLogLevel(logging.DebugLevel), WithCodec(codec))
assert.NoError(t, err)
err = ts.client.Start()
assert.NoError(t, err)
Expand All @@ -274,7 +274,7 @@ func testCodecServeWithGnetClient(
network+"://"+addr,
WithMulticore(multicore),
WithTicker(true),
WithLogLevel(zapcore.DebugLevel),
WithLogLevel(logging.DebugLevel),
WithSocketRecvBuffer(8*1024),
WithSocketSendBuffer(8*1024),
WithCodec(codec),
Expand Down
3 changes: 1 addition & 2 deletions gnet_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,6 @@ import (
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"go.uber.org/zap"
"go.uber.org/zap/zapcore"

"github.com/panjf2000/gnet/errors"
"github.com/panjf2000/gnet/logging"
Expand Down Expand Up @@ -259,7 +258,7 @@ func testCodecServe(
network+"://"+addr,
WithMulticore(multicore),
WithTicker(true),
WithLogLevel(zapcore.DebugLevel),
WithLogLevel(logging.DebugLevel),
WithTCPKeepAlive(
time.Minute*5,
),
Expand Down
4 changes: 2 additions & 2 deletions listener_unix.go
Original file line number Diff line number Diff line change
Expand Up @@ -70,10 +70,10 @@ func (ln *listener) close() {
ln.once.Do(
func() {
if ln.fd > 0 {
logging.LogErr(os.NewSyscallError("close", unix.Close(ln.fd)))
logging.Error(os.NewSyscallError("close", unix.Close(ln.fd)))
}
if ln.network == "unix" {
logging.LogErr(os.RemoveAll(ln.addr))
logging.Error(os.RemoveAll(ln.addr))
}
})
}
Expand Down
8 changes: 4 additions & 4 deletions listener_windows.go
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ func (ln *listener) dup() (int, string, error) {
func (ln *listener) normalize() (err error) {
switch ln.network {
case "unix":
logging.LogErr(os.RemoveAll(ln.addr))
logging.Error(os.RemoveAll(ln.addr))
fallthrough
case "tcp", "tcp4", "tcp6":
if ln.ln, err = net.Listen(ln.network, ln.addr); err != nil {
Expand All @@ -60,13 +60,13 @@ func (ln *listener) normalize() (err error) {
func (ln *listener) close() {
ln.once.Do(func() {
if ln.ln != nil {
logging.LogErr(ln.ln.Close())
logging.Error(ln.ln.Close())
}
if ln.pconn != nil {
logging.LogErr(ln.pconn.Close())
logging.Error(ln.pconn.Close())
}
if ln.network == "unix" {
logging.LogErr(os.RemoveAll(ln.addr))
logging.Error(os.RemoveAll(ln.addr))
}
})
}
Expand Down
42 changes: 33 additions & 9 deletions logging/logger.go
Original file line number Diff line number Diff line change
Expand Up @@ -59,7 +59,30 @@ import (
var (
flushLogs func() error
defaultLogger Logger
defaultLoggingLevel zapcore.Level
defaultLoggingLevel Level
)

type Level = zapcore.Level

const (
// DebugLevel logs are typically voluminous, and are usually disabled in
// production.
DebugLevel Level = iota - 1
// InfoLevel is the default logging priority.
InfoLevel
// WarnLevel logs are more important than Info, but don't need individual
// human review.
WarnLevel
// ErrorLevel logs are high-priority. If an application is running smoothly,
// it shouldn't generate any error-level logs.
ErrorLevel
// DPanicLevel logs are particularly important errors. In development the
// logger panics after writing the message.
DPanicLevel
// PanicLevel logs a message, then panics.
PanicLevel
// FatalLevel logs a message, then calls os.Exit(1).
FatalLevel
)

func init() {
Expand All @@ -69,7 +92,7 @@ func init() {
if err != nil {
panic("invalid GNET_LOGGING_LEVEL, " + err.Error())
}
defaultLoggingLevel = zapcore.Level(loggingLevel)
defaultLoggingLevel = Level(loggingLevel)
}

// Initializes the inside default logger of gnet.
Expand All @@ -83,14 +106,15 @@ func init() {
} else {
cfg := zap.NewDevelopmentConfig()
cfg.Level = zap.NewAtomicLevelAt(defaultLoggingLevel)
cfg.EncoderConfig.EncodeTime = zapcore.RFC3339NanoTimeEncoder
zapLogger, _ := cfg.Build()
defaultLogger = zapLogger.Sugar()
}
}

func getEncoder() zapcore.Encoder {
encoderConfig := zap.NewProductionEncoderConfig()
encoderConfig.EncodeTime = zapcore.ISO8601TimeEncoder
encoderConfig.EncodeTime = zapcore.RFC3339NanoTimeEncoder
encoderConfig.EncodeLevel = zapcore.CapitalLevelEncoder
return zapcore.NewConsoleEncoder(encoderConfig)
}
Expand All @@ -106,7 +130,7 @@ func LogLevel() string {
}

// CreateLoggerAsLocalFile setups the logger by local file path.
func CreateLoggerAsLocalFile(localFilePath string, logLevel zapcore.Level) (logger Logger, flush func() error, err error) {
func CreateLoggerAsLocalFile(localFilePath string, logLevel Level) (logger Logger, flush func() error, err error) {
if len(localFilePath) == 0 {
return nil, nil, errors.New("invalid local logger path")
}
Expand All @@ -115,15 +139,15 @@ func CreateLoggerAsLocalFile(localFilePath string, logLevel zapcore.Level) (logg
lumberJackLogger := &lumberjack.Logger{
Filename: localFilePath,
MaxSize: 100, // megabytes
MaxBackups: 3,
MaxAge: 28, // days
MaxBackups: 2,
MaxAge: 15, // days
}

encoder := getEncoder()
ws := zapcore.AddSync(lumberJackLogger)
zapcore.Lock(ws)

levelEnabler := zap.LevelEnablerFunc(func(level zapcore.Level) bool {
levelEnabler := zap.LevelEnablerFunc(func(level Level) bool {
return level >= logLevel
})
core := zapcore.NewCore(encoder, ws, levelEnabler)
Expand All @@ -140,8 +164,8 @@ func Cleanup() {
}
}

// LogErr prints err if it's not nil.
func LogErr(err error) {
// Error prints err if it's not nil.
func Error(err error) {
if err != nil {
defaultLogger.Errorf("error occurs during runtime, %v", err)
}
Expand Down
6 changes: 2 additions & 4 deletions options.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,8 +17,6 @@ package gnet
import (
"time"

"go.uber.org/zap/zapcore"

"github.com/panjf2000/gnet/logging"
)

Expand Down Expand Up @@ -110,7 +108,7 @@ type Options struct {
LogPath string

// LogLevel indicates the logging level, it should be used along with LogPath.
LogLevel zapcore.Level
LogLevel logging.Level

// Logger is the customized logger for logging info, if it is not set,
// then gnet will use the default logger powered by go.uber.org/zap.
Expand Down Expand Up @@ -223,7 +221,7 @@ func WithLogPath(fileName string) Option {
}

// WithLogLevel is an option to set up the logging level.
func WithLogLevel(lvl zapcore.Level) Option {
func WithLogLevel(lvl logging.Level) Option {
return func(opts *Options) {
opts.LogLevel = lvl
}
Expand Down

0 comments on commit 58d2031

Please sign in to comment.