From cd7c2e7b3d7b608649493a0f4f80388c4812a2ce Mon Sep 17 00:00:00 2001 From: Lynn Date: Thu, 31 Jan 2019 11:22:52 +0800 Subject: [PATCH 1/5] *: change to zap log --- cmd/benchdb/main.go | 4 +- cmd/benchfilesort/main.go | 4 +- cmd/explaintest/main.go | 4 +- config/config.go | 17 ++--- ddl/ddl_test.go | 5 +- ddl/failtest/fail_db_test.go | 5 +- distsql/request_builder_test.go | 4 +- executor/executor_test.go | 4 +- executor/seqtest/seq_executor_test.go | 4 +- go.mod | 8 +-- go.sum | 13 +++- owner/fail_test.go | 5 +- server/server_test.go | 4 +- session/tidb_test.go | 4 +- sessionctx/binloginfo/binloginfo_test.go | 4 +- store/store_test.go | 4 +- tidb-server/main.go | 41 +++++++---- util/logutil/log.go | 92 ++++++++++++++++++------ util/logutil/log_test.go | 41 ++++++++++- util/memory/tracker_test.go | 4 +- 20 files changed, 167 insertions(+), 104 deletions(-) diff --git a/cmd/benchdb/main.go b/cmd/benchdb/main.go index 152950b51c60c..bce400e76dd3c 100644 --- a/cmd/benchdb/main.go +++ b/cmd/benchdb/main.go @@ -55,9 +55,7 @@ var ( func main() { flag.Parse() flag.PrintDefaults() - err := logutil.InitLogger(&logutil.LogConfig{ - Level: *logLevel, - }) + err := logutil.InitLogger(logutil.NewLogConfig(*logLevel, logutil.DefaultLogFormat, "", logutil.EmptyFileLogConfig, false)) terror.MustNil(err) err = store.Register("tikv", tikv.Driver{}) terror.MustNil(err) diff --git a/cmd/benchfilesort/main.go b/cmd/benchfilesort/main.go index 08c16353a58fd..3c6f30827861d 100644 --- a/cmd/benchfilesort/main.go +++ b/cmd/benchfilesort/main.go @@ -382,9 +382,7 @@ func driveRunCmd() { } func init() { - err := logutil.InitLogger(&logutil.LogConfig{ - Level: logLevel, - }) + err := logutil.InitLogger(logutil.NewLogConfig(logLevel, logutil.DefaultLogFormat, "", logutil.EmptyFileLogConfig, false)) terror.MustNil(err) cwd, err1 := os.Getwd() terror.MustNil(err1) diff --git a/cmd/explaintest/main.go b/cmd/explaintest/main.go index 2ac30aa2b81cd..3a53d4de1944a 100644 --- a/cmd/explaintest/main.go +++ b/cmd/explaintest/main.go @@ -629,9 +629,7 @@ func openDBWithRetry(driverName, dataSourceName string) (mdb *sql.DB, err error) func main() { flag.Parse() - err := logutil.InitLogger(&logutil.LogConfig{ - Level: logLevel, - }) + err := logutil.InitLogger(logutil.NewLogConfig(logLevel, logutil.DefaultLogFormat, "", logutil.EmptyFileLogConfig, false)) if err != nil { panic("init logger fail, " + err.Error()) } diff --git a/config/config.go b/config/config.go index 0417cd65ac760..d13307a286448 100644 --- a/config/config.go +++ b/config/config.go @@ -285,12 +285,9 @@ var defaultConf = Config{ }, LowerCaseTableNames: 2, Log: Log{ - Level: "info", - Format: "text", - File: logutil.FileLogConfig{ - LogRotate: true, - MaxSize: logutil.DefaultLogMaxSize, - }, + Level: "info", + Format: "text", + File: logutil.NewFileLogConfig(true, logutil.DefaultLogMaxSize), SlowThreshold: logutil.DefaultSlowThreshold, ExpensiveThreshold: 10000, QueryLogMaxLen: logutil.DefaultQueryLogMaxLen, @@ -373,13 +370,7 @@ func (c *Config) Load(confFile string) error { // ToLogConfig converts *Log to *logutil.LogConfig. func (l *Log) ToLogConfig() *logutil.LogConfig { - return &logutil.LogConfig{ - Level: l.Level, - Format: l.Format, - DisableTimestamp: l.DisableTimestamp, - File: l.File, - SlowQueryFile: l.SlowQueryFile, - } + return logutil.NewLogConfig(l.Level, l.Format, l.SlowQueryFile, l.File, l.DisableTimestamp) } // ToTracingConfig converts *OpenTracing to *tracing.Configuration. diff --git a/ddl/ddl_test.go b/ddl/ddl_test.go index 97fc59615d199..477b401e7f898 100644 --- a/ddl/ddl_test.go +++ b/ddl/ddl_test.go @@ -94,10 +94,7 @@ func TestT(t *testing.T) { CustomVerboseFlag = true *CustomParallelSuiteFlag = true logLevel := os.Getenv("log_level") - logutil.InitLogger(&logutil.LogConfig{ - Level: logLevel, - Format: "highlight", - }) + logutil.InitLogger(logutil.NewLogConfig(logLevel, "highlight", "", logutil.EmptyFileLogConfig, false)) autoid.SetStep(5000) ReorgWaitTimeout = 30 * time.Millisecond diff --git a/ddl/failtest/fail_db_test.go b/ddl/failtest/fail_db_test.go index 1b89a2d0e3132..e3f59aa896ef2 100644 --- a/ddl/failtest/fail_db_test.go +++ b/ddl/failtest/fail_db_test.go @@ -44,10 +44,7 @@ import ( func TestT(t *testing.T) { CustomVerboseFlag = true logLevel := os.Getenv("log_level") - logutil.InitLogger(&logutil.LogConfig{ - Level: logLevel, - Format: "highlight", - }) + logutil.InitLogger(logutil.NewLogConfig(logLevel, "highlight", "", logutil.EmptyFileLogConfig, false)) testleak.BeforeTest() TestingT(t) testleak.AfterTestT(t)() diff --git a/distsql/request_builder_test.go b/distsql/request_builder_test.go index 10d319b9c3e65..ed310718882c6 100644 --- a/distsql/request_builder_test.go +++ b/distsql/request_builder_test.go @@ -37,9 +37,7 @@ var _ = Suite(&testSuite{}) func TestT(t *testing.T) { CustomVerboseFlag = true logLevel := os.Getenv("log_level") - logutil.InitLogger(&logutil.LogConfig{ - Level: logLevel, - }) + logutil.InitLogger(logutil.NewLogConfig(logLevel, logutil.DefaultLogFormat, "", logutil.EmptyFileLogConfig, false)) TestingT(t) } diff --git a/executor/executor_test.go b/executor/executor_test.go index ae53776e721c2..9ebd29fe22c98 100644 --- a/executor/executor_test.go +++ b/executor/executor_test.go @@ -69,9 +69,7 @@ func TestT(t *testing.T) { CustomVerboseFlag = true *CustomParallelSuiteFlag = true logLevel := os.Getenv("log_level") - logutil.InitLogger(&logutil.LogConfig{ - Level: logLevel, - }) + logutil.InitLogger(logutil.NewLogConfig(logLevel, logutil.DefaultLogFormat, "", logutil.EmptyFileLogConfig, false)) autoid.SetStep(5000) testleak.BeforeTest() TestingT(t) diff --git a/executor/seqtest/seq_executor_test.go b/executor/seqtest/seq_executor_test.go index 49808b642953b..0b7da7e428ed3 100644 --- a/executor/seqtest/seq_executor_test.go +++ b/executor/seqtest/seq_executor_test.go @@ -57,9 +57,7 @@ import ( func TestT(t *testing.T) { CustomVerboseFlag = true logLevel := os.Getenv("log_level") - logutil.InitLogger(&logutil.LogConfig{ - Level: logLevel, - }) + logutil.InitLogger(logutil.NewLogConfig(logLevel, logutil.DefaultLogFormat, "", logutil.EmptyFileLogConfig, false)) TestingT(t) } diff --git a/go.mod b/go.mod index 04e65ec9206ae..2fac71a4c7b22 100644 --- a/go.mod +++ b/go.mod @@ -48,11 +48,11 @@ require ( github.com/pingcap/gofail v0.0.0-20181217135706-6a951c1e42c3 github.com/pingcap/goleveldb v0.0.0-20171020122428-b9ff6c35079e github.com/pingcap/kvproto v0.0.0-20190110035000-d4fe6b336379 + github.com/pingcap/log v0.0.0-20190129103703-6afc545b8868 github.com/pingcap/parser v0.0.0-20190121074657-4b899f19591e github.com/pingcap/pd v2.1.0-rc.4+incompatible github.com/pingcap/tidb-tools v2.1.3-0.20190116051332-34c808eef588+incompatible github.com/pingcap/tipb v0.0.0-20181012112600-11e33c750323 - github.com/pkg/errors v0.8.0 // indirect github.com/prometheus/client_golang v0.9.0 github.com/prometheus/client_model v0.0.0-20180712105110-5c3871d89910 github.com/prometheus/common v0.0.0-20181020173914-7e9e6cabbd39 // indirect @@ -74,9 +74,7 @@ require ( github.com/ugorji/go/codec v0.0.0-20181127175209-856da096dbdf // indirect github.com/unrolled/render v0.0.0-20180914162206-b9786414de4d // indirect github.com/xiang90/probing v0.0.0-20160813154853-07dd2e8dfe18 // indirect - go.uber.org/atomic v1.3.2 // indirect - go.uber.org/multierr v1.1.0 // indirect - go.uber.org/zap v1.9.1 // indirect + go.uber.org/zap v1.9.1 golang.org/x/net v0.0.0-20190108225652-1e06a53dbb7e golang.org/x/sys v0.0.0-20190109145017-48ac38b7c8cb // indirect golang.org/x/text v0.3.0 @@ -88,3 +86,5 @@ require ( sourcegraph.com/sourcegraph/appdash v0.0.0-20180531100431-4c381bd170b4 sourcegraph.com/sourcegraph/appdash-data v0.0.0-20151005221446-73f23eafcf67 ) + +replace github.com/pingcap/log => github.com/pingcap/log v0.0.0-20190211033212-6e5c1a1a9e89 diff --git a/go.sum b/go.sum index 417d810660359..8dc6ca41078ea 100644 --- a/go.sum +++ b/go.sum @@ -26,6 +26,7 @@ github.com/cznic/mathutil v0.0.0-20181021201202-eba54fb065b7 h1:y+DH9ARrWiiNBV+6 github.com/cznic/mathutil v0.0.0-20181021201202-eba54fb065b7/go.mod h1:e6NPNENfs9mPDVNRekM7lKScauxd5kXTr1Mfyig6TDM= github.com/cznic/sortutil v0.0.0-20150617083342-4c7342852e65 h1:hxuZop6tSoOi0sxFzoGGYdRqNrPubyaIf9KoBG9tPiE= github.com/cznic/sortutil v0.0.0-20150617083342-4c7342852e65/go.mod h1:q2w6Bg5jeox1B+QkJ6Wp/+Vn0G/bo3f1uY7Fn3vivIQ= +github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/dgrijalva/jwt-go v3.2.0+incompatible h1:7qlOGliEKZXTDg6OTjfoBKDXWrumCAMpl/TFQ4/5kLM= @@ -110,6 +111,9 @@ github.com/pingcap/goleveldb v0.0.0-20171020122428-b9ff6c35079e h1:P73/4dPCL96rG github.com/pingcap/goleveldb v0.0.0-20171020122428-b9ff6c35079e/go.mod h1:O17XtbryoCJhkKGbT62+L2OlrniwqiGLSqrmdHCMzZw= github.com/pingcap/kvproto v0.0.0-20190110035000-d4fe6b336379 h1:l4KInBOtxjbgQLjCFHzX66vZgNzsH4a+RiuVZGrO0xk= github.com/pingcap/kvproto v0.0.0-20190110035000-d4fe6b336379/go.mod h1:QMdbTAXCHzzygQzqcG9uVUgU2fKeSN1GmfMiykdSzzY= +github.com/pingcap/log v0.0.0-20190129103703-6afc545b8868 h1:zkyIcjTiuRIOvhuPvbB1wsRFZH5aPqz/3o7p8uAdEzU= +github.com/pingcap/log v0.0.0-20190129103703-6afc545b8868/go.mod h1:xsfkWVaFVV5B8e1K9seWfyJWFrIhbtUTAD8NV1Pq3+w= +github.com/pingcap/log v0.0.0-20190211033212-6e5c1a1a9e89/go.mod h1:xsfkWVaFVV5B8e1K9seWfyJWFrIhbtUTAD8NV1Pq3+w= github.com/pingcap/parser v0.0.0-20190121074657-4b899f19591e h1:UxQ0Fj4NDpQ0SSZ0Z76je8OPSDlbRxMfXTbyPrFs6c4= github.com/pingcap/parser v0.0.0-20190121074657-4b899f19591e/go.mod h1:1FNvfp9+J0wvc4kl8eGNh7Rqrxveg15jJoWo/a0uHwA= github.com/pingcap/pd v2.1.0-rc.4+incompatible h1:/buwGk04aHO5odk/+O8ZOXGs4qkUjYTJ2UpCJXna8NE= @@ -118,8 +122,8 @@ github.com/pingcap/tidb-tools v2.1.3-0.20190116051332-34c808eef588+incompatible github.com/pingcap/tidb-tools v2.1.3-0.20190116051332-34c808eef588+incompatible/go.mod h1:XGdcy9+yqlDSEMTpOXnwf3hiTeqrV6MN/u1se9N8yIM= github.com/pingcap/tipb v0.0.0-20181012112600-11e33c750323 h1:mRKKzRjDNaUNPnAkPAHnRqpNmwNWBX1iA+hxlmvQ93I= github.com/pingcap/tipb v0.0.0-20181012112600-11e33c750323/go.mod h1:RtkHW8WbcNxj8lsbzjaILci01CtYnYbIkQhjyZWrWVI= -github.com/pkg/errors v0.8.0 h1:WdK/asTD0HN+q6hsWO3/vpuAkAr+tw6aNJNDFFf0+qw= -github.com/pkg/errors v0.8.0/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= +github.com/pkg/errors v0.8.1 h1:iURUrRGxPUNPdy5/HRSm+Yj6okJ6UtLINN0Q9M4+h3I= +github.com/pkg/errors v0.8.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= github.com/prometheus/client_golang v0.9.0 h1:tXuTFVHC03mW0D+Ua1Q2d1EAVqLTuggX50V0VLICCzY= @@ -144,9 +148,12 @@ github.com/soheilhy/cmux v0.1.4 h1:0HKaf1o97UwFjHH9o5XsHUOF+tqmdA7KEzXLpiyaw0E= github.com/soheilhy/cmux v0.1.4/go.mod h1:IM3LyeVVIOuxMH7sFAkER9+bJ4dT7Ms6E4xg4kGIyLM= github.com/spaolacci/murmur3 v0.0.0-20180118202830-f09979ecbc72 h1:qLC7fQah7D6K1B0ujays3HV9gkFtllcxhzImRR7ArPQ= github.com/spaolacci/murmur3 v0.0.0-20180118202830-f09979ecbc72/go.mod h1:JwIasOWyU6f++ZhiEuf87xNszmSA2myDM2Kzu9HwQUA= +github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= github.com/stretchr/objx v0.1.1/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= github.com/stretchr/testify v1.2.2 h1:bSDNvY7ZPG5RlJ8otE/7V6gMiyenm9RtJ7IUVIAoJ1w= github.com/stretchr/testify v1.2.2/go.mod h1:a8OnRcib4nhh0OaRAV+Yts87kKdq0PP7pXfy6kDkUVs= +github.com/stretchr/testify v1.3.0 h1:TivCn/peBQ7UY8ooIcPgZFpTNSz0Q2U6UrFlUfqbe0Q= +github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI= github.com/struCoder/pidusage v0.1.2 h1:fFPTThlcWFQyizv3xKs5Lyq1lpG5lZ36arEGNhWz2Vs= github.com/struCoder/pidusage v0.1.2/go.mod h1:pWBlW3YuSwRl6h7R5KbvA4N8oOqe9LjaKW5CwT1SPjI= github.com/tiancaiamao/appdash v0.0.0-20181126055449-889f96f722a2 h1:mbAskLJ0oJfDRtkanvQPiooDH8HvJ2FBh+iKT/OmiQQ= @@ -224,6 +231,8 @@ gopkg.in/tomb.v1 v1.0.0-20141024135613-dd632973f1e7 h1:uRGJdciOHaEIrze2W8Q3AKkep gopkg.in/tomb.v1 v1.0.0-20141024135613-dd632973f1e7/go.mod h1:dt/ZhP58zS4L8KSrWDmTeBkI65Dw0HsyUHuEVlX15mw= gopkg.in/yaml.v2 v2.2.1 h1:mUhvW9EsL+naU5Q3cakzfE91YhliOondGd6ZrsDBHQE= gopkg.in/yaml.v2 v2.2.1/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= +gopkg.in/yaml.v2 v2.2.2 h1:ZCJp+EgiOT7lHqUV2J862kp8Qj64Jo6az82+3Td9dZw= +gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= honnef.co/go/tools v0.0.0-20180728063816-88497007e858/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4= sourcegraph.com/sourcegraph/appdash v0.0.0-20180531100431-4c381bd170b4 h1:VO9oZbbkvTwqLimlQt15QNdOOBArT2dw/bvzsMZBiqQ= sourcegraph.com/sourcegraph/appdash v0.0.0-20180531100431-4c381bd170b4/go.mod h1:hI742Nqp5OhwiqlzhgfbWU4mW4yO10fP+LoT9WOswdU= diff --git a/owner/fail_test.go b/owner/fail_test.go index d6cd1fcfb2053..62076a13bd61c 100644 --- a/owner/fail_test.go +++ b/owner/fail_test.go @@ -33,10 +33,7 @@ import ( func TestT(t *testing.T) { CustomVerboseFlag = true logLevel := os.Getenv("log_level") - logutil.InitLogger(&logutil.LogConfig{ - Level: logLevel, - Format: "highlight", - }) + logutil.InitLogger(logutil.NewLogConfig(logLevel, "highlight", "", logutil.EmptyFileLogConfig, false)) TestingT(t) } diff --git a/server/server_test.go b/server/server_test.go index 4260c2d2d4ea0..18225ebbedf92 100644 --- a/server/server_test.go +++ b/server/server_test.go @@ -37,9 +37,7 @@ import ( func TestT(t *testing.T) { CustomVerboseFlag = true logLevel := os.Getenv("log_level") - logutil.InitLogger(&logutil.LogConfig{ - Level: logLevel, - }) + logutil.InitLogger(logutil.NewLogConfig(logLevel, logutil.DefaultLogFormat, "", logutil.EmptyFileLogConfig, false)) TestingT(t) } diff --git a/session/tidb_test.go b/session/tidb_test.go index 8a7baaabeed52..59d6cea7d8be7 100644 --- a/session/tidb_test.go +++ b/session/tidb_test.go @@ -35,9 +35,7 @@ import ( func TestT(t *testing.T) { logLevel := os.Getenv("log_level") - logutil.InitLogger(&logutil.LogConfig{ - Level: logLevel, - }) + logutil.InitLogger(logutil.NewLogConfig(logLevel, logutil.DefaultLogFormat, "", logutil.EmptyFileLogConfig, false)) CustomVerboseFlag = true TestingT(t) } diff --git a/sessionctx/binloginfo/binloginfo_test.go b/sessionctx/binloginfo/binloginfo_test.go index 7dba9b465e728..f960d14ef95c4 100644 --- a/sessionctx/binloginfo/binloginfo_test.go +++ b/sessionctx/binloginfo/binloginfo_test.go @@ -44,9 +44,7 @@ import ( func TestT(t *testing.T) { CustomVerboseFlag = true logLevel := os.Getenv("log_level") - logutil.InitLogger(&logutil.LogConfig{ - Level: logLevel, - }) + logutil.InitLogger(logutil.NewLogConfig(logLevel, logutil.DefaultLogFormat, "", logutil.EmptyFileLogConfig, false)) TestingT(t) } diff --git a/store/store_test.go b/store/store_test.go index 7807d76550941..f4d2e1ee6d1c0 100644 --- a/store/store_test.go +++ b/store/store_test.go @@ -46,9 +46,7 @@ func (s *brokenStore) Open(schema string) (kv.Storage, error) { func TestT(t *testing.T) { CustomVerboseFlag = true logLevel := os.Getenv("log_level") - logutil.InitLogger(&logutil.LogConfig{ - Level: logLevel, - }) + logutil.InitLogger(logutil.NewLogConfig(logLevel, logutil.DefaultLogFormat, "", logutil.EmptyFileLogConfig, false)) TestingT(t) } diff --git a/tidb-server/main.go b/tidb-server/main.go index 1150a9258cf6a..f480f5cc96266 100644 --- a/tidb-server/main.go +++ b/tidb-server/main.go @@ -26,6 +26,7 @@ import ( opentracing "github.com/opentracing/opentracing-go" "github.com/pingcap/errors" + "github.com/pingcap/log" "github.com/pingcap/parser/mysql" "github.com/pingcap/parser/terror" pd "github.com/pingcap/pd/client" @@ -53,8 +54,8 @@ import ( "github.com/pingcap/tidb/util/systimemon" "github.com/prometheus/client_golang/prometheus" "github.com/prometheus/client_golang/prometheus/push" - log "github.com/sirupsen/logrus" "github.com/struCoder/pidusage" + "go.uber.org/zap" ) // Flag Names @@ -142,6 +143,7 @@ func main() { validateConfig() setGlobalVars() setupLog() + defer syncLog() setupTracing() // Should before createServer and after setup config. printInfo() setupBinlogClient() @@ -154,6 +156,12 @@ func main() { os.Exit(0) } +func syncLog() { + if err := log.Sync(); err != nil { + println("sync log err: ", err) + } +} + func registerStores() { err := kvstore.Register("tikv", tikv.Driver{}) terror.MustNil(err) @@ -208,7 +216,7 @@ func setupBinlogClient() { terror.MustNil(err) binloginfo.SetPumpsClient(client) - log.Infof("create pumps client success, ignore binlog error %v", cfg.Binlog.IgnoreError) + log.Info("tidb-server", zap.Bool("create pumps client success, ignore binlog error", cfg.Binlog.IgnoreError)) } // Prometheus push. @@ -220,7 +228,7 @@ func pushMetric(addr string, interval time.Duration) { log.Info("disable Prometheus push client") return } - log.Infof("start Prometheus push client with server addr %s and interval %s", addr, interval) + log.Info("start prometheus push client", zap.String("server addr", addr), zap.String("interval", interval.String())) go prometheusPushClient(addr, interval) } @@ -236,7 +244,7 @@ func prometheusPushClient(addr string, interval time.Duration) { prometheus.DefaultGatherer, ) if err != nil { - log.Errorf("could not push metrics to Prometheus Pushgateway: %v", err) + log.Error("could not push metrics to prometheus pushgateway", zap.String("err", err.Error())) } time.Sleep(interval) } @@ -257,7 +265,7 @@ func parseDuration(lease string) time.Duration { dur, err = time.ParseDuration(lease + "s") } if err != nil || dur < 0 { - log.Fatalf("invalid lease duration %s", lease) + log.Fatal("invalid lease duration", zap.String("lease", lease)) } return dur } @@ -384,37 +392,37 @@ func validateConfig() { nameList = append(nameList, k) } } - log.Errorf("\"store\" should be in [%s] only", strings.Join(nameList, ", ")) + log.Error("validate config", zap.Strings("valid storages", nameList)) os.Exit(-1) } if cfg.Store == "mocktikv" && !cfg.RunDDL { - log.Errorf("can't disable DDL on mocktikv") + log.Error("can't disable DDL on mocktikv") os.Exit(-1) } if cfg.Log.File.MaxSize > config.MaxLogFileSize { - log.Errorf("log max-size should not be larger than %d MB", config.MaxLogFileSize) + log.Error("validate config", zap.Int("log max-size should not be larger than", config.MaxLogFileSize)) os.Exit(-1) } cfg.OOMAction = strings.ToLower(cfg.OOMAction) // lower_case_table_names is allowed to be 0, 1, 2 if cfg.LowerCaseTableNames < 0 || cfg.LowerCaseTableNames > 2 { - log.Errorf("lower-case-table-names should be 0 or 1 or 2.") + log.Error("lower-case-table-names should be 0 or 1 or 2.") os.Exit(-1) } if cfg.TxnLocalLatches.Enabled && cfg.TxnLocalLatches.Capacity == 0 { - log.Errorf("txn-local-latches.capacity can not be 0") + log.Error("txn-local-latches.capacity can not be 0") os.Exit(-1) } // For tikvclient. if cfg.TiKVClient.GrpcConnectionCount == 0 { - log.Errorf("grpc-connection-count should be greater than 0") + log.Error("grpc-connection-count should be greater than 0") os.Exit(-1) } if cfg.TiKVClient.MaxTxnTimeUse == 0 { - log.Errorf("max-txn-time-use should be greater than 0") + log.Error("max-txn-time-use should be greater than 0") os.Exit(-1) } } @@ -460,14 +468,17 @@ func setGlobalVars() { } func setupLog() { - err := logutil.InitLogger(cfg.Log.ToLogConfig()) + err := logutil.InitZapLogger(cfg.Log.ToLogConfig()) + terror.MustNil(err) + + err = logutil.InitLogger(cfg.Log.ToLogConfig()) terror.MustNil(err) } func printInfo() { // Make sure the TiDB info is always printed. level := log.GetLevel() - log.SetLevel(log.InfoLevel) + log.SetLevel(zap.InfoLevel) printer.PrintTiDBInfo() log.SetLevel(level) } @@ -520,7 +531,7 @@ func setupTracing() { tracingCfg := cfg.OpenTracing.ToTracingConfig() tracer, _, err := tracingCfg.New("TiDB") if err != nil { - log.Fatal("cannot initialize Jaeger Tracer", err) + log.Fatal("setup trace", zap.String("cannot initialize jaeger tracer", err.Error())) } opentracing.SetGlobalTracer(tracer) } diff --git a/util/logutil/log.go b/util/logutil/log.go index 24b306e25887f..01d52c99060aa 100644 --- a/util/logutil/log.go +++ b/util/logutil/log.go @@ -23,7 +23,9 @@ import ( "strings" "github.com/pingcap/errors" + zaplog "github.com/pingcap/log" log "github.com/sirupsen/logrus" + "go.uber.org/zap" "gopkg.in/natefinch/lumberjack.v2" ) @@ -31,42 +33,53 @@ const ( defaultLogTimeFormat = "2006/01/02 15:04:05.000" // DefaultLogMaxSize is the default size of log files. DefaultLogMaxSize = 300 // MB - defaultLogFormat = "text" - defaultLogLevel = log.InfoLevel + // DefaultLogFormat is the default format of the log. + DefaultLogFormat = "text" + defaultLogLevel = log.InfoLevel // DefaultSlowThreshold is the default slow log threshold in millisecond. DefaultSlowThreshold = 300 // DefaultQueryLogMaxLen is the default max length of the query in the log. DefaultQueryLogMaxLen = 2048 ) +// EmptyFileLogConfig is an empty FileLogConfig. +var EmptyFileLogConfig = FileLogConfig{} + // FileLogConfig serializes file log related config in toml/json. type FileLogConfig struct { - // Log filename, leave empty to disable file log. - Filename string `toml:"filename" json:"filename"` - // Is log rotate enabled. TODO. - LogRotate bool `toml:"log-rotate" json:"log-rotate"` - // Max size for a single file, in MB. - MaxSize uint `toml:"max-size" json:"max-size"` - // Max log keep days, default is never deleting. - MaxDays uint `toml:"max-days" json:"max-days"` - // Maximum number of old log files to retain. - MaxBackups uint `toml:"max-backups" json:"max-backups"` + zaplog.FileLogConfig +} + +// NewFileLogConfig creates a FileLogConfig. +func NewFileLogConfig(rotate bool, maxSize uint) FileLogConfig { + return FileLogConfig{FileLogConfig: zaplog.FileLogConfig{ + LogRotate: rotate, + MaxSize: int(maxSize), + }, + } } // LogConfig serializes log related config in toml/json. type LogConfig struct { - // Log level. - Level string `toml:"level" json:"level"` - // Log format. one of json, text, or console. - Format string `toml:"format" json:"format"` - // Disable automatic timestamps in output. - DisableTimestamp bool `toml:"disable-timestamp" json:"disable-timestamp"` - // File log config. - File FileLogConfig `toml:"file" json:"file"` + zaplog.Config + // SlowQueryFile filename, default to File log config on empty. SlowQueryFile string } +// NewLogConfig creates a LogConfig. +func NewLogConfig(level, format, slowQueryFile string, fileCfg FileLogConfig, disableTimestamp bool) *LogConfig { + return &LogConfig{ + Config: zaplog.Config{ + Level: level, + Format: format, + DisableTimestamp: disableTimestamp, + File: fileCfg.FileLogConfig, + }, + SlowQueryFile: slowQueryFile, + } +} + // isSKippedPackageName tests wether path name is on log library calling stack. func isSkippedPackageName(name string) bool { return strings.Contains(name, "github.com/sirupsen/logrus") || @@ -220,7 +233,7 @@ func stringToLogFormatter(format string, disableTimestamp bool) log.Formatter { } // initFileLog initializes file based logging options. -func initFileLog(cfg *FileLogConfig, logger *log.Logger) error { +func initFileLog(cfg *zaplog.FileLogConfig, logger *log.Logger) error { if st, err := os.Stat(cfg.Filename); err == nil { if st.IsDir() { return errors.New("can't use directory as log file name") @@ -250,13 +263,16 @@ func initFileLog(cfg *FileLogConfig, logger *log.Logger) error { // SlowQueryLogger is used to log slow query, InitLogger will modify it according to config file. var SlowQueryLogger = log.StandardLogger() +// SlowQueryZapLogger is used to log slow query, InitZapLogger will set it according to config file. +var SlowQueryZapLogger *zap.Logger + // InitLogger initializes PD's logger. func InitLogger(cfg *LogConfig) error { log.SetLevel(stringToLogLevel(cfg.Level)) log.AddHook(&contextHook{}) if cfg.Format == "" { - cfg.Format = defaultLogFormat + cfg.Format = DefaultLogFormat } formatter := stringToLogFormatter(cfg.Format, cfg.DisableTimestamp) log.SetFormatter(formatter) @@ -287,3 +303,35 @@ func InitLogger(cfg *LogConfig) error { return nil } + +// InitZapLogger initializes a zap logger with cfg. +func InitZapLogger(cfg *LogConfig) error { + gl, props, err := zaplog.InitLogger(&cfg.Config) + if err != nil { + return errors.Trace(err) + } + zaplog.ReplaceGlobals(gl, props) + + if len(cfg.SlowQueryFile) != 0 { + sqfCfg := zaplog.FileLogConfig{ + LogRotate: cfg.File.LogRotate, + MaxSize: cfg.File.MaxSize, + Filename: cfg.SlowQueryFile, + } + sqCfg := &zaplog.Config{ + Level: cfg.Level, + Format: cfg.Format, + DisableTimestamp: cfg.DisableTimestamp, + File: sqfCfg, + } + sqLogger, _, err := zaplog.InitLogger(sqCfg) + if err != nil { + return errors.Trace(err) + } + SlowQueryZapLogger = sqLogger + } else { + SlowQueryZapLogger = gl + } + + return nil +} diff --git a/util/logutil/log_test.go b/util/logutil/log_test.go index 5327bc5b8643b..5a7e4086e9d51 100644 --- a/util/logutil/log_test.go +++ b/util/logutil/log_test.go @@ -25,6 +25,7 @@ import ( . "github.com/pingcap/check" log "github.com/sirupsen/logrus" + "go.uber.org/zap" ) const ( @@ -61,7 +62,7 @@ func (s *testLogSuite) TestStringToLogLevel(c *C) { // TestLogging assure log format and log redirection works. func (s *testLogSuite) TestLogging(c *C) { - conf := &LogConfig{Level: "warn", File: FileLogConfig{}} + conf := NewLogConfig("warn", DefaultLogFormat, "", EmptyFileLogConfig, false) c.Assert(InitLogger(conf), IsNil) log.SetOutput(s.buf) @@ -84,7 +85,7 @@ func (s *testLogSuite) TestLogging(c *C) { func (s *testLogSuite) TestSlowQueryLogger(c *C) { fileName := "slow_query" - conf := &LogConfig{Level: "info", File: FileLogConfig{}, SlowQueryFile: fileName} + conf := NewLogConfig("info", DefaultLogFormat, fileName, EmptyFileLogConfig, false) err := InitLogger(conf) c.Assert(err, IsNil) defer os.Remove(fileName) @@ -113,7 +114,7 @@ func (s *testLogSuite) TestSlowQueryLogger(c *C) { func (s *testLogSuite) TestSlowQueryLoggerKeepOrder(c *C) { fileName := "slow_query" - conf := &LogConfig{Level: "warn", File: FileLogConfig{}, Format: "text", DisableTimestamp: true, SlowQueryFile: fileName} + conf := NewLogConfig("warn", DefaultLogFormat, fileName, EmptyFileLogConfig, true) c.Assert(InitLogger(conf), IsNil) defer os.Remove(fileName) ft, ok := SlowQueryLogger.Formatter.(*textFormatter) @@ -149,3 +150,37 @@ func (s *testLogSuite) TestSlowQueryLoggerKeepOrder(c *C) { expectMsg = fmt.Sprintf("log_test.go:%v: [warning] slow-query a=a b=b c=c d=d e=e f=f\n", line+1) c.Assert(s.buf.String(), Equals, expectMsg) } + +func (s *testLogSuite) TestSlowQueryZapLogger(c *C) { + fileName := "slow_query" + conf := NewLogConfig("info", DefaultLogFormat, fileName, EmptyFileLogConfig, false) + err := InitZapLogger(conf) + c.Assert(err, IsNil) + defer os.Remove(fileName) + + rets := []string{ + `[INFO] [log_test.go:167] ["info message"] ["str key"=val]`, + `[WARN] [log_test.go:168] ["warn message"] ["int key"=123]`, + `[ERROR] [log_test.go:169] ["error message"] ["bool key"=true]`, + } + SlowQueryZapLogger.Debug("debug message", zap.String("str key", "val")) + SlowQueryZapLogger.Info("info message", zap.String("str key", "val")) + SlowQueryZapLogger.Warn("warn message", zap.Int("int key", 123)) + SlowQueryZapLogger.Error("error message", zap.Bool("bool key", true)) + + f, err := os.Open(fileName) + c.Assert(err, IsNil) + defer f.Close() + + r := bufio.NewReader(f) + for _, ret := range rets { + var str string + str, err = r.ReadString('\n') + if err != nil { + break + } + c.Assert(strings.Contains(str, ret), IsTrue, Commentf("got %v, expected %v", str, ret)) + } + _, err = r.ReadString('\n') + c.Assert(err, Equals, io.EOF) +} diff --git a/util/memory/tracker_test.go b/util/memory/tracker_test.go index 65788551890be..2982fff0374d5 100644 --- a/util/memory/tracker_test.go +++ b/util/memory/tracker_test.go @@ -26,9 +26,7 @@ import ( func TestT(t *testing.T) { CustomVerboseFlag = true logLevel := os.Getenv("log_level") - logutil.InitLogger(&logutil.LogConfig{ - Level: logLevel, - }) + logutil.InitLogger(logutil.NewLogConfig(logLevel, logutil.DefaultLogFormat, "", logutil.EmptyFileLogConfig, false)) TestingT(t) } From 58d62aa99e46568dc0a03e9389217c24800f50f8 Mon Sep 17 00:00:00 2001 From: Lynn Date: Wed, 13 Feb 2019 16:18:33 +0800 Subject: [PATCH 2/5] util/logutil: address a comment --- go.sum | 1 + util/logutil/log_test.go | 15 ++++++--------- 2 files changed, 7 insertions(+), 9 deletions(-) diff --git a/go.sum b/go.sum index 8dc6ca41078ea..97c33d81bd4cd 100644 --- a/go.sum +++ b/go.sum @@ -113,6 +113,7 @@ github.com/pingcap/kvproto v0.0.0-20190110035000-d4fe6b336379 h1:l4KInBOtxjbgQLj github.com/pingcap/kvproto v0.0.0-20190110035000-d4fe6b336379/go.mod h1:QMdbTAXCHzzygQzqcG9uVUgU2fKeSN1GmfMiykdSzzY= github.com/pingcap/log v0.0.0-20190129103703-6afc545b8868 h1:zkyIcjTiuRIOvhuPvbB1wsRFZH5aPqz/3o7p8uAdEzU= github.com/pingcap/log v0.0.0-20190129103703-6afc545b8868/go.mod h1:xsfkWVaFVV5B8e1K9seWfyJWFrIhbtUTAD8NV1Pq3+w= +github.com/pingcap/log v0.0.0-20190211033212-6e5c1a1a9e89 h1:RRvKa01HXBYGKB2o6F0ogFxSgagzsD6sPCETrV3F7Ow= github.com/pingcap/log v0.0.0-20190211033212-6e5c1a1a9e89/go.mod h1:xsfkWVaFVV5B8e1K9seWfyJWFrIhbtUTAD8NV1Pq3+w= github.com/pingcap/parser v0.0.0-20190121074657-4b899f19591e h1:UxQ0Fj4NDpQ0SSZ0Z76je8OPSDlbRxMfXTbyPrFs6c4= github.com/pingcap/parser v0.0.0-20190121074657-4b899f19591e/go.mod h1:1FNvfp9+J0wvc4kl8eGNh7Rqrxveg15jJoWo/a0uHwA= diff --git a/util/logutil/log_test.go b/util/logutil/log_test.go index 5a7e4086e9d51..7eb8700f8fd5b 100644 --- a/util/logutil/log_test.go +++ b/util/logutil/log_test.go @@ -30,6 +30,9 @@ import ( const ( logPattern = `\d\d\d\d/\d\d/\d\d \d\d:\d\d:\d\d\.\d\d\d ([\w_%!$@.,+~-]+|\\.)+:\d+: \[(fatal|error|warning|info|debug)\] .*?\n` + // zapLogPatern is used to match the zap log format, such as the following log: + // [2019/02/13 15:56:05.385 +08:00] [INFO] [log_test.go:167] ["info message"] ["str key"=val] ["int key"=123] + zapLogPattern = `\[\d\d\d\d/\d\d/\d\d \d\d:\d\d:\d\d.\d\d\d\ \+\d\d:\d\d\] \[(FATAL|ERROR|WARN|INFO|DEBUG)\] \[([\w_%!$@.,+~-]+|\\.)+:\d+\] \[.*\] (\[.*=.*\]).*\n` ) func Test(t *testing.T) { @@ -158,14 +161,9 @@ func (s *testLogSuite) TestSlowQueryZapLogger(c *C) { c.Assert(err, IsNil) defer os.Remove(fileName) - rets := []string{ - `[INFO] [log_test.go:167] ["info message"] ["str key"=val]`, - `[WARN] [log_test.go:168] ["warn message"] ["int key"=123]`, - `[ERROR] [log_test.go:169] ["error message"] ["bool key"=true]`, - } SlowQueryZapLogger.Debug("debug message", zap.String("str key", "val")) SlowQueryZapLogger.Info("info message", zap.String("str key", "val")) - SlowQueryZapLogger.Warn("warn message", zap.Int("int key", 123)) + SlowQueryZapLogger.Warn("warn", zap.Int("int key", 123)) SlowQueryZapLogger.Error("error message", zap.Bool("bool key", true)) f, err := os.Open(fileName) @@ -173,14 +171,13 @@ func (s *testLogSuite) TestSlowQueryZapLogger(c *C) { defer f.Close() r := bufio.NewReader(f) - for _, ret := range rets { + for { var str string str, err = r.ReadString('\n') if err != nil { break } - c.Assert(strings.Contains(str, ret), IsTrue, Commentf("got %v, expected %v", str, ret)) + c.Assert(str, Matches, zapLogPattern) } - _, err = r.ReadString('\n') c.Assert(err, Equals, io.EOF) } From 4774ed7623707be152894dd385a9cc3d8e22e391 Mon Sep 17 00:00:00 2001 From: Lynn Date: Wed, 13 Feb 2019 17:03:33 +0800 Subject: [PATCH 3/5] *: make tidy --- go.sum | 1 - 1 file changed, 1 deletion(-) diff --git a/go.sum b/go.sum index 97c33d81bd4cd..8dc6ca41078ea 100644 --- a/go.sum +++ b/go.sum @@ -113,7 +113,6 @@ github.com/pingcap/kvproto v0.0.0-20190110035000-d4fe6b336379 h1:l4KInBOtxjbgQLj github.com/pingcap/kvproto v0.0.0-20190110035000-d4fe6b336379/go.mod h1:QMdbTAXCHzzygQzqcG9uVUgU2fKeSN1GmfMiykdSzzY= github.com/pingcap/log v0.0.0-20190129103703-6afc545b8868 h1:zkyIcjTiuRIOvhuPvbB1wsRFZH5aPqz/3o7p8uAdEzU= github.com/pingcap/log v0.0.0-20190129103703-6afc545b8868/go.mod h1:xsfkWVaFVV5B8e1K9seWfyJWFrIhbtUTAD8NV1Pq3+w= -github.com/pingcap/log v0.0.0-20190211033212-6e5c1a1a9e89 h1:RRvKa01HXBYGKB2o6F0ogFxSgagzsD6sPCETrV3F7Ow= github.com/pingcap/log v0.0.0-20190211033212-6e5c1a1a9e89/go.mod h1:xsfkWVaFVV5B8e1K9seWfyJWFrIhbtUTAD8NV1Pq3+w= github.com/pingcap/parser v0.0.0-20190121074657-4b899f19591e h1:UxQ0Fj4NDpQ0SSZ0Z76je8OPSDlbRxMfXTbyPrFs6c4= github.com/pingcap/parser v0.0.0-20190121074657-4b899f19591e/go.mod h1:1FNvfp9+J0wvc4kl8eGNh7Rqrxveg15jJoWo/a0uHwA= From 876444210b4e4bf5a12c083c9a0efb129191bfd4 Mon Sep 17 00:00:00 2001 From: Lynn Date: Thu, 14 Feb 2019 14:56:21 +0800 Subject: [PATCH 4/5] tidb-server: address comments --- go.mod | 4 +--- go.sum | 5 ++--- tidb-server/main.go | 5 +++-- 3 files changed, 6 insertions(+), 8 deletions(-) diff --git a/go.mod b/go.mod index 2fac71a4c7b22..12765bd1522bb 100644 --- a/go.mod +++ b/go.mod @@ -48,7 +48,7 @@ require ( github.com/pingcap/gofail v0.0.0-20181217135706-6a951c1e42c3 github.com/pingcap/goleveldb v0.0.0-20171020122428-b9ff6c35079e github.com/pingcap/kvproto v0.0.0-20190110035000-d4fe6b336379 - github.com/pingcap/log v0.0.0-20190129103703-6afc545b8868 + github.com/pingcap/log v0.0.0-20190214045112-b37da76f67a7 github.com/pingcap/parser v0.0.0-20190121074657-4b899f19591e github.com/pingcap/pd v2.1.0-rc.4+incompatible github.com/pingcap/tidb-tools v2.1.3-0.20190116051332-34c808eef588+incompatible @@ -86,5 +86,3 @@ require ( sourcegraph.com/sourcegraph/appdash v0.0.0-20180531100431-4c381bd170b4 sourcegraph.com/sourcegraph/appdash-data v0.0.0-20151005221446-73f23eafcf67 ) - -replace github.com/pingcap/log => github.com/pingcap/log v0.0.0-20190211033212-6e5c1a1a9e89 diff --git a/go.sum b/go.sum index 8dc6ca41078ea..7f38209129f16 100644 --- a/go.sum +++ b/go.sum @@ -111,9 +111,8 @@ github.com/pingcap/goleveldb v0.0.0-20171020122428-b9ff6c35079e h1:P73/4dPCL96rG github.com/pingcap/goleveldb v0.0.0-20171020122428-b9ff6c35079e/go.mod h1:O17XtbryoCJhkKGbT62+L2OlrniwqiGLSqrmdHCMzZw= github.com/pingcap/kvproto v0.0.0-20190110035000-d4fe6b336379 h1:l4KInBOtxjbgQLjCFHzX66vZgNzsH4a+RiuVZGrO0xk= github.com/pingcap/kvproto v0.0.0-20190110035000-d4fe6b336379/go.mod h1:QMdbTAXCHzzygQzqcG9uVUgU2fKeSN1GmfMiykdSzzY= -github.com/pingcap/log v0.0.0-20190129103703-6afc545b8868 h1:zkyIcjTiuRIOvhuPvbB1wsRFZH5aPqz/3o7p8uAdEzU= -github.com/pingcap/log v0.0.0-20190129103703-6afc545b8868/go.mod h1:xsfkWVaFVV5B8e1K9seWfyJWFrIhbtUTAD8NV1Pq3+w= -github.com/pingcap/log v0.0.0-20190211033212-6e5c1a1a9e89/go.mod h1:xsfkWVaFVV5B8e1K9seWfyJWFrIhbtUTAD8NV1Pq3+w= +github.com/pingcap/log v0.0.0-20190214045112-b37da76f67a7 h1:kOHAMalwF69bJrtWrOdVaCSvZjLucrJhP4NQKIu6uM4= +github.com/pingcap/log v0.0.0-20190214045112-b37da76f67a7/go.mod h1:xsfkWVaFVV5B8e1K9seWfyJWFrIhbtUTAD8NV1Pq3+w= github.com/pingcap/parser v0.0.0-20190121074657-4b899f19591e h1:UxQ0Fj4NDpQ0SSZ0Z76je8OPSDlbRxMfXTbyPrFs6c4= github.com/pingcap/parser v0.0.0-20190121074657-4b899f19591e/go.mod h1:1FNvfp9+J0wvc4kl8eGNh7Rqrxveg15jJoWo/a0uHwA= github.com/pingcap/pd v2.1.0-rc.4+incompatible h1:/buwGk04aHO5odk/+O8ZOXGs4qkUjYTJ2UpCJXna8NE= diff --git a/tidb-server/main.go b/tidb-server/main.go index f480f5cc96266..7afc1f6e4660e 100644 --- a/tidb-server/main.go +++ b/tidb-server/main.go @@ -158,7 +158,8 @@ func main() { func syncLog() { if err := log.Sync(); err != nil { - println("sync log err: ", err) + fmt.Fprintln(os.Stderr, "sync log err:", err) + os.Exit(1) } } @@ -531,7 +532,7 @@ func setupTracing() { tracingCfg := cfg.OpenTracing.ToTracingConfig() tracer, _, err := tracingCfg.New("TiDB") if err != nil { - log.Fatal("setup trace", zap.String("cannot initialize jaeger tracer", err.Error())) + log.Fatal("setup jaeger tracer failed", zap.String("error message", err.Error())) } opentracing.SetGlobalTracer(tracer) } From b3d5a00ce25564ccf3499cc189090db559c48eaa Mon Sep 17 00:00:00 2001 From: Lynn Date: Fri, 15 Feb 2019 16:22:32 +0800 Subject: [PATCH 5/5] *: address comments --- server/http_handler.go | 8 ++++++++ server/http_handler_test.go | 4 ++++ tidb-server/main.go | 6 +++--- util/logutil/log.go | 10 ++++++++++ util/logutil/log_test.go | 18 ++++++++++++++++++ 5 files changed, 43 insertions(+), 3 deletions(-) diff --git a/server/http_handler.go b/server/http_handler.go index ee3605abb5a9b..725d1c99dd52a 100644 --- a/server/http_handler.go +++ b/server/http_handler.go @@ -51,6 +51,7 @@ import ( "github.com/pingcap/tidb/tablecodec" "github.com/pingcap/tidb/types" "github.com/pingcap/tidb/util/codec" + logutil "github.com/pingcap/tidb/util/logutil" log "github.com/sirupsen/logrus" ) @@ -695,12 +696,19 @@ func (h settingsHandler) ServeHTTP(w http.ResponseWriter, req *http.Request) { return } if levelStr := req.Form.Get("log_level"); levelStr != "" { + err1 := logutil.SetLevel(levelStr) + if err1 != nil { + writeError(w, err1) + return + } + l, err1 := log.ParseLevel(levelStr) if err1 != nil { writeError(w, err1) return } log.SetLevel(l) + config.GetGlobalConfig().Log.Level = levelStr } if generalLog := req.Form.Get("tidb_general_log"); generalLog != "" { diff --git a/server/http_handler_test.go b/server/http_handler_test.go index b7a79f7b73bab..c42bb38c90ad4 100644 --- a/server/http_handler_test.go +++ b/server/http_handler_test.go @@ -30,6 +30,7 @@ import ( . "github.com/pingcap/check" "github.com/pingcap/kvproto/pkg/kvrpcpb" + zaplog "github.com/pingcap/log" "github.com/pingcap/parser/model" "github.com/pingcap/parser/mysql" "github.com/pingcap/tidb/config" @@ -48,6 +49,7 @@ import ( "github.com/pingcap/tidb/util/codec" "github.com/pingcap/tidb/util/printer" log "github.com/sirupsen/logrus" + "go.uber.org/zap" ) type HTTPHandlerTestSuite struct { @@ -622,6 +624,7 @@ func (ts *HTTPHandlerTestSuite) TestPostSettings(c *C) { c.Assert(err, IsNil) c.Assert(resp.StatusCode, Equals, http.StatusOK) c.Assert(log.GetLevel(), Equals, log.ErrorLevel) + c.Assert(zaplog.GetLevel(), Equals, zap.ErrorLevel) c.Assert(config.GetGlobalConfig().Log.Level, Equals, "error") c.Assert(atomic.LoadUint32(&variable.ProcessGeneralLog), Equals, uint32(1)) form = make(url.Values) @@ -632,6 +635,7 @@ func (ts *HTTPHandlerTestSuite) TestPostSettings(c *C) { c.Assert(resp.StatusCode, Equals, http.StatusOK) c.Assert(atomic.LoadUint32(&variable.ProcessGeneralLog), Equals, uint32(0)) c.Assert(log.GetLevel(), Equals, log.InfoLevel) + c.Assert(zaplog.GetLevel(), Equals, zap.InfoLevel) c.Assert(config.GetGlobalConfig().Log.Level, Equals, "info") // test ddl_slow_threshold diff --git a/tidb-server/main.go b/tidb-server/main.go index 7afc1f6e4660e..279ed416b43dc 100644 --- a/tidb-server/main.go +++ b/tidb-server/main.go @@ -143,7 +143,6 @@ func main() { validateConfig() setGlobalVars() setupLog() - defer syncLog() setupTracing() // Should before createServer and after setup config. printInfo() setupBinlogClient() @@ -153,14 +152,15 @@ func main() { signal.SetupSignalHandler(serverShutdown) runServer() cleanup() - os.Exit(0) + exit() } -func syncLog() { +func exit() { if err := log.Sync(); err != nil { fmt.Fprintln(os.Stderr, "sync log err:", err) os.Exit(1) } + os.Exit(0) } func registerStores() { diff --git a/util/logutil/log.go b/util/logutil/log.go index 01d52c99060aa..553f0c36bff9d 100644 --- a/util/logutil/log.go +++ b/util/logutil/log.go @@ -335,3 +335,13 @@ func InitZapLogger(cfg *LogConfig) error { return nil } + +// SetLevel sets the zap logger's level. +func SetLevel(level string) error { + l := zap.NewAtomicLevel() + if err := l.UnmarshalText([]byte(level)); err != nil { + return errors.Trace(err) + } + zaplog.SetLevel(l.Level()) + return nil +} diff --git a/util/logutil/log_test.go b/util/logutil/log_test.go index 7eb8700f8fd5b..a02d675a7d6a5 100644 --- a/util/logutil/log_test.go +++ b/util/logutil/log_test.go @@ -24,6 +24,7 @@ import ( "testing" . "github.com/pingcap/check" + zaplog "github.com/pingcap/log" log "github.com/sirupsen/logrus" "go.uber.org/zap" ) @@ -181,3 +182,20 @@ func (s *testLogSuite) TestSlowQueryZapLogger(c *C) { } c.Assert(err, Equals, io.EOF) } + +func (s *testLogSuite) TestSetLevel(c *C) { + conf := NewLogConfig("info", DefaultLogFormat, "", EmptyFileLogConfig, false) + err := InitZapLogger(conf) + c.Assert(err, IsNil) + + c.Assert(zaplog.GetLevel(), Equals, zap.InfoLevel) + err = SetLevel("warn") + c.Assert(err, IsNil) + c.Assert(zaplog.GetLevel(), Equals, zap.WarnLevel) + err = SetLevel("Error") + c.Assert(err, IsNil) + c.Assert(zaplog.GetLevel(), Equals, zap.ErrorLevel) + err = SetLevel("DEBUG") + c.Assert(err, IsNil) + c.Assert(zaplog.GetLevel(), Equals, zap.DebugLevel) +}