2
0
mirror of https://gitee.ltd/lxh/logger.git synced 2025-04-20 07:40:34 +08:00

Compare commits

..

13 Commits

Author SHA1 Message Date
170c532443 Merge pull request 'coward' (#6) from coward into master
Reviewed-on: https://gitee.ltd/lxh/logger/pulls/6
2025-02-11 16:12:43 +08:00
coward
f71c5996ea Merge branch 'master' into coward 2025-02-11 16:11:20 +08:00
coward
a1a701428b ⬆️升级loki-client包依赖 2025-02-11 09:58:52 +08:00
be64023660 Merge pull request '🐛ants使用了默认连接池不要release,会变得不幸😢' (#4) from coward into master
Reviewed-on: https://gitee.ltd/lxh/logger/pulls/4
2024-11-29 16:12:54 +08:00
coward
aff875eb11 🐛ants使用了默认连接池不要release,会变得不幸😢 2024-11-29 16:12:03 +08:00
c9ca2b3858 Merge pull request '🐛修复loki异步推送搞错了,弄成同步了.' (#3) from coward into master
Reviewed-on: https://gitee.ltd/lxh/logger/pulls/3
2024-11-29 10:34:15 +08:00
coward
869dedc580 🐛修复loki异步推送搞错了,弄成同步了. 2024-11-29 10:32:57 +08:00
0ed7416b49 Merge pull request '🎨writer方法中json反序列化更改为sonic包,异步推送到loki更改为ants包去做一个全局工作池' (#2) from coward into master
Reviewed-on: https://gitee.ltd/lxh/logger/pulls/2
2024-11-29 09:27:47 +08:00
coward
c20634ea80 🎨writer方法中json反序列化更改为sonic包,异步推送到loki更改为ants包去做一个全局工作池 2024-11-29 09:15:24 +08:00
李寻欢
541c744c60 添加许可证 2022-10-25 16:27:54 +08:00
李寻欢
27e9f08a92 ⬆️ 依赖更新 2022-10-20 11:53:08 +08:00
李寻欢
16775ae2ab 🎨 优化日志文件名,新增主机名 2022-10-20 11:48:25 +08:00
李寻欢
40a3dc9339 🎨 优化gorm日志 2022-05-19 09:01:05 +08:00
8 changed files with 1303 additions and 392 deletions

202
LICENSE Normal file
View File

@ -0,0 +1,202 @@
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 (c) 2020 lixunhuan Authors. All Rights Reserved.
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.

12
file.go
View File

@ -5,17 +5,19 @@ import (
"github.com/natefinch/lumberjack"
"go.uber.org/zap"
"go.uber.org/zap/zapcore"
"os"
"time"
)
// 初始化LokiCore使日志可以输出到文件
func initFileCore() zapcore.Core {
hostname, _ := os.Hostname()
lumberJackLogger := &lumberjack.Logger{
Filename: "logs/runtime.log", // 日志文件的位置
MaxSize: 10, // 最大10M
MaxBackups: 5, // 保留旧文件的最大个数
MaxAge: 30, // 保留旧文件的最大天数
Compress: false, // 是否压缩/归档旧文件
Filename: fmt.Sprintf("logs/runtime-%s.log", hostname), // 日志文件的位置
MaxSize: 10, // 最大10M
MaxBackups: 5, // 保留旧文件的最大个数
MaxAge: 30, // 保留旧文件的最大天数
Compress: false, // 是否压缩/归档旧文件
}
// 配置 sugaredLogger
writer := zapcore.AddSync(lumberJackLogger)

63
go.mod
View File

@ -1,52 +1,69 @@
module gitee.ltd/lxh/logger
go 1.17
go 1.20
require (
github.com/caarlos0/env/v6 v6.9.2
github.com/bytedance/sonic v1.12.5
github.com/caarlos0/env/v6 v6.10.1
github.com/go-kit/kit v0.12.0
github.com/lixh00/loki-client-go v1.0.1
github.com/grafana/loki-client-go v0.0.0-20240913122146-e119d400c3a5
github.com/natefinch/lumberjack v2.0.0+incompatible
github.com/prometheus/common v0.34.0
go.uber.org/zap v1.21.0
github.com/panjf2000/ants/v2 v2.10.0
github.com/prometheus/common v0.37.0
go.uber.org/zap v1.23.0
gorm.io/driver/mysql v1.3.2
gorm.io/gorm v1.23.5
gorm.io/gorm v1.24.0
)
require (
github.com/BurntSushi/toml v0.4.1 // indirect
github.com/beorn7/perks v1.0.1 // indirect
github.com/cespare/xxhash/v2 v2.1.2 // indirect
github.com/bytedance/sonic/loader v0.2.0 // indirect
github.com/cespare/xxhash/v2 v2.2.0 // indirect
github.com/cloudwego/base64x v0.1.4 // indirect
github.com/cloudwego/iasm v0.2.0 // indirect
github.com/davecgh/go-spew v1.1.1 // indirect
github.com/dennwc/varint v1.0.0 // indirect
github.com/go-kit/log v0.2.1 // indirect
github.com/go-logfmt/logfmt v0.5.1 // indirect
github.com/go-sql-driver/mysql v1.6.0 // indirect
github.com/gogo/protobuf v1.3.2 // indirect
github.com/golang/protobuf v1.5.2 // indirect
github.com/golang/protobuf v1.5.4 // indirect
github.com/golang/snappy v0.0.4 // indirect
github.com/grafana/loki/pkg/push v0.0.0-20240912152814-63e84b476a9a // indirect
github.com/grafana/regexp v0.0.0-20220304095617-2e8d9baf4ac2 // indirect
github.com/jinzhu/inflection v1.0.0 // indirect
github.com/jinzhu/now v1.1.4 // indirect
github.com/jpillora/backoff v1.0.0 // indirect
github.com/json-iterator/go v1.1.12 // indirect
github.com/matttproud/golang_protobuf_extensions v1.0.1 // indirect
github.com/klauspost/cpuid/v2 v2.0.9 // indirect
github.com/matttproud/golang_protobuf_extensions v1.0.2 // indirect
github.com/mitchellh/mapstructure v1.5.0 // indirect
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect
github.com/modern-go/reflect2 v1.0.2 // indirect
github.com/mwitkow/go-conntrack v0.0.0-20190716064945-2f068394615f // indirect
github.com/pkg/errors v0.9.1 // indirect
github.com/prometheus/client_golang v1.12.2 // indirect
github.com/prometheus/client_model v0.2.0 // indirect
github.com/prometheus/procfs v0.7.3 // indirect
github.com/prometheus/prometheus v1.8.2-0.20201028100903-3245b3267b24 // indirect
go.uber.org/atomic v1.9.0 // indirect
github.com/pmezard/go-difflib v1.0.0 // indirect
github.com/prometheus/client_golang v1.13.0 // indirect
github.com/prometheus/client_model v0.3.0 // indirect
github.com/prometheus/procfs v0.8.0 // indirect
github.com/prometheus/prometheus v0.35.0 // indirect
github.com/stretchr/testify v1.8.2 // indirect
github.com/twitchyliquid64/golang-asm v0.15.1 // indirect
go.uber.org/atomic v1.10.0 // indirect
go.uber.org/goleak v1.1.12 // indirect
go.uber.org/multierr v1.8.0 // indirect
golang.org/x/net v0.0.0-20220517181318-183a9ca12b87 // indirect
golang.org/x/oauth2 v0.0.0-20220411215720-9780585627b5 // indirect
golang.org/x/sys v0.0.0-20220517195934-5e4e11fc645e // indirect
golang.org/x/text v0.3.7 // indirect
google.golang.org/appengine v1.6.7 // indirect
google.golang.org/genproto v0.0.0-20220505152158-f39f71e6c8f3 // indirect
google.golang.org/grpc v1.46.2 // indirect
google.golang.org/protobuf v1.28.0 // indirect
gopkg.in/natefinch/lumberjack.v2 v2.0.0 // indirect
golang.org/x/arch v0.0.0-20210923205945-b76863e36670 // indirect
golang.org/x/exp v0.0.0-20240325151524-a685a6edb6d8 // indirect
golang.org/x/net v0.33.0 // indirect
golang.org/x/oauth2 v0.18.0 // indirect
golang.org/x/sync v0.10.0 // indirect
golang.org/x/sys v0.28.0 // indirect
golang.org/x/text v0.21.0 // indirect
google.golang.org/appengine v1.6.8 // indirect
google.golang.org/genproto v0.0.0-20230410155749-daa745c078e1 // indirect
google.golang.org/grpc v1.64.1 // indirect
google.golang.org/protobuf v1.36.5 // indirect
gopkg.in/yaml.v2 v2.4.0 // indirect
gopkg.in/yaml.v3 v3.0.1 // indirect
)

1358
go.sum

File diff suppressed because it is too large Load Diff

View File

@ -79,10 +79,15 @@ func NewGormLoggerWithConfig(config gl.Config) gl.Interface {
// DefaultGormLogger 默认的日志实现
func DefaultGormLogger() gl.Interface {
// 默认日志级别为Info如果是生产环境就是Error
logLevel := gl.Info
if config.Mode == Prod {
logLevel = gl.Error
}
return &gormLogger{gl.Config{
SlowThreshold: time.Second, // Slow SQL threshold
IgnoreRecordNotFoundError: false, // 忽略没找到结果的错误
LogLevel: gl.Info, // Log level
LogLevel: logLevel, // Log level
Colorful: false, // Disable color
}}
}

View File

@ -4,7 +4,9 @@ import (
"gitee.ltd/lxh/logger/log"
"gorm.io/driver/mysql"
"gorm.io/gorm"
gl "gorm.io/gorm/logger"
"testing"
"time"
)
func TestGormLogger(t *testing.T) {
@ -15,6 +17,26 @@ func TestGormLogger(t *testing.T) {
log.Panicf("mysql connect error: %s", err.Error())
}
var count int64
if err := engine.Table("t_tenant").Count(&count).Error; err != nil {
t.Log(err)
}
t.Logf("count: %d", count)
}
func TestGormLoggerWithConfig(t *testing.T) {
dsn := "saas:saas123@tcp(10.11.0.10:3307)/saas_tenant?charset=utf8mb4&parseTime=True&loc=Local"
engine, err := gorm.Open(mysql.Open(dsn), &gorm.Config{Logger: NewGormLoggerWithConfig(gl.Config{
SlowThreshold: time.Second, // Slow SQL threshold
IgnoreRecordNotFoundError: false, // 忽略没找到结果的错误
LogLevel: gl.Warn, // Log level
Colorful: false, // Disable color
})})
if err != nil {
log.Panicf("mysql connect error: %s", err.Error())
}
var count int64
if err := engine.Table("t_tenant1").Count(&count).Error; err != nil {
t.Log(err)

View File

@ -21,3 +21,19 @@ func TestLogger2(t *testing.T) {
log.Info("我是测试消息")
//time.Sleep(5 * time.Second)
}
func TestLogger3(t *testing.T) {
InitLogger(LogConfig{
Mode: Dev,
LokiEnable: true,
FileEnable: false,
LokiHost: "",
LokiPort: 0,
LokiSource: "test-logger",
LokiJob: "test-logger",
})
log.Info("这是info日志")
log.Debug("这是debug日志")
log.Warn("这是warn日志")
}

15
loki.go
View File

@ -1,11 +1,12 @@
package logger
import (
"encoding/json"
"errors"
"fmt"
"github.com/bytedance/sonic"
"github.com/go-kit/kit/log"
"github.com/lixh00/loki-client-go/loki"
"github.com/grafana/loki-client-go/loki"
"github.com/panjf2000/ants/v2"
"github.com/prometheus/common/model"
"go.uber.org/zap"
"go.uber.org/zap/zapcore"
@ -43,7 +44,7 @@ func initLokiCore() zapcore.Core {
func initLokiClient() {
// 如果Loki配置错误返回一个nil
if config.LokiHost == "" || config.LokiPort < 1 {
panic(errors.New("Loki配置错误"))
panic(errors.New("loki配置错误"))
}
// 初始化配置
cfg, _ := loki.NewDefaultConfig(config.getLokiPushURL())
@ -64,7 +65,7 @@ func (c lokiWriter) Write(p []byte) (int, error) {
Msg string `json:"msg"` // 日志内容
}
var li logInfo
err := json.Unmarshal(p, &li)
err := sonic.Unmarshal(p, &li)
if err != nil {
return 0, err
}
@ -73,8 +74,8 @@ func (c lokiWriter) Write(p []byte) (int, error) {
label["source"] = model.LabelValue(config.LokiSource)
label["level"] = model.LabelValue(li.Level)
label["caller"] = model.LabelValue(li.Caller)
// 异步推送消息到服务器
go func() {
_ = ants.Submit(func() {
t, e := time.ParseInLocation("2006-01-02 15:04:05.000", li.Ts, time.Local)
if e != nil {
t = time.Now().Local()
@ -82,7 +83,7 @@ func (c lokiWriter) Write(p []byte) (int, error) {
if err = lokiClient.Handle(label, t, li.Msg); err != nil {
fmt.Printf("日志推送到Loki失败: %v\n", err.Error())
}
}()
})
return 0, nil
}