This is an automated email from the ASF dual-hosted git repository.
littlecui pushed a commit to branch master
in repository
https://gitbox.apache.org/repos/asf/incubator-servicecomb-service-center.git
The following commit(s) were added to refs/heads/master by this push:
new 2bc012b SCB-317 Use the ServiceComb/paas-lager. (#274)
2bc012b is described below
commit 2bc012b8c4b23cdd62aca7f586a4293b4b1580e7
Author: little-cui <[email protected]>
AuthorDate: Sun Feb 4 09:36:44 2018 +0800
SCB-317 Use the ServiceComb/paas-lager. (#274)
* SCB-317 Use the ServiceComb/paas-lager.
* SCB-317 Update the log_test.go.
---
pkg/async/async_task_test.go | 2 +-
pkg/lager/README.md | 107 ------
pkg/lager/core/LICENSE | 201 -----------
pkg/lager/core/README.md | 76 -----
pkg/lager/core/chug/chug.go | 140 --------
pkg/lager/core/chug/chug_suite_test.go | 29 --
pkg/lager/core/chug/chug_test.go | 259 --------------
pkg/lager/core/chug/match_log_entry_test.go | 57 ----
pkg/lager/core/ginkgoreporter/ginkgo_reporter.go | 171 ----------
.../ginkgoreporter/ginkgoreporter_suite_test.go | 29 --
.../core/ginkgoreporter/ginkgoreporter_test.go | 198 -----------
pkg/lager/core/lager_suite_test.go | 29 --
pkg/lager/core/lagertest/test_sink.go | 87 -----
pkg/lager/core/logger.go | 310 -----------------
pkg/lager/core/logger_test.go | 374 ---------------------
pkg/lager/core/models.go | 101 ------
pkg/lager/core/reconfigurable_sink.go | 51 ---
pkg/lager/core/reconfigurable_sink_test.go | 79 -----
pkg/lager/core/writer_sink.go | 56 ---
pkg/lager/core/writer_sink_test.go | 120 -------
pkg/lager/examples/main.go | 50 ---
pkg/lager/lager.go | 142 --------
pkg/lager/syslog/syslog.go | 92 -----
pkg/util/log.go | 104 ++++--
pkg/util/log_test.go | 21 +-
pkg/{logrotate => util}/logrotate.go | 42 +--
scripts/create_gvt_manifest(exp).sh | 1 +
server/core/0_init.go | 38 +--
.../plugin/infra/tracing/buildin/file_collector.go | 3 +-
vendor/manifest | 8 +
30 files changed, 117 insertions(+), 2860 deletions(-)
diff --git a/pkg/async/async_task_test.go b/pkg/async/async_task_test.go
index 04608d0..0504799 100644
--- a/pkg/async/async_task_test.go
+++ b/pkg/async/async_task_test.go
@@ -28,7 +28,7 @@ import (
)
func init() {
- util.InitLogger("async_task_test", &lager.Config{
+ util.InitGlobalLogger("async_task_test", &log.Config{
LoggerLevel: "DEBUG",
LoggerFile: "",
EnableRsyslog: false,
diff --git a/pkg/lager/README.md b/pkg/lager/README.md
deleted file mode 100644
index 8f194e7..0000000
--- a/pkg/lager/README.md
+++ /dev/null
@@ -1,107 +0,0 @@
-#paas_lager
-===========
-A golang logging library for PaaS
-
-paas_lager 是 PaaS运维组对 CloudFoundry 的 lager 库进行了封装和完善,目的是提供统一的接口方便 PaaS
自研模块的日志输出需求。
-运维组对原始的 lager
日志输出中不符合公司日志要求规范的部分也做了加强和信息补全,以更方便实际问题的诊断和定位。补充的信息包括:进程ID,文件名,行号,方法名等。
-使用 paas_lager 记录日志,能保证自研模块的日志输出为统一的 json 格式,方便后续日志在 Elasticsearch 中做进一步检索和分析。
-
-##Usage
-Download
-```
-git clone http://rnd-isourceb.huawei.com/PaaS/paas-sdk.git $GOPATH/src/paas-sdk
-```
-
-Create logger (complex mode)
-```
-paas_lager.Init(paas_lager.Config{
- LoggerLevel: loggerLevel,
- LoggerFile: loggerFile,
- EnableRsyslog: enableRsyslog,
- RsyslogNetwork: "udp",
- RsyslogAddr: "127.0.0.1:514",
- LogFormatText: false,
-})
-
-logger := paas_lager.NewLogger(component)
-```
-
-* LoggerLevel: 日志级别由低到高分别为 DEBUG, INFO, WARN, ERROR, FATAL
共5个级别,这里设置的级别是日志输出的最低级别,只有不低于该级别的日志才会输出。所以,如果不想打印 WARN 以下级别的日志,可以把 LoggerLevel
设置为 WARN。
-从减小日志大小的考虑,建议在单元测试的时候,可以把 LoggerLevel 级别设置的比较低,比如 DEBUG,而在正式部署的系统代码中,建议级别设置为
WARN,以减少日志频繁输出带来的高 IO 对 VM 和 PaaS 日志后台的存储和处理的负担。
-* LoggerFile: 输出日志的文件名,为空则输出到 os.Stdout。建议路径统一放置在 /var/paas/sys/log
目录下,各个模块分别创建各自的子目录,这样后续可以通过 logrotate 统一进行日志的 rotate 防爆处理。
-* EnableRsyslog: 设定是否输出日志到 rsyslog,默认为 false。
-* RsyslogNetwork: 设定日志传输的方式,是 "udp" 还是 "tcp",默认为"udp"
-* RsyslogAddr: 设定日志发送的目的syslog地址
-* LogFormatText: 设定日志的输出格式是 json 还是 plaintext (类似于log4j),默认为
false,不建议修改,如果开发过程中想本地查看日志的话,可以设定 LoggerFile 和 LogFormatText 为 true,这样会输出类似于
log4j 格式的本地日志。但是建议正式的生产环境还是用 json 的格式输出。
-* component: 日志中输出的模块名字,source 字段所指定的值
-
-对于大多数的使用场景,可以只配置下面的参数即可。
-Create logger (simple mode)
-```
-paas_lager.Init(paas_lager.Config{
- LoggerLevel: loggerLevel,
- LoggerFile: loggerFile,
- EnableRsyslog: enableRsyslog,
-})
-
-logger := paas_lager.NewLogger(component)
-```
-
-##Example
-```
-package main
-
-import (
- "fmt"
-
- "paas_lager"
- "paas_lager/lager"
-)
-
-func main() {
- paas_lager.Init(paas_lager.Config{
- LoggerLevel: "WARN",
- LoggerFile: "/var/paas/sys/log/ops-mgr/example.log",
- EnableRsyslog: false,
- })
-
- logger := paas_lager.NewLogger("example")
-
- logger.InfoF("Hi %s, system is starting up ...", "paas-bot")
-
- logger.Debug("check-info", lager.Data{
- "info": "something",
- })
-
- err := fmt.Errorf("Oops, error occurred!")
- logger.Warn("failed-to-do-somthing", err, lager.Data{
- "info": "something",
- })
-
- err = fmt.Errorf("This is an error")
- logger.Error("failed-to-do-somthing", err)
-
- logger.Info("shutting-down")
-}
-
-```
-
-The output is:
-```
-{"timestamp":"2015-11-09T14:19:16.825759987Z","source":"example","message":"example.Hi
paas-bot, system is starting up
...","log_level":"info","data":{},"process_id":5234,"file":"paas_lager/examples/main.go","lineno":20,"method":"main"}{"timestamp":"2015-11-09T14:19:16.826463479Z","source":"example","message":"example.check-info","log_level":"debug","data":{"info":"something"},"process_id":5234,"file":"paas_lager/examples/main.go","lineno":24,"method":"main"}{"timestamp":"2015-11-09T14:1
[...]
-{"timestamp":"2015-11-09T14:19:16.827071328Z","source":"example","message":"example.failed-to-do-somthing","log_level":"error","data":{"error":"This
is an
error"},"process_id":5234,"file":"paas_lager/examples/main.go","lineno":32,"method":"main"}
-{"timestamp":"2015-11-09T14:19:16.82732567Z","source":"example","message":"example.shutting-down","log_level":"info","data":{},"process_id":5234,"file":"paas_lager/examples/main.go","lineno":34,"method":"main"}
-```
-
-
-如果上述 paas_lager.Init 初始化部分,把 "LogFormatText: true," 加上的话,日志的输出内容会变成如下的
plaintext 模式,方便开发人员本地调试查看日志:
-```
-2015-11-09T14:19:53.73768695Z INFO example 5748 paas_lager/examples/main.go
main():20 - example.Hi paas-bot, system is starting up ...
-2015-11-09T14:19:53.73784007Z DEBUG example 5748 paas_lager/examples/main.go
main():24 - example.check-info
-2015-11-09T14:19:53.737859147Z WARN example 5748 paas_lager/examples/main.go
main():29 - example.failed-to-do-somthing
-2015-11-09T14:19:53.738067943Z ERROR example 5748 paas_lager/examples/main.go
main():32 - example.failed-to-do-somthing
-2015-11-09T14:19:53.738092109Z INFO example 5748 paas_lager/examples/main.go
main():34 - example.shutting-down
-```
-
-## Suggestion to log4go, glog
-使用其他日志模块的,如果不方便迁移到 paas_lager,也建议参考上面的日志输出,把日志格式一致起来,转换为有语义的格式化文档。这样后续在
ElasticSearch 中,可以很方便的解析 json 日志,进行检索。
diff --git a/pkg/lager/core/LICENSE b/pkg/lager/core/LICENSE
deleted file mode 100644
index 5c304d1..0000000
--- a/pkg/lager/core/LICENSE
+++ /dev/null
@@ -1,201 +0,0 @@
-Apache License
- Version 2.0, January 2004
- http://www.apache.org/licenses/
-
- TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
-
- 1. Definitions.
-
- "License" shall mean the terms and conditions for use, reproduction,
- and distribution as defined by Sections 1 through 9 of this document.
-
- "Licensor" shall mean the copyright owner or entity authorized by
- the copyright owner that is granting the License.
-
- "Legal Entity" shall mean the union of the acting entity and all
- other entities that control, are controlled by, or are under common
- control with that entity. For the purposes of this definition,
- "control" means (i) the power, direct or indirect, to cause the
- direction or management of such entity, whether by contract or
- otherwise, or (ii) ownership of fifty percent (50%) or more of the
- outstanding shares, or (iii) beneficial ownership of such entity.
-
- "You" (or "Your") shall mean an individual or Legal Entity
- exercising permissions granted by this License.
-
- "Source" form shall mean the preferred form for making modifications,
- including but not limited to software source code, documentation
- source, and configuration files.
-
- "Object" form shall mean any form resulting from mechanical
- transformation or translation of a Source form, including but
- not limited to compiled object code, generated documentation,
- and conversions to other media types.
-
- "Work" shall mean the work of authorship, whether in Source or
- Object form, made available under the License, as indicated by a
- copyright notice that is included in or attached to the work
- (an example is provided in the Appendix below).
-
- "Derivative Works" shall mean any work, whether in Source or Object
- form, that is based on (or derived from) the Work and for which the
- editorial revisions, annotations, elaborations, or other modifications
- represent, as a whole, an original work of authorship. For the purposes
- of this License, Derivative Works shall not include works that remain
- separable from, or merely link (or bind by name) to the interfaces of,
- the Work and Derivative Works thereof.
-
- "Contribution" shall mean any work of authorship, including
- the original version of the Work and any modifications or additions
- to that Work or Derivative Works thereof, that is intentionally
- submitted to Licensor for inclusion in the Work by the copyright owner
- or by an individual or Legal Entity authorized to submit on behalf of
- the copyright owner. For the purposes of this definition, "submitted"
- means any form of electronic, verbal, or written communication sent
- to the Licensor or its representatives, including but not limited to
- communication on electronic mailing lists, source code control systems,
- and issue tracking systems that are managed by, or on behalf of, the
- Licensor for the purpose of discussing and improving the Work, but
- excluding communication that is conspicuously marked or otherwise
- designated in writing by the copyright owner as "Not a Contribution."
-
- "Contributor" shall mean Licensor and any individual or Legal Entity
- on behalf of whom a Contribution has been received by Licensor and
- subsequently incorporated within the Work.
-
- 2. Grant of Copyright License. Subject to the terms and conditions of
- this License, each Contributor hereby grants to You a perpetual,
- worldwide, non-exclusive, no-charge, royalty-free, irrevocable
- copyright license to reproduce, prepare Derivative Works of,
- publicly display, publicly perform, sublicense, and distribute the
- Work and such Derivative Works in Source or Object form.
-
- 3. Grant of Patent License. Subject to the terms and conditions of
- this License, each Contributor hereby grants to You a perpetual,
- worldwide, non-exclusive, no-charge, royalty-free, irrevocable
- (except as stated in this section) patent license to make, have made,
- use, offer to sell, sell, import, and otherwise transfer the Work,
- where such license applies only to those patent claims licensable
- by such Contributor that are necessarily infringed by their
- Contribution(s) alone or by combination of their Contribution(s)
- with the Work to which such Contribution(s) was submitted. If You
- institute patent litigation against any entity (including a
- cross-claim or counterclaim in a lawsuit) alleging that the Work
- or a Contribution incorporated within the Work constitutes direct
- or contributory patent infringement, then any patent licenses
- granted to You under this License for that Work shall terminate
- as of the date such litigation is filed.
-
- 4. Redistribution. You may reproduce and distribute copies of the
- Work or Derivative Works thereof in any medium, with or without
- modifications, and in Source or Object form, provided that You
- meet the following conditions:
-
- (a) You must give any other recipients of the Work or
- Derivative Works a copy of this License; and
-
- (b) You must cause any modified files to carry prominent notices
- stating that You changed the files; and
-
- (c) You must retain, in the Source form of any Derivative Works
- that You distribute, all copyright, patent, trademark, and
- attribution notices from the Source form of the Work,
- excluding those notices that do not pertain to any part of
- the Derivative Works; and
-
- (d) If the Work includes a "NOTICE" text file as part of its
- distribution, then any Derivative Works that You distribute must
- include a readable copy of the attribution notices contained
- within such NOTICE file, excluding those notices that do not
- pertain to any part of the Derivative Works, in at least one
- of the following places: within a NOTICE text file distributed
- as part of the Derivative Works; within the Source form or
- documentation, if provided along with the Derivative Works; or,
- within a display generated by the Derivative Works, if and
- wherever such third-party notices normally appear. The contents
- of the NOTICE file are for informational purposes only and
- do not modify the License. You may add Your own attribution
- notices within Derivative Works that You distribute, alongside
- or as an addendum to the NOTICE text from the Work, provided
- that such additional attribution notices cannot be construed
- as modifying the License.
-
- You may add Your own copyright statement to Your modifications and
- may provide additional or different license terms and conditions
- for use, reproduction, or distribution of Your modifications, or
- for any such Derivative Works as a whole, provided Your use,
- reproduction, and distribution of the Work otherwise complies with
- the conditions stated in this License.
-
- 5. Submission of Contributions. Unless You explicitly state otherwise,
- any Contribution intentionally submitted for inclusion in the Work
- by You to the Licensor shall be under the terms and conditions of
- this License, without any additional terms or conditions.
- Notwithstanding the above, nothing herein shall supersede or modify
- the terms of any separate license agreement you may have executed
- with Licensor regarding such Contributions.
-
- 6. Trademarks. This License does not grant permission to use the trade
- names, trademarks, service marks, or product names of the Licensor,
- except as required for reasonable and customary use in describing the
- origin of the Work and reproducing the content of the NOTICE file.
-
- 7. Disclaimer of Warranty. Unless required by applicable law or
- agreed to in writing, Licensor provides the Work (and each
- Contributor provides its Contributions) on an "AS IS" BASIS,
- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
- implied, including, without limitation, any warranties or conditions
- of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
- PARTICULAR PURPOSE. You are solely responsible for determining the
- appropriateness of using or redistributing the Work and assume any
- risks associated with Your exercise of permissions under this License.
-
- 8. Limitation of Liability. In no event and under no legal theory,
- whether in tort (including negligence), contract, or otherwise,
- unless required by applicable law (such as deliberate and grossly
- negligent acts) or agreed to in writing, shall any Contributor be
- liable to You for damages, including any direct, indirect, special,
- incidental, or consequential damages of any character arising as a
- result of this License or out of the use or inability to use the
- Work (including but not limited to damages for loss of goodwill,
- work stoppage, computer failure or malfunction, or any and all
- other commercial damages or losses), even if such Contributor
- has been advised of the possibility of such damages.
-
- 9. Accepting Warranty or Additional Liability. While redistributing
- the Work or Derivative Works thereof, You may choose to offer,
- and charge a fee for, acceptance of support, warranty, indemnity,
- or other liability obligations and/or rights consistent with this
- License. However, in accepting such obligations, You may act only
- on Your own behalf and on Your sole responsibility, not on behalf
- of any other Contributor, and only if You agree to indemnify,
- defend, and hold each Contributor harmless for any liability
- incurred by, or claims asserted against, such Contributor by reason
- of your accepting any such warranty or additional liability.
-
- END OF TERMS AND CONDITIONS
-
- APPENDIX: How to apply the Apache License to your work.
-
- To apply the Apache License to your work, attach the following
- boilerplate notice, with the fields enclosed by brackets "{}"
- replaced with your own identifying information. (Don't include
- the brackets!) The text should be enclosed in the appropriate
- comment syntax for the file format. We also recommend that a
- file or class name and description of purpose be included on the
- same "printed page" as the copyright notice for easier
- identification within third-party archives.
-
- Copyright {yyyy} {name of copyright owner}
-
- Licensed under the Apache License, Version 2.0 (the "License");
- you may not use this file except in compliance with the License.
- You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software
- distributed under the License is distributed on an "AS IS" BASIS,
- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- See the License for the specific language governing permissions and
- limitations under the License.
diff --git a/pkg/lager/core/README.md b/pkg/lager/core/README.md
deleted file mode 100644
index 5560831..0000000
--- a/pkg/lager/core/README.md
+++ /dev/null
@@ -1,76 +0,0 @@
-lager
-=====
-
-Lager is a logging library for go.
-
-## Usage
-
-Instantiate a logger with the name of your component.
-
-```go
-import (
- "paas_lager/lager"
-)
-
-logger := lager.NewLogger("my-app")
-```
-
-### Sinks
-
-Lager can write logs to a variety of destinations. You can specify the
destinations
-using Lager sinks:
-
-To write to an arbitrary `Writer` object:
-
-```go
-logger.RegisterSink(lager.NewWriterSink(myWriter, lager.INFO))
-```
-
-### Emitting logs
-
-Lager supports the usual level-based logging, with an optional argument for
arbitrary key-value data.
-
-```go
-logger.Info("doing-stuff", logger.Data{
- "informative": true,
-})
-```
-
-output:
-```json
-{ "source": "my-app", "message": "doing-stuff", "data": { "informative": true
}, "timestamp": 1232345, "log_level": 1 }
-```
-
-Error messages also take an `Error` object:
-
-```go
-logger.Error("failed-to-do-stuff", errors.New("Something went wrong"))
-```
-
-output:
-```json
-{ "source": "my-app", "message": "failed-to-do-stuff", "data": { "error":
"Something went wrong" }, "timestamp": 1232345, "log_level": 1 }
-```
-
-### Sessions
-
-You can avoid repetition of contextual data using 'Sessions':
-
-```go
-
-contextualLogger := logger.Session("my-task", logger.Data{
- "request-id": 5,
-})
-
-contextualLogger.Info("my-action")
-```
-
-output:
-
-```json
-{ "source": "my-app", "message": "my-task.my-action", "data": { "request-id":
5 }, "timestamp": 1232345, "log_level": 1 }
-```
-
-## License
-
-Lager is [Apache 2.0](https://paas_lager/lager/blob/master/LICENSE) licensed.
diff --git a/pkg/lager/core/chug/chug.go b/pkg/lager/core/chug/chug.go
deleted file mode 100644
index 7614971..0000000
--- a/pkg/lager/core/chug/chug.go
+++ /dev/null
@@ -1,140 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package chug
-
-import (
- "bufio"
- "encoding/json"
- "errors"
- "io"
- "strconv"
- "strings"
- "time"
-
- "github.com/apache/incubator-servicecomb-service-center/pkg/lager"
- "github.com/apache/incubator-servicecomb-service-center/pkg/util"
-)
-
-type Entry struct {
- IsLager bool
- Raw []byte
- Log LogEntry
-}
-
-type LogEntry struct {
- Timestamp time.Time
- LogLevel lager.LogLevel
-
- Source string
- Message string
- Session string
-
- Error error
- Trace string
-
- Data lager.Data
-}
-
-func Chug(reader io.Reader, out chan<- Entry) {
- scanner := bufio.NewScanner(reader)
- for scanner.Scan() {
- out <- entry(scanner.Bytes())
- }
- close(out)
-}
-
-func entry(raw []byte) (entry Entry) {
- copiedBytes := make([]byte, len(raw))
- copy(copiedBytes, raw)
- entry = Entry{
- IsLager: false,
- Raw: copiedBytes,
- }
-
- rawString := util.BytesToStringWithNoCopy(raw)
- idx := strings.Index(rawString, "{")
- if idx == -1 {
- return
- }
-
- var lagerLog lager.LogFormat
- decoder := json.NewDecoder(strings.NewReader(rawString[idx:]))
- err := decoder.Decode(&lagerLog)
- if err != nil {
- return
- }
-
- entry.Log, entry.IsLager = convertLagerLog(lagerLog)
-
- return
-}
-
-func convertLagerLog(lagerLog lager.LogFormat) (LogEntry, bool) {
- timestamp, err := strconv.ParseFloat(lagerLog.Timestamp, 64)
-
- if err != nil {
- return LogEntry{}, false
- }
-
- data := lagerLog.Data
-
- var logErr error
- if lagerLog.LogLevel == lager.ERROR || lagerLog.LogLevel == lager.FATAL
{
- dataErr, ok := lagerLog.Data["error"]
- if ok {
- errorString, ok := dataErr.(string)
- if !ok {
- return LogEntry{}, false
- }
- logErr = errors.New(errorString)
- delete(lagerLog.Data, "error")
- }
- }
-
- var logTrace string
- dataTrace, ok := lagerLog.Data["trace"]
- if ok {
- logTrace, ok = dataTrace.(string)
- if !ok {
- return LogEntry{}, false
- }
- delete(lagerLog.Data, "trace")
- }
-
- var logSession string
- dataSession, ok := lagerLog.Data["session"]
- if ok {
- logSession, ok = dataSession.(string)
- if !ok {
- return LogEntry{}, false
- }
- delete(lagerLog.Data, "session")
- }
-
- return LogEntry{
- Timestamp: time.Unix(0, int64(timestamp*1e9)),
- LogLevel: lagerLog.LogLevel,
- Source: lagerLog.Source,
- Message: lagerLog.Message,
- Session: logSession,
-
- Error: logErr,
- Trace: logTrace,
-
- Data: data,
- }, true
-}
diff --git a/pkg/lager/core/chug/chug_suite_test.go
b/pkg/lager/core/chug/chug_suite_test.go
deleted file mode 100644
index fa7fbe2..0000000
--- a/pkg/lager/core/chug/chug_suite_test.go
+++ /dev/null
@@ -1,29 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package chug_test
-
-import (
- . "github.com/onsi/ginkgo"
- . "github.com/onsi/gomega"
-
- "testing"
-)
-
-func TestChug(t *testing.T) {
- RegisterFailHandler(Fail)
- RunSpecs(t, "Chug Suite")
-}
diff --git a/pkg/lager/core/chug/chug_test.go b/pkg/lager/core/chug/chug_test.go
deleted file mode 100644
index 82e536b..0000000
--- a/pkg/lager/core/chug/chug_test.go
+++ /dev/null
@@ -1,259 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package chug_test
-
-import (
- "errors"
- "io"
- "time"
-
- "../..//lager"
- . "../..//lager/chug"
-
- . "github.com/onsi/ginkgo"
- . "github.com/onsi/gomega"
-)
-
-var _ = Describe("Chug", func() {
- var (
- logger lager.Logger
- stream chan Entry
- pipeReader *io.PipeReader
- pipeWriter *io.PipeWriter
- )
-
- BeforeEach(func() {
- pipeReader, pipeWriter = io.Pipe()
- logger = lager.NewLogger("chug-test")
- logger.RegisterSink(lager.NewWriterSink(pipeWriter,
lager.DEBUG))
- stream = make(chan Entry, 100)
- go Chug(pipeReader, stream)
- })
-
- AfterEach(func() {
- pipeWriter.Close()
- Eventually(stream).Should(BeClosed())
- })
-
- Context("when fed a stream of well-formed lager messages", func() {
- It("should return parsed lager messages", func() {
- data := lager.Data{"some-float": 3.0, "some-string":
"foo"}
- logger.Debug("chug", data)
- logger.Info("again", data)
-
- entry := <-stream
- Ω(entry.IsLager).Should(BeTrue())
- Ω(entry.Log).Should(MatchLogEntry(LogEntry{
- LogLevel: lager.DEBUG,
- Source: "chug-test",
- Message: "chug-test.chug",
- Data: data,
- }))
-
- entry = <-stream
- Ω(entry.IsLager).Should(BeTrue())
- Ω(entry.Log).Should(MatchLogEntry(LogEntry{
- LogLevel: lager.INFO,
- Source: "chug-test",
- Message: "chug-test.again",
- Data: data,
- }))
- })
-
- It("should parse the timestamp", func() {
- logger.Debug("chug")
- entry := <-stream
- Ω(entry.Log.Timestamp).Should(BeTemporally("~",
time.Now(), 10*time.Millisecond))
- })
-
- Context("when parsing an error message", func() {
- It("should include the error", func() {
- data := lager.Data{"some-float": 3.0,
"some-string": "foo"}
- logger.Error("chug", errors.New("some-error"),
data)
- Ω((<-stream).Log).Should(MatchLogEntry(LogEntry{
- LogLevel: lager.ERROR,
- Source: "chug-test",
- Message: "chug-test.chug",
- Error: errors.New("some-error"),
- Data: lager.Data{"some-float": 3.0,
"some-string": "foo"},
- }))
- })
- })
-
- Context("when parsing an info message with an error", func() {
- It("should not take the error out of the data map",
func() {
- data := lager.Data{"some-float": 3.0,
"some-string": "foo", "error": "some-error"}
- logger.Info("chug", data)
- Ω((<-stream).Log).Should(MatchLogEntry(LogEntry{
- LogLevel: lager.INFO,
- Source: "chug-test",
- Message: "chug-test.chug",
- Error: nil,
- Data: lager.Data{"some-float": 3.0,
"some-string": "foo", "error": "some-error"},
- }))
- })
- })
-
- Context("when multiple sessions have been established", func() {
- It("should build up the task array appropriately",
func() {
- firstSession := logger.Session("first-session")
- firstSession.Info("encabulate")
- nestedSession :=
firstSession.Session("nested-session-1")
- nestedSession.Info("baconize")
- firstSession.Info("remodulate")
- nestedSession.Info("ergonomize")
- nestedSession =
firstSession.Session("nested-session-2")
- nestedSession.Info("modernify")
-
- Ω((<-stream).Log).Should(MatchLogEntry(LogEntry{
- LogLevel: lager.INFO,
- Source: "chug-test",
- Message:
"chug-test.first-session.encabulate",
- Session: "1",
- Data: lager.Data{},
- }))
-
- Ω((<-stream).Log).Should(MatchLogEntry(LogEntry{
- LogLevel: lager.INFO,
- Source: "chug-test",
- Message:
"chug-test.first-session.nested-session-1.baconize",
- Session: "1.1",
- Data: lager.Data{},
- }))
-
- Ω((<-stream).Log).Should(MatchLogEntry(LogEntry{
- LogLevel: lager.INFO,
- Source: "chug-test",
- Message:
"chug-test.first-session.remodulate",
- Session: "1",
- Data: lager.Data{},
- }))
-
- Ω((<-stream).Log).Should(MatchLogEntry(LogEntry{
- LogLevel: lager.INFO,
- Source: "chug-test",
- Message:
"chug-test.first-session.nested-session-1.ergonomize",
- Session: "1.1",
- Data: lager.Data{},
- }))
-
- Ω((<-stream).Log).Should(MatchLogEntry(LogEntry{
- LogLevel: lager.INFO,
- Source: "chug-test",
- Message:
"chug-test.first-session.nested-session-2.modernify",
- Session: "1.2",
- Data: lager.Data{},
- }))
- })
- })
- })
-
- Context("handling lager JSON that is surrounded by non-JSON", func() {
- var input []byte
- var entry Entry
-
- BeforeEach(func() {
- input =
[]byte(`[some-component][e]{"timestamp":"1407102779.028711081","source":"chug-test","message":"chug-test.chug","log_level":0,"data":{"some-float":3,"some-string":"foo"}}...some
trailing stuff`)
- pipeWriter.Write(input)
- pipeWriter.Write([]byte("\n"))
-
- Eventually(stream).Should(Receive(&entry))
- })
-
- It("should be a lager message", func() {
- Ω(entry.IsLager).Should(BeTrue())
- })
-
- It("should contain all the data in Raw", func() {
- Ω(entry.Raw).Should(Equal(input))
- })
-
- It("should succesfully parse the lager message", func() {
- Ω(entry.Log.Source).Should(Equal("chug-test"))
- })
- })
-
- Context("handling malformed/non-lager data", func() {
- var input []byte
- var entry Entry
-
- JustBeforeEach(func() {
- pipeWriter.Write(input)
- pipeWriter.Write([]byte("\n"))
-
- Eventually(stream).Should(Receive(&entry))
- })
-
- itReturnsRawData := func() {
- It("returns raw data", func() {
- Ω(entry.IsLager).Should(BeFalse())
- Ω(entry.Log).Should(BeZero())
- Ω(entry.Raw).Should(Equal(input))
- })
- }
-
- Context("when fed a stream of malformed lager messages", func()
{
- Context("when the timestamp is invalid", func() {
- BeforeEach(func() {
- input =
[]byte(`{"timestamp":"tomorrow","source":"chug-test","message":"chug-test.chug","log_level":3,"data":{"some-float":3,"some-string":"foo","error":7}}`)
- })
-
- itReturnsRawData()
- })
-
- Context("when the error does not parse", func() {
- BeforeEach(func() {
- input =
[]byte(`{"timestamp":"1407102779.028711081","source":"chug-test","message":"chug-test.chug","log_level":3,"data":{"some-float":3,"some-string":"foo","error":7}}`)
- })
-
- itReturnsRawData()
- })
-
- Context("when the trace does not parse", func() {
- BeforeEach(func() {
- input =
[]byte(`{"timestamp":"1407102779.028711081","source":"chug-test","message":"chug-test.chug","log_level":3,"data":{"some-float":3,"some-string":"foo","trace":7}}`)
- })
-
- itReturnsRawData()
- })
-
- Context("when the session does not parse", func() {
- BeforeEach(func() {
- input =
[]byte(`{"timestamp":"1407102779.028711081","source":"chug-test","message":"chug-test.chug","log_level":3,"data":{"some-float":3,"some-string":"foo","session":7}}`)
- })
-
- itReturnsRawData()
- })
- })
-
- Context("When fed JSON that is not a lager message at all",
func() {
- BeforeEach(func() {
- input = []byte(`{"source":"chattanooga"}`)
- })
-
- itReturnsRawData()
- })
-
- Context("When fed none-JSON that is not a lager message at
all", func() {
- BeforeEach(func() {
- input = []byte(`ß`)
- })
-
- itReturnsRawData()
- })
- })
-})
diff --git a/pkg/lager/core/chug/match_log_entry_test.go
b/pkg/lager/core/chug/match_log_entry_test.go
deleted file mode 100644
index a819677..0000000
--- a/pkg/lager/core/chug/match_log_entry_test.go
+++ /dev/null
@@ -1,57 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package chug_test
-
-import (
- "fmt"
- "reflect"
-
- "../..//lager/chug"
- "github.com/onsi/gomega/format"
- "github.com/onsi/gomega/types"
-)
-
-func MatchLogEntry(entry chug.LogEntry) types.GomegaMatcher {
- return &logEntryMatcher{entry}
-}
-
-type logEntryMatcher struct {
- entry chug.LogEntry
-}
-
-func (m *logEntryMatcher) Match(actual interface{}) (success bool, err error) {
- actualEntry, ok := actual.(chug.LogEntry)
- if !ok {
- return false, fmt.Errorf("MatchLogEntry must be passed a
chug.LogEntry. Got:\n%s", format.Object(actual, 1))
- }
-
- return m.entry.LogLevel == actualEntry.LogLevel &&
- m.entry.Source == actualEntry.Source &&
- m.entry.Message == actualEntry.Message &&
- m.entry.Session == actualEntry.Session &&
- reflect.DeepEqual(m.entry.Error, actualEntry.Error) &&
- m.entry.Trace == actualEntry.Trace &&
- reflect.DeepEqual(m.entry.Data, actualEntry.Data), nil
-}
-
-func (m *logEntryMatcher) FailureMessage(actual interface{}) (message string) {
- return format.Message(actual, "to equal", m.entry)
-}
-
-func (m *logEntryMatcher) NegatedFailureMessage(actual interface{}) (message
string) {
- return format.Message(actual, "not to equal", m.entry)
-}
diff --git a/pkg/lager/core/ginkgoreporter/ginkgo_reporter.go
b/pkg/lager/core/ginkgoreporter/ginkgo_reporter.go
deleted file mode 100644
index eba3ce4..0000000
--- a/pkg/lager/core/ginkgoreporter/ginkgo_reporter.go
+++ /dev/null
@@ -1,171 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package ginkgoreporter
-
-import (
- "fmt"
- "io"
- "time"
-
- "github.com/apache/incubator-servicecomb-service-center/pkg/lager"
- "github.com/onsi/ginkgo/config"
- "github.com/onsi/ginkgo/types"
-)
-
-type SuiteStartSummary struct {
- RandomSeed int64 `json:"random_seed"`
- SuiteDescription string `json:"description"`
- NumberOfSpecsThatWillBeRun int `json:"num_specs"`
-}
-
-type SuiteEndSummary struct {
- SuiteDescription string `json:"description"`
- Passed bool
- NumberOfSpecsThatWillBeRun int `json:"num_specs"`
- NumberOfPassedSpecs int `json:"num_passed"`
- NumberOfFailedSpecs int `json:"num_failed"`
-}
-
-type SpecSummary struct {
- Name []string `json:"name"`
- Location string `json:"location"`
- State string `json:"state"`
- Passed bool `json:"passed"`
- RunTime time.Duration `json:"run_time"`
-
- StackTrace string `json:"stack_trace,omitempty"`
-}
-
-type SetupSummary struct {
- Name string `json:"name"`
- State string `json:"state"`
- Passed bool `json:"passed"`
- RunTime time.Duration `json:"run_time,omitempty"`
-
- StackTrace string `json:"stack_trace,omitempty"`
-}
-
-func New(writer io.Writer) *GinkgoReporter {
- logger := lager.NewLogger("ginkgo")
- logger.RegisterSink(lager.NewWriterSink(writer, lager.DEBUG))
- return &GinkgoReporter{
- writer: writer,
- logger: logger,
- }
-}
-
-type GinkgoReporter struct {
- logger lager.Logger
- writer io.Writer
- session lager.Logger
-}
-
-func (g *GinkgoReporter) wrappedWithNewlines(f func()) {
- g.writer.Write([]byte("\n"))
- f()
- g.writer.Write([]byte("\n"))
-}
-
-func (g *GinkgoReporter) SpecSuiteWillBegin(config config.GinkgoConfigType,
summary *types.SuiteSummary) {
- if config.ParallelTotal > 1 {
- var session = g.logger
- for i := 0; i < config.ParallelNode; i++ {
- session = g.logger.Session(fmt.Sprintf("node-%d", i+1))
- }
- g.logger = session
- }
-}
-
-func (g *GinkgoReporter) BeforeSuiteDidRun(setupSummary *types.SetupSummary) {
-}
-
-func (g *GinkgoReporter) SpecWillRun(specSummary *types.SpecSummary) {
- g.wrappedWithNewlines(func() {
- g.session = g.logger.Session("spec")
- g.session.Info("start", lager.Data{
- "summary": SpecSummary{
- Name: specSummary.ComponentTexts,
- Location:
specSummary.ComponentCodeLocations[len(specSummary.ComponentTexts)-1].String(),
- },
- })
- })
-}
-
-func (g *GinkgoReporter) SpecDidComplete(specSummary *types.SpecSummary) {
- g.wrappedWithNewlines(func() {
- if g.session == nil {
- return
- }
- summary := SpecSummary{
- Name: specSummary.ComponentTexts,
- Location:
specSummary.ComponentCodeLocations[len(specSummary.ComponentTexts)-1].String(),
- State: stateAsString(specSummary.State),
- Passed: passed(specSummary.State),
- RunTime: specSummary.RunTime,
- }
-
- if passed(specSummary.State) {
- g.session.Info("end", lager.Data{
- "summary": summary,
- })
- } else {
- summary.StackTrace =
specSummary.Failure.Location.FullStackTrace
- g.session.Error("end",
errorForFailure(specSummary.Failure), lager.Data{
- "summary": summary,
- })
- }
- g.session = nil
- })
-}
-
-func (g *GinkgoReporter) AfterSuiteDidRun(setupSummary *types.SetupSummary) {
-}
-
-func (g *GinkgoReporter) SpecSuiteDidEnd(summary *types.SuiteSummary) {
-}
-
-func stateAsString(state types.SpecState) string {
- switch state {
- case types.SpecStatePending:
- return "PENDING"
- case types.SpecStateSkipped:
- return "SKIPPED"
- case types.SpecStatePassed:
- return "PASSED"
- case types.SpecStateFailed:
- return "FAILED"
- case types.SpecStatePanicked:
- return "PANICKED"
- case types.SpecStateTimedOut:
- return "TIMED OUT"
- default:
- return "INVALID"
- }
-}
-
-func passed(state types.SpecState) bool {
- return !(state == types.SpecStateFailed || state ==
types.SpecStatePanicked || state == types.SpecStateTimedOut)
-}
-
-func errorForFailure(failure types.SpecFailure) error {
- message := failure.Message
- if failure.ForwardedPanic != "" {
- message += fmt.Sprintf("%s", failure.ForwardedPanic)
- }
-
- return fmt.Errorf("%s\n%s", message, failure.Location.String())
-}
diff --git a/pkg/lager/core/ginkgoreporter/ginkgoreporter_suite_test.go
b/pkg/lager/core/ginkgoreporter/ginkgoreporter_suite_test.go
deleted file mode 100644
index a95f628..0000000
--- a/pkg/lager/core/ginkgoreporter/ginkgoreporter_suite_test.go
+++ /dev/null
@@ -1,29 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package ginkgoreporter_test
-
-import (
- . "github.com/onsi/ginkgo"
- . "github.com/onsi/gomega"
-
- "testing"
-)
-
-func TestGinkgoReporter(t *testing.T) {
- RegisterFailHandler(Fail)
- RunSpecs(t, "GinkgoReporter Suite")
-}
diff --git a/pkg/lager/core/ginkgoreporter/ginkgoreporter_test.go
b/pkg/lager/core/ginkgoreporter/ginkgoreporter_test.go
deleted file mode 100644
index 663aff7..0000000
--- a/pkg/lager/core/ginkgoreporter/ginkgoreporter_test.go
+++ /dev/null
@@ -1,198 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package ginkgoreporter_test
-
-import (
- "bytes"
- "encoding/json"
- "time"
-
- "../..//lager"
- "../..//lager/chug"
- . "../..//lager/ginkgoreporter"
-
- . "github.com/onsi/ginkgo"
- "github.com/onsi/ginkgo/config"
- "github.com/onsi/ginkgo/reporters"
- "github.com/onsi/ginkgo/types"
- . "github.com/onsi/gomega"
-)
-
-var _ = Describe("Ginkgoreporter", func() {
- var (
- reporter reporters.Reporter
- buffer *bytes.Buffer
- )
-
- BeforeEach(func() {
- buffer = &bytes.Buffer{}
- reporter = New(buffer)
- })
-
- fetchLogs := func() []chug.LogEntry {
- out := make(chan chug.Entry, 1000)
- chug.Chug(buffer, out)
- logs := []chug.LogEntry{}
- for entry := range out {
- if entry.IsLager {
- logs = append(logs, entry.Log)
- }
- }
- return logs
- }
-
- jsonRoundTrip := func(object interface{}) interface{} {
- jsonEncoded, err := json.Marshal(object)
- Ω(err).ShouldNot(HaveOccurred())
- var out interface{}
- err = json.Unmarshal(jsonEncoded, &out)
- Ω(err).ShouldNot(HaveOccurred())
- return out
- }
-
- Describe("Announcing specs", func() {
- var summary *types.SpecSummary
- BeforeEach(func() {
- summary = &types.SpecSummary{
- ComponentTexts: []string{"A", "B"},
- ComponentCodeLocations: []types.CodeLocation{
- {
- FileName: "file/a",
- LineNumber: 3,
- FullStackTrace:
"some-stack-trace",
- },
- {
- FileName: "file/b",
- LineNumber: 4,
- FullStackTrace:
"some-stack-trace",
- },
- },
- RunTime: time.Minute,
- State: types.SpecStatePassed,
- }
- })
-
- Context("when running in parallel", func() {
- It("should include the node # in the session and
message", func() {
- configType := config.GinkgoConfigType{
- ParallelTotal: 3,
- ParallelNode: 2,
- }
- suiteSummary := &types.SuiteSummary{}
- reporter.SpecSuiteWillBegin(configType,
suiteSummary)
-
- reporter.SpecWillRun(summary)
- reporter.SpecDidComplete(summary)
- reporter.SpecWillRun(summary)
- reporter.SpecDidComplete(summary)
-
- logs := fetchLogs()
- Ω(logs[0].Session).Should(Equal("2.1"))
-
Ω(logs[0].Message).Should(Equal("ginkgo.node-2.spec.start"))
- Ω(logs[1].Session).Should(Equal("2.1"))
-
Ω(logs[1].Message).Should(Equal("ginkgo.node-2.spec.end"))
- Ω(logs[2].Session).Should(Equal("2.2"))
-
Ω(logs[0].Message).Should(Equal("ginkgo.node-2.spec.start"))
- Ω(logs[3].Session).Should(Equal("2.2"))
-
Ω(logs[1].Message).Should(Equal("ginkgo.node-2.spec.end"))
- })
- })
-
- Describe("incrementing sessions", func() {
- It("should increment the session counter as specs run",
func() {
- reporter.SpecWillRun(summary)
- reporter.SpecDidComplete(summary)
- reporter.SpecWillRun(summary)
- reporter.SpecDidComplete(summary)
-
- logs := fetchLogs()
- Ω(logs[0].Session).Should(Equal("1"))
- Ω(logs[1].Session).Should(Equal("1"))
- Ω(logs[2].Session).Should(Equal("2"))
- Ω(logs[3].Session).Should(Equal("2"))
- })
- })
-
- Context("when a spec starts", func() {
- BeforeEach(func() {
- reporter.SpecWillRun(summary)
- })
-
- It("should log about the spec starting", func() {
- log := fetchLogs()[0]
- Ω(log.LogLevel).Should(Equal(lager.INFO))
- Ω(log.Source).Should(Equal("ginkgo"))
-
Ω(log.Message).Should(Equal("ginkgo.spec.start"))
- Ω(log.Session).Should(Equal("1"))
-
Ω(log.Data["summary"]).Should(Equal(jsonRoundTrip(SpecSummary{
- Name: []string{"A", "B"},
- Location: "file/b:4",
- })))
- })
-
- Context("when the spec succeeds", func() {
- It("should info", func() {
- reporter.SpecDidComplete(summary)
- log := fetchLogs()[1]
-
Ω(log.LogLevel).Should(Equal(lager.INFO))
- Ω(log.Source).Should(Equal("ginkgo"))
-
Ω(log.Message).Should(Equal("ginkgo.spec.end"))
- Ω(log.Session).Should(Equal("1"))
-
Ω(log.Data["summary"]).Should(Equal(jsonRoundTrip(SpecSummary{
- Name: []string{"A", "B"},
- Location: "file/b:4",
- State: "PASSED",
- Passed: true,
- RunTime: time.Minute,
- })))
- })
- })
-
- Context("when the spec fails", func() {
- BeforeEach(func() {
- summary.State = types.SpecStateFailed
- summary.Failure = types.SpecFailure{
- Message: "something failed!",
- Location: types.CodeLocation{
- FileName:
"some/file",
- LineNumber: 3,
- FullStackTrace:
"some-stack-trace",
- },
- }
- })
-
- It("should error", func() {
- reporter.SpecDidComplete(summary)
- log := fetchLogs()[1]
-
Ω(log.LogLevel).Should(Equal(lager.ERROR))
- Ω(log.Source).Should(Equal("ginkgo"))
-
Ω(log.Message).Should(Equal("ginkgo.spec.end"))
- Ω(log.Session).Should(Equal("1"))
-
Ω(log.Error.Error()).Should(Equal("something failed!\nsome/file:3"))
-
Ω(log.Data["summary"]).Should(Equal(jsonRoundTrip(SpecSummary{
- Name: []string{"A", "B"},
- Location: "file/b:4",
- State: "FAILED",
- Passed: false,
- RunTime: time.Minute,
- StackTrace: "some-stack-trace",
- })))
- })
- })
- })
- })
-})
diff --git a/pkg/lager/core/lager_suite_test.go
b/pkg/lager/core/lager_suite_test.go
deleted file mode 100644
index 8ee4b17..0000000
--- a/pkg/lager/core/lager_suite_test.go
+++ /dev/null
@@ -1,29 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package core_test
-
-import (
- . "github.com/onsi/ginkgo"
- . "github.com/onsi/gomega"
-
- "testing"
-)
-
-func TestLager(t *testing.T) {
- RegisterFailHandler(Fail)
- RunSpecs(t, "Lager Suite")
-}
diff --git a/pkg/lager/core/lagertest/test_sink.go
b/pkg/lager/core/lagertest/test_sink.go
deleted file mode 100644
index fb91f9c..0000000
--- a/pkg/lager/core/lagertest/test_sink.go
+++ /dev/null
@@ -1,87 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package lagertest
-
-import (
- "bytes"
- "encoding/json"
- "io"
-
- "github.com/onsi/ginkgo"
- "github.com/onsi/gomega/gbytes"
-
- "github.com/apache/incubator-servicecomb-service-center/pkg/lager"
-)
-
-type TestLogger struct {
- lager.Logger
- *TestSink
-}
-
-type TestSink struct {
- lager.Sink
- buffer *gbytes.Buffer
-}
-
-func NewTestLogger(component string) *TestLogger {
- logger := lager.NewLogger(component)
-
- testSink := NewTestSink()
- logger.RegisterSink(testSink)
- logger.RegisterSink(lager.NewWriterSink(ginkgo.GinkgoWriter,
lager.DEBUG))
-
- return &TestLogger{logger, testSink}
-}
-
-func NewTestSink() *TestSink {
- buffer := gbytes.NewBuffer()
-
- return &TestSink{
- Sink: lager.NewWriterSink(buffer, lager.DEBUG),
- buffer: buffer,
- }
-}
-
-func (s *TestSink) Buffer() *gbytes.Buffer {
- return s.buffer
-}
-
-func (s *TestSink) Logs() []lager.LogFormat {
- logs := []lager.LogFormat{}
-
- decoder := json.NewDecoder(bytes.NewBuffer(s.buffer.Contents()))
- for {
- var log lager.LogFormat
- if err := decoder.Decode(&log); err == io.EOF {
- return logs
- } else if err != nil {
- panic(err)
- }
- logs = append(logs, log)
- }
-
- return logs
-}
-
-func (s *TestSink) LogMessages() []string {
- logs := s.Logs()
- messages := make([]string, 0, len(logs))
- for _, log := range logs {
- messages = append(messages, log.Message)
- }
- return messages
-}
diff --git a/pkg/lager/core/logger.go b/pkg/lager/core/logger.go
deleted file mode 100644
index 23e052a..0000000
--- a/pkg/lager/core/logger.go
+++ /dev/null
@@ -1,310 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package core
-
-import (
- "bytes"
- "fmt"
- "os"
- "runtime"
- "strconv"
- "strings"
- "sync/atomic"
- "time"
- "unsafe"
-)
-
-const STACK_TRACE_BUFFER_SIZE = 1024 * 100
-
-var processID = os.Getpid()
-
-type Logger interface {
- RegisterSink(Sink)
- Session(task string, data ...Data) Logger
- SessionName() string
- Debug(action string, data ...Data)
- Info(action string, data ...Data)
- Warn(action string, err error, data ...Data)
- Error(action string, err error, data ...Data)
- Fatal(action string, err error, data ...Data)
- Debugf(format string, args ...interface{})
- Infof(format string, args ...interface{})
- Warnf(err error, format string, args ...interface{})
- Errorf(err error, format string, args ...interface{})
- Fatalf(err error, format string, args ...interface{})
- WithData(Data) Logger
-}
-
-type logger struct {
- component string
- task string
- sinks []Sink
- sessionID string
- nextSession uint64
- data Data
- logFormatText bool
-}
-
-func NewLoggerExt(component string, isFormatText bool) Logger {
- return &logger{
- component: component,
- task: component,
- sinks: []Sink{},
- data: Data{},
- logFormatText: isFormatText,
- }
-}
-
-func NewLogger(component string) Logger {
- return NewLoggerExt(component, true)
-}
-
-func (l *logger) RegisterSink(sink Sink) {
- l.sinks = append(l.sinks, sink)
-}
-
-func (l *logger) SessionName() string {
- return l.task
-}
-
-func (l *logger) Session(task string, data ...Data) Logger {
- sid := atomic.AddUint64(&l.nextSession, 1)
-
- var sessionIDstr string
-
- if l.sessionID != "" {
- sessionIDstr = fmt.Sprintf("%s.%d", l.sessionID, sid)
- } else {
- sessionIDstr = fmt.Sprintf("%d", sid)
- }
-
- return &logger{
- component: l.component,
- task: fmt.Sprintf("%s.%s", l.task, task),
- sinks: l.sinks,
- sessionID: sessionIDstr,
- data: l.baseData(data...),
- }
-}
-
-func (l *logger) WithData(data Data) Logger {
- return &logger{
- component: l.component,
- task: l.task,
- sinks: l.sinks,
- sessionID: l.sessionID,
- data: l.baseData(data),
- }
-}
-
-func (l *logger) activeSinks(loglevel LogLevel) []Sink {
- ss := make([]Sink, len(l.sinks))
- idx := 0
- for _, itf := range l.sinks {
- if s, ok := itf.(*writerSink); ok && loglevel < s.minLogLevel {
- continue
- }
- if s, ok := itf.(*ReconfigurableSink); ok && loglevel <
LogLevel(atomic.LoadInt32(&s.minLogLevel)) {
- continue
- }
- ss[idx] = itf
- idx++
- }
- return ss[:idx]
-}
-
-func (l *logger) log(loglevel LogLevel, action string, err error, data
...Data) {
- ss := l.activeSinks(loglevel)
- if len(ss) == 0 {
- return
- }
- l.logs(ss, loglevel, action, err, data...)
-}
-
-func (l *logger) logs(ss []Sink, loglevel LogLevel, action string, err error,
data ...Data) {
- logData := l.baseData(data...)
-
- if err != nil {
- logData["error"] = err.Error()
- }
-
- if loglevel == FATAL {
- stackTrace := make([]byte, STACK_TRACE_BUFFER_SIZE)
- stackSize := runtime.Stack(stackTrace, false)
- stackTrace = stackTrace[:stackSize]
-
- logData["trace"] = *(*string)(unsafe.Pointer(&stackTrace))
- }
-
- log := LogFormat{
- Timestamp: currentTimestamp(),
- Source: l.component,
- Message: strconv.QuoteToGraphic(action),
- LogLevel: loglevel,
- Data: logData,
- }
-
- // add process_id, file, lineno, method to log data
- addExtLogInfo(&log)
-
- for _, sink := range ss {
- if !(l.logFormatText) {
- log.Message = l.task + "." + log.Message
- jsondata, jserr := log.ToJSON()
- if jserr != nil {
- fmt.Printf("[lager] ToJSON() ERROR! action: %s,
jserr: %s, log: %s\n", action, jserr, log)
-
- // also output json marshal error event to sink
- log.Data = Data{"Data": fmt.Sprint(logData)}
- jsonerrdata, _ := log.ToJSON()
- sink.Log(ERROR, jsonerrdata)
-
- continue
- }
- sink.Log(loglevel, jsondata)
- } else {
- levelstr :=
strings.ToUpper(FormatLogLevel(log.LogLevel))
- buf := bytes.Buffer{}
- buf.WriteString(fmt.Sprintf("%s %s %s %d %s %s():%d %s",
- log.Timestamp, levelstr, log.Source,
log.ProcessID, log.File, log.Method, log.LineNo, log.Message))
- if err != nil {
- buf.WriteString(fmt.Sprintf("(error: %s)",
logData["error"]))
- }
- if loglevel == FATAL {
- buf.WriteString(fmt.Sprintf("(trace: %s)",
logData["trace"]))
- }
- sink.Log(loglevel, buf.Bytes())
- }
- }
-
- if loglevel == FATAL {
- panic(err)
- }
-}
-
-func (l *logger) Debug(action string, data ...Data) {
- l.log(DEBUG, action, nil, data...)
-}
-
-func (l *logger) Info(action string, data ...Data) {
- l.log(INFO, action, nil, data...)
-}
-
-func (l *logger) Warn(action string, err error, data ...Data) {
- l.log(WARN, action, err, data...)
-}
-
-func (l *logger) Error(action string, err error, data ...Data) {
- l.log(ERROR, action, err, data...)
-}
-
-func (l *logger) Fatal(action string, err error, data ...Data) {
- l.log(FATAL, action, err, data...)
-}
-
-func (l *logger) logf(loglevel LogLevel, err error, format string, args
...interface{}) {
- ss := l.activeSinks(loglevel)
- if len(ss) == 0 {
- return
- }
- logmsg := fmt.Sprintf(format, args...)
- l.logs(ss, loglevel, logmsg, err)
-}
-
-func (l *logger) Debugf(format string, args ...interface{}) {
- l.logf(DEBUG, nil, format, args...)
-}
-
-func (l *logger) Infof(format string, args ...interface{}) {
- l.logf(INFO, nil, format, args...)
-}
-
-func (l *logger) Warnf(err error, format string, args ...interface{}) {
- l.logf(WARN, err, format, args...)
-}
-
-func (l *logger) Errorf(err error, format string, args ...interface{}) {
- l.logf(ERROR, err, format, args...)
-}
-
-func (l *logger) Fatalf(err error, format string, args ...interface{}) {
- l.logf(FATAL, err, format, args...)
-}
-
-func (l *logger) baseData(givenData ...Data) Data {
- data := Data{}
-
- for k, v := range l.data {
- data[k] = v
- }
-
- if len(givenData) > 0 {
- for _, dataArg := range givenData {
- for key, val := range dataArg {
- data[key] = val
- }
- }
- }
-
- if l.sessionID != "" {
- data["session"] = l.sessionID
- }
-
- return data
-}
-
-func currentTimestamp() string {
- return time.Now().Format("2006-01-02T15:04:05.000Z07:00")
-}
-
-func addExtLogInfo(logf *LogFormat) {
- logf.ProcessID = processID
-
- for i := 3; i <= 5; i++ {
- pc, file, line, ok := runtime.Caller(i)
-
- if strings.Index(file, "logger.go") > 0 {
- continue
- }
-
- if ok {
- idx := strings.LastIndex(file, "/")
- switch {
- case idx >= 0:
- logf.File = file[idx+1:]
- default:
- logf.File = file
- }
- logf.LineNo = line
- if f := runtime.FuncForPC(pc); f != nil {
- logf.Method = formatFuncName(f.Name())
- }
- }
- break
- }
-}
-
-func formatFuncName(f string) string {
- i := strings.LastIndex(f, "/")
- j := strings.Index(f[i+1:], ".")
- if j < 1 {
- return "???"
- }
- _, fun := f[:i+j+1], f[i+j+2:]
- i = strings.LastIndex(fun, ".")
- return fun[i+1:]
-}
diff --git a/pkg/lager/core/logger_test.go b/pkg/lager/core/logger_test.go
deleted file mode 100644
index cd74447..0000000
--- a/pkg/lager/core/logger_test.go
+++ /dev/null
@@ -1,374 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package core_test
-
-import (
- "errors"
- "fmt"
- "strconv"
- "time"
-
- "..//lager"
- "..//lager/lagertest"
-
- . "github.com/onsi/ginkgo"
- . "github.com/onsi/gomega"
-)
-
-var _ = Describe("Logger", func() {
- var logger lager.Logger
- var testSink *lagertest.TestSink
-
- var component = "my-component"
- var action = "my-action"
- var logData = lager.Data{
- "foo": "bar",
- "a-number": 7,
- }
- var anotherLogData = lager.Data{
- "baz": "quux",
- "b-number": 43,
- }
-
- BeforeEach(func() {
- logger = lager.NewLogger(component)
- testSink = lagertest.NewTestSink()
- logger.RegisterSink(testSink)
- })
-
- var TestCommonLogFeatures = func(level lager.LogLevel) {
- var log lager.LogFormat
-
- BeforeEach(func() {
- log = testSink.Logs()[0]
- })
-
- It("writes a log to the sink", func() {
- Ω(testSink.Logs()).Should(HaveLen(1))
- })
-
- It("records the source component", func() {
- Ω(log.Source).Should(Equal(component))
- })
-
- It("outputs a properly-formatted message", func() {
- Ω(log.Message).Should(Equal(fmt.Sprintf("%s.%s",
component, action)))
- })
-
- It("has a timestamp", func() {
- expectedTime := float64(time.Now().UnixNano()) / 1e9
- parsedTimestamp, err :=
strconv.ParseFloat(log.Timestamp, 64)
- Ω(err).ShouldNot(HaveOccurred())
- Ω(parsedTimestamp).Should(BeNumerically("~",
expectedTime, 1.0))
- })
-
- It("sets the proper output level", func() {
- Ω(log.LogLevel).Should(Equal(level))
- })
- }
-
- var TestLogData = func() {
- var log lager.LogFormat
-
- BeforeEach(func() {
- log = testSink.Logs()[0]
- })
-
- It("data contains custom user data", func() {
- Ω(log.Data["foo"]).Should(Equal("bar"))
- Ω(log.Data["a-number"]).Should(BeNumerically("==", 7))
- Ω(log.Data["baz"]).Should(Equal("quux"))
- Ω(log.Data["b-number"]).Should(BeNumerically("==", 43))
- })
- }
-
- Describe("Session", func() {
- var session lager.Logger
-
- BeforeEach(func() {
- session = logger.Session("sub-action")
- })
-
- Describe("the returned logger", func() {
- JustBeforeEach(func() {
- session.Debug("some-debug-action",
lager.Data{"level": "debug"})
- session.Info("some-info-action",
lager.Data{"level": "info"})
- session.Error("some-error-action",
errors.New("oh no!"), lager.Data{"level": "error"})
-
- defer func() {
- recover()
- }()
-
- session.Fatal("some-fatal-action",
errors.New("oh no!"), lager.Data{"level": "fatal"})
- })
-
- It("logs with a shared session id in the data", func() {
-
Ω(testSink.Logs()[0].Data["session"]).Should(Equal("1"))
-
Ω(testSink.Logs()[1].Data["session"]).Should(Equal("1"))
-
Ω(testSink.Logs()[2].Data["session"]).Should(Equal("1"))
-
Ω(testSink.Logs()[3].Data["session"]).Should(Equal("1"))
- })
-
- It("logs with the task added to the message", func() {
-
Ω(testSink.Logs()[0].Message).Should(Equal("my-component.sub-action.some-debug-action"))
-
Ω(testSink.Logs()[1].Message).Should(Equal("my-component.sub-action.some-info-action"))
-
Ω(testSink.Logs()[2].Message).Should(Equal("my-component.sub-action.some-error-action"))
-
Ω(testSink.Logs()[3].Message).Should(Equal("my-component.sub-action.some-fatal-action"))
- })
-
- It("logs with the original data", func() {
-
Ω(testSink.Logs()[0].Data["level"]).Should(Equal("debug"))
-
Ω(testSink.Logs()[1].Data["level"]).Should(Equal("info"))
-
Ω(testSink.Logs()[2].Data["level"]).Should(Equal("error"))
-
Ω(testSink.Logs()[3].Data["level"]).Should(Equal("fatal"))
- })
-
- Context("with data", func() {
- BeforeEach(func() {
- session = logger.Session("sub-action",
lager.Data{"foo": "bar"})
- })
-
- It("logs with the data added to the message",
func() {
-
Ω(testSink.Logs()[0].Data["foo"]).Should(Equal("bar"))
-
Ω(testSink.Logs()[1].Data["foo"]).Should(Equal("bar"))
-
Ω(testSink.Logs()[2].Data["foo"]).Should(Equal("bar"))
-
Ω(testSink.Logs()[3].Data["foo"]).Should(Equal("bar"))
- })
-
- It("keeps the original data", func() {
-
Ω(testSink.Logs()[0].Data["level"]).Should(Equal("debug"))
-
Ω(testSink.Logs()[1].Data["level"]).Should(Equal("info"))
-
Ω(testSink.Logs()[2].Data["level"]).Should(Equal("error"))
-
Ω(testSink.Logs()[3].Data["level"]).Should(Equal("fatal"))
- })
- })
-
- Context("with another session", func() {
- BeforeEach(func() {
- session =
logger.Session("next-sub-action")
- })
-
- It("logs with a shared session id in the data",
func() {
-
Ω(testSink.Logs()[0].Data["session"]).Should(Equal("2"))
-
Ω(testSink.Logs()[1].Data["session"]).Should(Equal("2"))
-
Ω(testSink.Logs()[2].Data["session"]).Should(Equal("2"))
-
Ω(testSink.Logs()[3].Data["session"]).Should(Equal("2"))
- })
-
- It("logs with the task added to the message",
func() {
-
Ω(testSink.Logs()[0].Message).Should(Equal("my-component.next-sub-action.some-debug-action"))
-
Ω(testSink.Logs()[1].Message).Should(Equal("my-component.next-sub-action.some-info-action"))
-
Ω(testSink.Logs()[2].Message).Should(Equal("my-component.next-sub-action.some-error-action"))
-
Ω(testSink.Logs()[3].Message).Should(Equal("my-component.next-sub-action.some-fatal-action"))
- })
- })
-
- Describe("WithData", func() {
- BeforeEach(func() {
- session =
logger.WithData(lager.Data{"foo": "bar"})
- })
-
- It("returns a new logger with the given data",
func() {
-
Ω(testSink.Logs()[0].Data["foo"]).Should(Equal("bar"))
-
Ω(testSink.Logs()[1].Data["foo"]).Should(Equal("bar"))
-
Ω(testSink.Logs()[2].Data["foo"]).Should(Equal("bar"))
-
Ω(testSink.Logs()[3].Data["foo"]).Should(Equal("bar"))
- })
-
- It("does not append to the logger's task",
func() {
-
Ω(testSink.Logs()[0].Message).Should(Equal("my-component.some-debug-action"))
- })
- })
-
- Context("with a nested session", func() {
- BeforeEach(func() {
- session =
session.Session("sub-sub-action")
- })
-
- It("logs with a shared session id in the data",
func() {
-
Ω(testSink.Logs()[0].Data["session"]).Should(Equal("1.1"))
-
Ω(testSink.Logs()[1].Data["session"]).Should(Equal("1.1"))
-
Ω(testSink.Logs()[2].Data["session"]).Should(Equal("1.1"))
-
Ω(testSink.Logs()[3].Data["session"]).Should(Equal("1.1"))
- })
-
- It("logs with the task added to the message",
func() {
-
Ω(testSink.Logs()[0].Message).Should(Equal("my-component.sub-action.sub-sub-action.some-debug-action"))
-
Ω(testSink.Logs()[1].Message).Should(Equal("my-component.sub-action.sub-sub-action.some-info-action"))
-
Ω(testSink.Logs()[2].Message).Should(Equal("my-component.sub-action.sub-sub-action.some-error-action"))
-
Ω(testSink.Logs()[3].Message).Should(Equal("my-component.sub-action.sub-sub-action.some-fatal-action"))
- })
- })
- })
- })
-
- Describe("Debug", func() {
- Context("with log data", func() {
- BeforeEach(func() {
- logger.Debug(action, logData, anotherLogData)
- })
-
- TestCommonLogFeatures(lager.DEBUG)
- TestLogData()
- })
-
- Context("with no log data", func() {
- BeforeEach(func() {
- logger.Debug(action)
- })
-
- TestCommonLogFeatures(lager.DEBUG)
- })
- })
-
- Describe("Info", func() {
- Context("with log data", func() {
- BeforeEach(func() {
- logger.Info(action, logData, anotherLogData)
- })
-
- TestCommonLogFeatures(lager.INFO)
- TestLogData()
- })
-
- Context("with no log data", func() {
- BeforeEach(func() {
- logger.Info(action)
- })
-
- TestCommonLogFeatures(lager.INFO)
- })
- })
-
- Describe("Error", func() {
- var err = errors.New("oh noes!")
- Context("with log data", func() {
- BeforeEach(func() {
- logger.Error(action, err, logData,
anotherLogData)
- })
-
- TestCommonLogFeatures(lager.ERROR)
- TestLogData()
-
- It("data contains error message", func() {
-
Ω(testSink.Logs()[0].Data["error"]).Should(Equal(err.Error()))
- })
- })
-
- Context("with no log data", func() {
- BeforeEach(func() {
- logger.Error(action, err)
- })
-
- TestCommonLogFeatures(lager.ERROR)
-
- It("data contains error message", func() {
-
Ω(testSink.Logs()[0].Data["error"]).Should(Equal(err.Error()))
- })
- })
-
- Context("with no error", func() {
- BeforeEach(func() {
- logger.Error(action, nil)
- })
-
- TestCommonLogFeatures(lager.ERROR)
-
- It("does not contain the error message", func() {
-
Ω(testSink.Logs()[0].Data).ShouldNot(HaveKey("error"))
- })
- })
- })
-
- Describe("Fatal", func() {
- var err = errors.New("oh noes!")
- var fatalErr interface{}
-
- Context("with log data", func() {
- BeforeEach(func() {
- defer func() {
- fatalErr = recover()
- }()
-
- logger.Fatal(action, err, logData,
anotherLogData)
- })
-
- TestCommonLogFeatures(lager.FATAL)
- TestLogData()
-
- It("data contains error message", func() {
-
Ω(testSink.Logs()[0].Data["error"]).Should(Equal(err.Error()))
- })
-
- It("data contains stack trace", func() {
-
Ω(testSink.Logs()[0].Data["trace"]).ShouldNot(BeEmpty())
- })
-
- It("panics with the provided error", func() {
- Ω(fatalErr).Should(Equal(err))
- })
- })
-
- Context("with no log data", func() {
- BeforeEach(func() {
- defer func() {
- fatalErr = recover()
- }()
-
- logger.Fatal(action, err)
- })
-
- TestCommonLogFeatures(lager.FATAL)
-
- It("data contains error message", func() {
-
Ω(testSink.Logs()[0].Data["error"]).Should(Equal(err.Error()))
- })
-
- It("data contains stack trace", func() {
-
Ω(testSink.Logs()[0].Data["trace"]).ShouldNot(BeEmpty())
- })
-
- It("panics with the provided error", func() {
- Ω(fatalErr).Should(Equal(err))
- })
- })
-
- Context("with no error", func() {
- BeforeEach(func() {
- defer func() {
- fatalErr = recover()
- }()
-
- logger.Fatal(action, nil)
- })
-
- TestCommonLogFeatures(lager.FATAL)
-
- It("does not contain the error message", func() {
-
Ω(testSink.Logs()[0].Data).ShouldNot(HaveKey("error"))
- })
-
- It("data contains stack trace", func() {
-
Ω(testSink.Logs()[0].Data["trace"]).ShouldNot(BeEmpty())
- })
-
- It("panics with the provided error (i.e. nil)", func() {
- Ω(fatalErr).Should(BeNil())
- })
- })
- })
-})
diff --git a/pkg/lager/core/models.go b/pkg/lager/core/models.go
deleted file mode 100644
index 6821767..0000000
--- a/pkg/lager/core/models.go
+++ /dev/null
@@ -1,101 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package core
-
-import (
- "bytes"
- "encoding/json"
-)
-
-type LogLevel int
-
-const (
- DEBUG LogLevel = iota
- INFO
- WARN
- ERROR
- FATAL
-)
-
-func FormatLogLevel(x LogLevel) string {
- var level string
- switch x {
- case DEBUG:
- level = "debug"
- case INFO:
- level = "info"
- case WARN:
- level = "warn"
- case ERROR:
- level = "error"
- case FATAL:
- level = "fatal"
- }
- return level
-}
-
-func (x LogLevel) MarshalJSON() ([]byte, error) {
- // var level string
- var level = FormatLogLevel(x)
- return json.Marshal(level)
-}
-
-/*
-func (x LogLevel) MarshalJSON() ([]byte, error) {
- var level string
- switch x {
- case DEBUG:
- level = "debug"
- case INFO:
- level = "info"
- case WARN:
- level = "warn"
- case ERROR:
- level = "error"
- case FATAL:
- level = "fatal"
- }
- return json.Marshal(level)
-}
-*/
-
-type Data map[string]interface{}
-
-type LogFormat struct {
- Timestamp string `json:"timestamp"`
- Source string `json:"source"`
- Message string `json:"message"`
- LogLevel LogLevel `json:"log_level"`
- Data Data `json:"data"`
- ProcessID int `json:"process_id"`
- File string `json:"file"`
- LineNo int `json:"lineno"`
- Method string `json:"method"`
-}
-
-func prettyPrint(in []byte) []byte {
- var out bytes.Buffer
- err := json.Indent(&out, in, "", "\t")
- if err != nil {
- return in
- }
- return out.Bytes()
-}
-func (log LogFormat) ToJSON() ([]byte, error) {
- j, err := json.Marshal(log)
- return prettyPrint(j), err
-}
diff --git a/pkg/lager/core/reconfigurable_sink.go
b/pkg/lager/core/reconfigurable_sink.go
deleted file mode 100644
index 4d4247c..0000000
--- a/pkg/lager/core/reconfigurable_sink.go
+++ /dev/null
@@ -1,51 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package core
-
-import "sync/atomic"
-
-type ReconfigurableSink struct {
- sink Sink
-
- minLogLevel int32
-}
-
-func NewReconfigurableSink(sink Sink, initialMinLogLevel LogLevel)
*ReconfigurableSink {
- return &ReconfigurableSink{
- sink: sink,
-
- minLogLevel: int32(initialMinLogLevel),
- }
-}
-
-func (sink *ReconfigurableSink) Log(level LogLevel, log []byte) {
- minLogLevel := LogLevel(atomic.LoadInt32(&sink.minLogLevel))
-
- if level < minLogLevel {
- return
- }
-
- sink.sink.Log(level, log)
-}
-
-func (sink *ReconfigurableSink) SetMinLevel(level LogLevel) {
- atomic.StoreInt32(&sink.minLogLevel, int32(level))
-}
-
-func (sink *ReconfigurableSink) GetMinLevel() LogLevel {
- return LogLevel(atomic.LoadInt32(&sink.minLogLevel))
-}
diff --git a/pkg/lager/core/reconfigurable_sink_test.go
b/pkg/lager/core/reconfigurable_sink_test.go
deleted file mode 100644
index 4225da8..0000000
--- a/pkg/lager/core/reconfigurable_sink_test.go
+++ /dev/null
@@ -1,79 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package core_test
-
-import (
- "..//lager"
- "..//lager/lagertest"
-
- . "github.com/onsi/ginkgo"
- . "github.com/onsi/gomega"
- "github.com/onsi/gomega/gbytes"
-)
-
-var _ = Describe("ReconfigurableSink", func() {
- var (
- testSink *lagertest.TestSink
-
- sink *lager.ReconfigurableSink
- )
-
- BeforeEach(func() {
- testSink = lagertest.NewTestSink()
-
- sink = lager.NewReconfigurableSink(testSink, lager.INFO)
- })
-
- It("returns the current level", func() {
- Ω(sink.GetMinLevel()).Should(Equal(lager.INFO))
- })
-
- Context("when logging above the minimum log level", func() {
- BeforeEach(func() {
- sink.Log(lager.INFO, []byte("hello world"))
- })
-
- It("writes to the given sink", func() {
- Ω(testSink.Buffer()).Should(gbytes.Say("hello world\n"))
- })
- })
-
- Context("when logging below the minimum log level", func() {
- BeforeEach(func() {
- sink.Log(lager.DEBUG, []byte("hello world"))
- })
-
- It("does not write to the given writer", func() {
- Ω(testSink.Buffer().Contents()).Should(BeEmpty())
- })
- })
-
- Context("when reconfigured to a new log level", func() {
- BeforeEach(func() {
- sink.SetMinLevel(lager.DEBUG)
- })
-
- It("writes logs above the new log level", func() {
- sink.Log(lager.DEBUG, []byte("hello world"))
- Ω(testSink.Buffer()).Should(gbytes.Say("hello world\n"))
- })
-
- It("returns the newly updated level", func() {
- Ω(sink.GetMinLevel()).Should(Equal(lager.DEBUG))
- })
- })
-})
diff --git a/pkg/lager/core/writer_sink.go b/pkg/lager/core/writer_sink.go
deleted file mode 100644
index 69a735c..0000000
--- a/pkg/lager/core/writer_sink.go
+++ /dev/null
@@ -1,56 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package core
-
-import (
- "io"
- "sync"
-)
-
-const logBufferSize = 1024
-
-// A Sink represents a write destination for a Logger. It provides
-// a thread-safe interface for writing logs
-type Sink interface {
- //Log to the sink. Best effort -- no need to worry about errors.
- Log(level LogLevel, payload []byte)
-}
-
-type writerSink struct {
- writer io.Writer
- minLogLevel LogLevel
- writeL *sync.Mutex
-}
-
-func NewWriterSink(writer io.Writer, minLogLevel LogLevel) Sink {
- return &writerSink{
- writer: writer,
- minLogLevel: minLogLevel,
- writeL: new(sync.Mutex),
- }
-}
-
-func (sink *writerSink) Log(level LogLevel, log []byte) {
- if level < sink.minLogLevel {
- return
- }
-
- log = append(log, '\n')
- sink.writeL.Lock()
- sink.writer.Write(log)
- sink.writeL.Unlock()
-}
diff --git a/pkg/lager/core/writer_sink_test.go
b/pkg/lager/core/writer_sink_test.go
deleted file mode 100644
index d1ec80c..0000000
--- a/pkg/lager/core/writer_sink_test.go
+++ /dev/null
@@ -1,120 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package core_test
-
-import (
- "runtime"
- "sync"
-
- "..//lager"
-
- . "github.com/onsi/ginkgo"
- . "github.com/onsi/gomega"
-)
-
-var _ = Describe("WriterSink", func() {
- const MaxThreads = 100
-
- var sink lager.Sink
- var writer *copyWriter
-
- BeforeSuite(func() {
- runtime.GOMAXPROCS(MaxThreads)
- })
-
- BeforeEach(func() {
- writer = NewCopyWriter()
- sink = lager.NewWriterSink(writer, lager.INFO)
- })
-
- Context("when logging above the minimum log level", func() {
- BeforeEach(func() {
- sink.Log(lager.INFO, []byte("hello world"))
- })
-
- It("writes to the given writer", func() {
- Ω(writer.Copy()).Should(Equal([]byte("hello world\n")))
- })
- })
-
- Context("when logging below the minimum log level", func() {
- BeforeEach(func() {
- sink.Log(lager.DEBUG, []byte("hello world"))
- })
-
- It("does not write to the given writer", func() {
- Ω(writer.Copy()).Should(Equal([]byte{}))
- })
- })
-
- Context("when logging from multiple threads", func() {
- var content = "abcdefg "
-
- BeforeEach(func() {
- wg := new(sync.WaitGroup)
- for i := 0; i < MaxThreads; i++ {
- wg.Add(1)
- go func() {
- sink.Log(lager.INFO, []byte(content))
- wg.Done()
- }()
- }
- wg.Wait()
- })
-
- It("writes to the given writer", func() {
- expectedBytes := []byte{}
- for i := 0; i < MaxThreads; i++ {
- expectedBytes = append(expectedBytes,
[]byte(content)...)
- expectedBytes = append(expectedBytes,
[]byte("\n")...)
- }
- Ω(writer.Copy()).Should(Equal(expectedBytes))
- })
- })
-})
-
-// copyWriter is an INTENTIONALLY UNSAFE writer. Use it to test code that
-// should be handling thread safety.
-type copyWriter struct {
- contents []byte
- lock *sync.RWMutex
-}
-
-func NewCopyWriter() *copyWriter {
- return ©Writer{
- contents: []byte{},
- lock: new(sync.RWMutex),
- }
-}
-
-// no, we really mean RLock on write.
-func (writer *copyWriter) Write(p []byte) (n int, err error) {
- writer.lock.RLock()
- defer writer.lock.RUnlock()
-
- writer.contents = append(writer.contents, p...)
- return len(p), nil
-}
-
-func (writer *copyWriter) Copy() []byte {
- writer.lock.Lock()
- defer writer.lock.Unlock()
-
- contents := make([]byte, len(writer.contents))
- copy(contents, writer.contents)
- return contents
-}
diff --git a/pkg/lager/examples/main.go b/pkg/lager/examples/main.go
deleted file mode 100644
index e708d22..0000000
--- a/pkg/lager/examples/main.go
+++ /dev/null
@@ -1,50 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package main
-
-import (
- "fmt"
-
- "github.com/apache/incubator-servicecomb-service-center/pkg/lager"
-)
-
-func main() {
- logger.Init(logger.Config{
- LoggerLevel: "DEBUG",
- LoggerFile: "",
- EnableRsyslog: false,
- LogFormatText: false,
- })
-
- logger := logger.NewLogger("example")
-
- logger.Infof("Hi %s, system is starting up ...", "paas-bot")
-
- logger.Debug("check-info", lager.Data{
- "info": "something",
- })
-
- err := fmt.Errorf("Oops, error occurred!")
- logger.Warn("failed-to-do-somthing", err, lager.Data{
- "info": "something",
- })
-
- err = fmt.Errorf("This is an error")
- logger.Error("failed-to-do-somthing", err)
-
- logger.Info("shutting-down")
-}
diff --git a/pkg/lager/lager.go b/pkg/lager/lager.go
deleted file mode 100644
index 83fb4a4..0000000
--- a/pkg/lager/lager.go
+++ /dev/null
@@ -1,142 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package lager
-
-import (
- "fmt"
- "log"
- "os"
- "strings"
-
- "github.com/apache/incubator-servicecomb-service-center/pkg/lager/core"
-
"github.com/apache/incubator-servicecomb-service-center/pkg/lager/syslog"
-)
-
-const (
- DEBUG = "DEBUG"
- INFO = "INFO"
- WARN = "WARN"
- ERROR = "ERROR"
- FATAL = "FATAL"
-)
-
-type Config struct {
- LoggerLevel string
- LoggerFile string
-
- EnableRsyslog bool
- RsyslogNetwork string
- RsyslogAddr string
-
- LogFormatText bool
-
- EnableStdOut bool
-}
-
-func GetConfig() *Config {
- return config
-}
-
-var config *Config = DefaultConfig()
-
-func DefaultConfig() *Config {
- return &Config{
- LoggerLevel: INFO,
- LoggerFile: "",
- EnableRsyslog: false,
- RsyslogNetwork: "udp",
- RsyslogAddr: "127.0.0.1:5140",
- LogFormatText: false,
- EnableStdOut: false,
- }
-}
-
-func Init(c Config) {
- if c.LoggerLevel != "" {
- config.LoggerLevel = c.LoggerLevel
- }
-
- if c.LoggerFile != "" {
- config.LoggerFile = c.LoggerFile
- }
-
- if c.EnableRsyslog {
- config.EnableRsyslog = c.EnableRsyslog
- }
-
- if c.RsyslogNetwork != "" {
- config.RsyslogNetwork = c.RsyslogNetwork
- }
-
- if c.RsyslogAddr != "" {
- config.RsyslogAddr = c.RsyslogAddr
- }
-
- config.EnableStdOut = c.EnableStdOut
- config.LogFormatText = c.LogFormatText
-}
-
-func NewLogger(component string) core.Logger {
- return NewLoggerExt(component, component, config)
-}
-
-func NewLoggerExt(component string, app_guid string, config *Config)
core.Logger {
- var lagerLogLevel core.LogLevel
- switch strings.ToUpper(config.LoggerLevel) {
- case DEBUG:
- lagerLogLevel = core.DEBUG
- case INFO:
- lagerLogLevel = core.INFO
- case WARN:
- lagerLogLevel = core.WARN
- case ERROR:
- lagerLogLevel = core.ERROR
- case FATAL:
- lagerLogLevel = core.FATAL
- default:
- panic(fmt.Errorf("unknown logger level: %s",
config.LoggerLevel))
- }
-
- logger := core.NewLoggerExt(component, config.LogFormatText)
- if config.EnableStdOut {
- sink :=
core.NewReconfigurableSink(core.NewWriterSink(os.Stdout, core.DEBUG),
lagerLogLevel)
- logger.RegisterSink(sink)
- }
-
- if config.LoggerFile != "" {
- file, err := os.OpenFile(config.LoggerFile,
os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0600)
- if err != nil {
- panic(err)
- }
-
- sink := core.NewReconfigurableSink(core.NewWriterSink(file,
core.DEBUG), lagerLogLevel)
- logger.RegisterSink(sink)
- }
-
- if config.EnableRsyslog {
- syslog, err := syslog.Dial(component, app_guid,
config.RsyslogNetwork, config.RsyslogAddr)
- if err != nil {
- //warn, not panic
- log.Println(err.Error())
- } else {
- sink :=
core.NewReconfigurableSink(core.NewWriterSink(syslog, core.DEBUG),
lagerLogLevel)
- logger.RegisterSink(sink)
- }
- }
-
- return logger
-}
diff --git a/pkg/lager/syslog/syslog.go b/pkg/lager/syslog/syslog.go
deleted file mode 100644
index 5db0a5b..0000000
--- a/pkg/lager/syslog/syslog.go
+++ /dev/null
@@ -1,92 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package syslog
-
-import (
- "errors"
- "fmt"
- "net"
- "os"
- "time"
-)
-
-type Writer struct {
- conn net.Conn
-}
-
-var syslogHeader string
-
-func New() (*Writer, error) {
- return Dial("", "", "", "")
-}
-
-func Dial(component, appguid, network, raddr string) (*Writer, error) {
-
- hostname, _ := os.Hostname()
- // construct syslog header the same to rsyslog's,
- // origin, node_id, app_guid, instance_id, loglevel
- syslogHeader = fmt.Sprintf("%s %s %s %s %s", component, component,
appguid, hostname, "all")
-
- var conn net.Conn
- var err error
- if network == "" {
- conn, err = unixSyslog()
- } else {
- conn, err = net.Dial(network, raddr)
- }
- return &Writer{
- conn: conn,
- }, err
-}
-
-func (r *Writer) Write(b []byte) (int, error) {
- nl := ""
- if len(b) == 0 || b[len(b)-1] != '\n' {
- nl = "\n"
- }
-
- r.conn.SetWriteDeadline(time.Now().Add(1 * time.Second))
-
- _, err := fmt.Fprintf(r.conn, " %s %s%s", syslogHeader, b, nl)
- if err != nil {
- return 0, err
- }
-
- return len(b), nil
-}
-
-func (r *Writer) Close() error {
- return r.conn.Close()
-}
-
-func unixSyslog() (net.Conn, error) {
- logTypes := []string{"unixgram", "unix"}
- logPaths := []string{"/dev/log", "/var/run/syslog"}
- var raddr string
- for _, network := range logTypes {
- for _, path := range logPaths {
- raddr = path
- conn, err := net.Dial(network, raddr)
- if err != nil {
- continue
- } else {
- return conn, nil
- }
- }
- }
- return nil, errors.New("Could not connect to local syslog socket")
-}
diff --git a/pkg/util/log.go b/pkg/util/log.go
index 00de0b8..5e475a7 100644
--- a/pkg/util/log.go
+++ b/pkg/util/log.go
@@ -18,8 +18,8 @@ package util
import (
"fmt"
- "github.com/apache/incubator-servicecomb-service-center/pkg/lager"
- "github.com/apache/incubator-servicecomb-service-center/pkg/lager/core"
+ "github.com/ServiceComb/paas-lager"
+
"github.com/ServiceComb/paas-lager/third_party/forked/cloudfoundry/lager"
"os"
"path/filepath"
"runtime"
@@ -30,48 +30,89 @@ import (
//log var
var (
- LOGGER core.Logger
- reBuildLogLevel core.LogLevel
+ LOGGER lager.Logger
+ defaultLagerConfig = stlager.DefaultConfig()
+ loggerConfig LoggerConfig
+ logLevel lager.LogLevel
- loggers map[string]core.Logger
+ loggers map[string]lager.Logger
loggerNames map[string]string
loggersMux sync.RWMutex
+
+ stdOutWriters = []string{"stdout"}
+ fileWriters = []string{"file"}
)
+// LoggerConfig struct for lager and rotate parameters
+type LoggerConfig struct {
+ LoggerLevel string
+ LoggerFile string
+ LogFormatText bool
+ LogRotatePeriod time.Duration
+ LogRotateSize int
+ LogBackupCount int
+}
+
func init() {
- loggers = make(map[string]core.Logger, 10)
+ loggers = make(map[string]lager.Logger, 10)
loggerNames = make(map[string]string, 10)
- LOGGER = lager.NewLogger("default")
+ // make LOGGER do not be nil, new a stdout logger
+ LOGGER = newLogger(fromLagerConfig(defaultLagerConfig))
}
-func InitLogger(loggerName string, cfg *lager.Config) {
- lager.Init(*cfg)
- LOGGER = lager.NewLogger(loggerName)
- LOGGER.Debug("init logger")
+func fromLagerConfig(c *stlager.Config) LoggerConfig {
+ return LoggerConfig{
+ LoggerLevel: c.LoggerLevel,
+ LoggerFile: c.LoggerFile,
+ LogFormatText: c.LogFormatText,
+ }
+}
+
+func toLagerConfig(c LoggerConfig) stlager.Config {
+ w := fileWriters
+ if len(c.LoggerFile) == 0 {
+ w = stdOutWriters
+ }
+ return stlager.Config{
+ Writers: w,
+ LoggerLevel: c.LoggerLevel,
+ LoggerFile: c.LoggerFile,
+ LogFormatText: c.LogFormatText,
+ }
+}
- switch strings.ToUpper(lager.GetConfig().LoggerLevel) {
- case "DEBUG":
- reBuildLogLevel = core.DEBUG
+// newLog new log, unsafe
+func newLogger(cfg LoggerConfig) lager.Logger {
+ stlager.Init(toLagerConfig(cfg))
+ return stlager.NewLogger(cfg.LoggerFile)
+}
+
+func InitGlobalLogger(cfg LoggerConfig) {
+ // renew the global logger
+ if len(cfg.LoggerLevel) == 0 {
+ cfg.LoggerLevel = defaultLagerConfig.LoggerLevel
+ }
+ loggerConfig = cfg
+ LOGGER = newLogger(cfg)
+ // log rotate
+ RunLogDirRotate(cfg)
+ // recreate the deleted log file
+ switch strings.ToUpper(cfg.LoggerLevel) {
case "INFO":
- reBuildLogLevel = core.INFO
+ logLevel = lager.INFO
case "WARN":
- reBuildLogLevel = core.WARN
+ logLevel = lager.WARN
case "ERROR":
- reBuildLogLevel = core.ERROR
+ logLevel = lager.ERROR
case "FATAL":
- reBuildLogLevel = core.FATAL
+ logLevel = lager.FATAL
default:
- panic(fmt.Errorf("unknown logger level: %s",
lager.GetConfig().LoggerLevel))
+ logLevel = lager.DEBUG
}
-
monitorLogFile()
}
-func NewLogger(loggerName string, cfg *lager.Config) core.Logger {
- return lager.NewLoggerExt(loggerName, loggerName, cfg)
-}
-
-func Logger() core.Logger {
+func Logger() lager.Logger {
if len(loggerNames) == 0 {
return LOGGER
}
@@ -99,11 +140,11 @@ func Logger() core.Logger {
loggersMux.Lock()
logger, ok = loggers[logFile]
if !ok {
- cfg := *lager.GetConfig()
+ cfg := loggerConfig
if len(cfg.LoggerFile) != 0 {
cfg.LoggerFile =
filepath.Join(filepath.Dir(cfg.LoggerFile), logFile+".log")
}
- logger = NewLogger(logFile, &cfg)
+ logger = newLogger(cfg)
loggers[logFile] = logger
LOGGER.Warnf(nil, "match %s, new logger %s for %s",
prefix, logFile, funcFullName)
}
@@ -146,6 +187,9 @@ func CustomLogger(pkgOrFunc, fileName string) {
}
func monitorLogFile() {
+ if len(loggerConfig.LoggerFile) == 0 {
+ return
+ }
Go(func(stopCh <-chan struct{}) {
for {
select {
@@ -154,14 +198,14 @@ func monitorLogFile() {
case <-time.After(time.Minute):
Logger().Debug(fmt.Sprintf("Check log file at
%s", time.Now()))
- if lager.GetConfig().LoggerFile != "" &&
!PathExist(lager.GetConfig().LoggerFile) {
- file, err :=
os.OpenFile(lager.GetConfig().LoggerFile, os.O_APPEND|os.O_CREATE|os.O_WRONLY,
0600)
+ if !PathExist(loggerConfig.LoggerFile) {
+ file, err :=
os.OpenFile(loggerConfig.LoggerFile, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0600)
if err != nil {
Logger().Errorf(err, "Create
log file failed.")
return
}
// TODO Here will lead to file handle
leak
- sink :=
core.NewReconfigurableSink(core.NewWriterSink(file, core.DEBUG),
reBuildLogLevel)
+ sink :=
lager.NewReconfigurableSink(lager.NewWriterSink("file", file, lager.DEBUG),
logLevel)
Logger().RegisterSink(sink)
Logger().Errorf(nil, "log file is
removed, create again.")
}
diff --git a/pkg/util/log_test.go b/pkg/util/log_test.go
index 5dec806..0fe8e7c 100644
--- a/pkg/util/log_test.go
+++ b/pkg/util/log_test.go
@@ -18,20 +18,9 @@ package util
import (
"fmt"
- "github.com/apache/incubator-servicecomb-service-center/pkg/lager"
"testing"
)
-func init() {
- InitLogger("log_test", &lager.Config{
- LoggerLevel: "DEBUG",
- LoggerFile: "",
- EnableRsyslog: false,
- LogFormatText: true,
- EnableStdOut: false,
- })
-}
-
func TestLogger(t *testing.T) {
CustomLogger("Not Exist", "testDefaultLOGGER")
l := Logger()
@@ -63,9 +52,12 @@ func BenchmarkLogger(b *testing.B) {
l := Logger()
b.RunParallel(func(pb *testing.PB) {
for pb.Next() {
- l.Infof("test")
+ l.Debugf("debug test")
+ l.Infof("info test")
}
})
+ // after: 50000 20964 ns/op 1296 B/op
18 allocs/op
+ // before: 50000 31378 ns/op 2161 B/op
30 allocs/op
b.ReportAllocs()
}
@@ -74,8 +66,11 @@ func BenchmarkLoggerCustom(b *testing.B) {
l := Logger()
b.RunParallel(func(pb *testing.PB) {
for pb.Next() {
- l.Infof("test")
+ l.Debugf("debug test")
+ l.Infof("info test")
}
})
+ // after: 100000 21374 ns/op 1296 B/op
18 allocs/op
+ // before: 50000 21804 ns/op 2161 B/op
30 allocs/op
b.ReportAllocs()
}
diff --git a/pkg/logrotate/logrotate.go b/pkg/util/logrotate.go
similarity index 85%
rename from pkg/logrotate/logrotate.go
rename to pkg/util/logrotate.go
index 76de98d..db4b79f 100644
--- a/pkg/logrotate/logrotate.go
+++ b/pkg/util/logrotate.go
@@ -14,12 +14,11 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-package traceutils
+package util
import (
"archive/zip"
"fmt"
- "github.com/apache/incubator-servicecomb-service-center/pkg/util"
"io"
"os"
"path/filepath"
@@ -68,7 +67,7 @@ func removeExceededFiles(path string, baseFileName string,
}
fileList, err := FilterFileList(path, pat)
if err != nil {
- util.Logger().Error("filepath.Walk() "+EscapPath(path)+"
failed", err)
+ Logger().Error("filepath.Walk() "+EscapPath(path)+" failed",
err)
return
}
sort.Strings(fileList)
@@ -78,10 +77,10 @@ func removeExceededFiles(path string, baseFileName string,
//remove exceeded files, keep file count below maxBackupCount
for len(fileList) > maxKeptCount {
filePath := fileList[0]
- util.Logger().Warn("remove "+EscapPath(filePath), nil)
+ Logger().Warn("remove "+EscapPath(filePath), nil)
err := removeFile(filePath)
if err != nil {
- util.Logger().Error("remove "+EscapPath(filePath)+"
failed", err)
+ Logger().Error("remove "+EscapPath(filePath)+" failed",
err)
break
}
//remove the first element of a list
@@ -136,7 +135,7 @@ func shouldRollover(fPath string, MaxFileSize int) bool {
fileInfo, err := os.Stat(fPath)
if err != nil {
- util.Logger().Error("state "+EscapPath(fPath)+" failed", err)
+ Logger().Error("state "+EscapPath(fPath)+" failed", err)
return false
}
@@ -156,13 +155,13 @@ func doRollover(fPath string, MaxFileSize int,
MaxBackupCount int) {
rotateFile := fPath + "." + timeStamp
err := CopyFile(fPath, rotateFile)
if err != nil {
- util.Logger().Error("copy "+EscapPath(fPath)+" failed", err)
+ Logger().Error("copy "+EscapPath(fPath)+" failed", err)
}
//truncate the file
f, err := os.OpenFile(fPath, os.O_CREATE|os.O_WRONLY|os.O_TRUNC, 0600)
if err != nil {
- util.Logger().Error("truncate "+EscapPath(fPath)+" failed", err)
+ Logger().Error("truncate "+EscapPath(fPath)+" failed", err)
return
}
f.Close()
@@ -178,7 +177,7 @@ func doBackup(fPath string, MaxBackupCount int) {
pat := fmt.Sprintf(`%s\.[0-9]{1,17}$`, filepath.Base(fPath))
rotateFileList, err := FilterFileList(filepath.Dir(fPath), pat)
if err != nil {
- util.Logger().Error("walk"+EscapPath(fPath)+" failed", err)
+ Logger().Error("walk"+EscapPath(fPath)+" failed", err)
return
}
@@ -193,12 +192,12 @@ func doBackup(fPath string, MaxBackupCount int) {
err = compressFile(file, filepath.Base(fPath), true)
}
if err != nil {
- util.Logger().Error("compress"+EscapPath(file)+"
failed", err)
+ Logger().Error("compress"+EscapPath(file)+" failed",
err)
continue
}
err = removeFile(file)
if err != nil {
- util.Logger().Error("remove"+EscapPath(file)+" failed",
err)
+ Logger().Error("remove"+EscapPath(file)+" failed", err)
}
}
@@ -209,7 +208,7 @@ func doBackup(fPath string, MaxBackupCount int) {
func LogRotateFile(file string, MaxFileSize int, MaxBackupCount int) {
defer func() {
if e := recover(); e != nil {
- util.Logger().Errorf(nil, "LogRotate file %s catch an
exception, err: %v.", EscapPath(file), e)
+ Logger().Errorf(nil, "LogRotate file %s catch an
exception, err: %v.", EscapPath(file), e)
}
}()
@@ -224,14 +223,14 @@ func LogRotate(path string, MaxFileSize int,
MaxBackupCount int) {
//filter .log .trace files
defer func() {
if e := recover(); e != nil {
- util.Logger().Errorf(nil, "LogRotate catch an
exception, err: %v.", e)
+ Logger().Errorf(nil, "LogRotate catch an exception,
err: %v.", e)
}
}()
pat := `.(\.log|\.trace|\.out)$`
fileList, err := FilterFileList(path, pat)
if err != nil {
- util.Logger().Error("filepath.Walk() "+EscapPath(path)+"
failed", err)
+ Logger().Error("filepath.Walk() "+EscapPath(path)+" failed",
err)
return
}
@@ -293,21 +292,14 @@ func CopyFile(srcFile, destFile string) error {
return err
}
-type LogRotateConfig struct {
- Dir string
- Period time.Duration
- MaxFileSize int
- BackupCount int
-}
-
-func RunLogRotate(cfg *LogRotateConfig) {
- util.Go(func(stopCh <-chan struct{}) {
+func RunLogDirRotate(cfg LoggerConfig) {
+ Go(func(stopCh <-chan struct{}) {
for {
select {
case <-stopCh:
return
- case <-time.After(cfg.Period):
- LogRotate(cfg.Dir, cfg.MaxFileSize,
cfg.BackupCount)
+ case <-time.After(cfg.LogRotatePeriod):
+ LogRotate(filepath.Dir(cfg.LoggerFile),
cfg.LogRotateSize, cfg.LogBackupCount)
}
}
})
diff --git a/scripts/create_gvt_manifest(exp).sh
b/scripts/create_gvt_manifest(exp).sh
index 0160862..f27ff77 100755
--- a/scripts/create_gvt_manifest(exp).sh
+++ b/scripts/create_gvt_manifest(exp).sh
@@ -75,3 +75,4 @@ gvt fetch -precaire -no-recurse -revision
bb955e01b9346ac19dc29eb16586c90ded99a9
gvt fetch -precaire -no-recurse -revision
ded5959c0d4e360646dc9e9908cff48666781367 github.com/eapache/queue
gvt fetch -precaire -no-recurse -revision
cb6bfca970f6908083f26f39a79009d608efd5cd github.com/klauspost/crc32
gvt fetch -precaire -no-recurse -revision
879c5887cd475cd7864858769793b2ceb0d44feb github.com/satori/go.uuid
+gvt fetch -precaire -no-recurse -revision
378a833fc008d8343083dc73e77db142afccf377 github.com/ServiceComb/paas-lager
diff --git a/server/core/0_init.go b/server/core/0_init.go
index d7da1ba..1b88849 100644
--- a/server/core/0_init.go
+++ b/server/core/0_init.go
@@ -21,14 +21,11 @@ import (
"flag"
"fmt"
"github.com/apache/incubator-servicecomb-service-center/pkg/grace"
- "github.com/apache/incubator-servicecomb-service-center/pkg/lager"
- "github.com/apache/incubator-servicecomb-service-center/pkg/logrotate"
"github.com/apache/incubator-servicecomb-service-center/pkg/plugin"
"github.com/apache/incubator-servicecomb-service-center/pkg/util"
"github.com/apache/incubator-servicecomb-service-center/version"
"os"
"os/signal"
- "path/filepath"
"runtime"
"syscall"
"time"
@@ -79,34 +76,13 @@ func printVersion() {
}
func initLogger() {
- util.InitLogger(ServerInfo.Config.LoggerName,
- &lager.Config{
- LoggerLevel: ServerInfo.Config.LogLevel,
- LoggerFile:
os.ExpandEnv(ServerInfo.Config.LogFilePath),
- EnableRsyslog: ServerInfo.Config.LogSys,
- LogFormatText: ServerInfo.Config.LogFormat == "text",
- EnableStdOut: version.Ver().RunMode == "dev",
- })
-
- // custom loggers
- util.CustomLogger("Heartbeat", "heartbeat")
- util.CustomLogger("HeartbeatSet", "heartbeat")
-
-
util.CustomLogger("github.com/apache/incubator-servicecomb-service-center/server/service/event",
"event")
-
util.CustomLogger("github.com/apache/incubator-servicecomb-service-center/server/service/notification",
"event")
-
-
util.CustomLogger("github.com/apache/incubator-servicecomb-service-center/server/core/backend",
"registry")
-
- initLogRotate()
-}
-
-func initLogRotate() {
- rotatePeriod := 30 * time.Second
- traceutils.RunLogRotate(&traceutils.LogRotateConfig{
- Dir:
filepath.Dir(os.ExpandEnv(ServerInfo.Config.LogFilePath)),
- MaxFileSize: int(ServerInfo.Config.LogRotateSize),
- BackupCount: int(ServerInfo.Config.LogBackupCount),
- Period: rotatePeriod,
+ util.InitGlobalLogger(util.LoggerConfig{
+ LoggerLevel: ServerInfo.Config.LogLevel,
+ LoggerFile: os.ExpandEnv(ServerInfo.Config.LogFilePath),
+ LogFormatText: ServerInfo.Config.LogFormat == "text",
+ LogRotatePeriod: 30 * time.Second,
+ LogRotateSize: int(ServerInfo.Config.LogRotateSize),
+ LogBackupCount: int(ServerInfo.Config.LogBackupCount),
})
}
diff --git a/server/plugin/infra/tracing/buildin/file_collector.go
b/server/plugin/infra/tracing/buildin/file_collector.go
index 636e7aa..b61b8c2 100644
--- a/server/plugin/infra/tracing/buildin/file_collector.go
+++ b/server/plugin/infra/tracing/buildin/file_collector.go
@@ -20,7 +20,6 @@ import (
"bufio"
"encoding/json"
"fmt"
- "github.com/apache/incubator-servicecomb-service-center/pkg/logrotate"
"github.com/apache/incubator-servicecomb-service-center/pkg/util"
"github.com/apache/incubator-servicecomb-service-center/server/core"
"github.com/openzipkin/zipkin-go-opentracing/thrift/gen-go/zipkincore"
@@ -98,7 +97,7 @@ func (f *FileCollector) loop(stopCh <-chan struct{}) {
}
case <-t.C:
if time.Now().After(nr) {
- traceutils.LogRotateFile(f.Fd.Name(),
+ util.LogRotateFile(f.Fd.Name(),
int(core.ServerInfo.Config.LogRotateSize),
int(core.ServerInfo.Config.LogBackupCount),
)
diff --git a/vendor/manifest b/vendor/manifest
index bb7690c..697b78c 100644
--- a/vendor/manifest
+++ b/vendor/manifest
@@ -10,6 +10,14 @@
"notests": true
},
{
+ "importpath": "github.com/ServiceComb/paas-lager",
+ "repository":
"https://github.com/ServiceComb/paas-lager",
+ "vcs": "git",
+ "revision": "378a833fc008d8343083dc73e77db142afccf377",
+ "branch": "HEAD",
+ "notests": true
+ },
+ {
"importpath": "github.com/Shopify/sarama",
"repository": "https://github.com/Shopify/sarama",
"vcs": "git",
--
To stop receiving notification emails like this one, please contact
[email protected].