Initial Commit

This commit is contained in:
Justin Hammond 2021-09-21 23:32:13 +08:00
commit 154ebc43a1
20 changed files with 829 additions and 0 deletions

62
.github/CODE_OF_CONDUCT.md vendored Normal file
View file

@ -0,0 +1,62 @@
# Contributor Covenant Code of Conduct
## Our Pledge
In the interest of fostering an open and welcoming environment, we as contributors and maintainers pledge to making
participation in our project and our community a harassment-free experience for everyone, regardless of age, body size,
disability, ethnicity, sex characteristics, gender identity and expression, level of experience, education,
socio-economic status, nationality, personal appearance, race, religion, or sexual identity and orientation.
## Our Standards
Examples of behavior that contributes to creating a positive environment include:
* Using welcoming and inclusive language
* Being respectful of differing viewpoints and experiences
* Gracefully accepting constructive criticism
* Focusing on what is best for the community
* Showing empathy towards other community members
Examples of unacceptable behavior by participants include:
* The use of sexualized language or imagery and unwelcome sexual attention or advances
* Trolling, insulting/derogatory comments, and personal or political attacks
* Public or private harassment
* Publishing others' private information, such as a physical or electronic address, without explicit permission
* Other conduct which could reasonably be considered inappropriate in a professional setting
## Our Responsibilities
Project maintainers are responsible for clarifying the standards of acceptable behavior and are expected to take
appropriate and fair corrective action in response to any instances of unacceptable behavior.
Project maintainers have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits,
issues, and other contributions that are not aligned to this Code of Conduct, or to ban temporarily or permanently any
contributor for other behaviors that they deem inappropriate, threatening, offensive, or harmful.
## Scope
This Code of Conduct applies both within project spaces and in public spaces when an individual is representing the
project or its community. Examples of representing a project or community include using an official project e-mail
address, posting via an official social media account, or acting as an appointed representative at an online or offline
event. Representation of a project may be further defined and clarified by project maintainers.
## Enforcement
Instances of abusive, harassing, or otherwise unacceptable behavior may be reported by contacting the project team at
sherifabdlnaby@gmail.com. All complaints will be reviewed and investigated and will result in a response that is deemed
necessary and appropriate to the circumstances. The project team is obligated to maintain confidentiality with regard to
the reporter of an incident. Further details of specific enforcement policies may be posted separately.
Project maintainers who do not follow or enforce the Code of Conduct in good faith may face temporary or permanent
repercussions as determined by other members of the project's leadership.
## Attribution
This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4, available
at https://www.contributor-covenant.org/version/1/4/code-of-conduct.html
[homepage]: https://www.contributor-covenant.org
For answers to common questions about this code of conduct, see
https://www.contributor-covenant.org/faq

62
.github/CONTRIBUTING.md vendored Normal file
View file

@ -0,0 +1,62 @@
# Contributor Covenant Code of Conduct
## Our Pledge
In the interest of fostering an open and welcoming environment, we as contributors and maintainers pledge to make
participation in our project and our community a harassment-free experience for everyone, regardless of age, body size,
disability, ethnicity, sex characteristics, gender identity and expression, level of experience, education,
socio-economic status, nationality, personal appearance, race, religion, or sexual identity and orientation.
## Our Standards
Examples of behavior that contributes to creating a positive environment include:
* Using welcoming and inclusive language
* Being respectful of differing viewpoints and experiences
* Gracefully accepting constructive criticism
* Focusing on what is best for the community
* Showing empathy towards other community members
Examples of unacceptable behavior by participants include:
* The use of sexualized language or imagery and unwelcome sexual attention or advances
* Trolling, insulting/derogatory comments, and personal or political attacks
* Public or private harassment
* Publishing others' private information, such as a physical or electronic address, without explicit permission
* Other conduct which could reasonably be considered inappropriate in a professional setting
## Our Responsibilities
Project maintainers are responsible for clarifying the standards of acceptable behavior and are expected to take
appropriate and fair corrective action in response to any instances of unacceptable behavior.
Project maintainers have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits,
issues, and other contributions that are not aligned to this Code of Conduct, or to ban temporarily or permanently any
contributor for other behaviors that they deem inappropriate, threatening, offensive, or harmful.
## Scope
This Code of Conduct applies within all project spaces, and it also applies when an individual is representing the
project or its community in public spaces. Examples of representing a project or community include using an official
project e-mail address, posting via an official social media account, or acting as an appointed representative at an
online or offline event. Representation of a project may be further defined and clarified by project maintainers.
## Enforcement
Instances of abusive, harassing, or otherwise unacceptable behavior may be reported by contacting the project team
at [INSERT EMAIL ADDRESS]. All complaints will be reviewed and investigated and will result in a response that is deemed
necessary and appropriate to the circumstances. The project team is obligated to maintain confidentiality with regard to
the reporter of an incident. Further details of specific enforcement policies may be posted separately.
Project maintainers who do not follow or enforce the Code of Conduct in good faith may face temporary or permanent
repercussions as determined by other members of the project's leadership.
## Attribution
This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4, available
at https://www.contributor-covenant.org/version/1/4/code-of-conduct.html
[homepage]: https://www.contributor-covenant.org
For answers to common questions about this code of conduct, see
https://www.contributor-covenant.org/faq

38
.github/ISSUE_TEMPLATE/bug_report.md vendored Normal file
View file

@ -0,0 +1,38 @@
---
name: Bug report
about: Create a report to help us improve
title: ''
labels: ''
assignees: ''
---
**Describe the bug**
A clear and concise description of what the bug is.
**To Reproduce**
Steps to reproduce the behavior:
1. Go to '...'
2. Click on '....'
3. Scroll down to '....'
4. See error
**Expected behavior**
A clear and concise description of what you expected to happen.
**Screenshots**
If applicable, add screenshots to help explain your problem.
**Desktop (please complete the following information):**
- OS: [e.g. iOS]
- Browser [e.g. chrome, safari]
- Version [e.g. 22]
**Smartphone (please complete the following information):**
- Device: [e.g. iPhone6]
- OS: [e.g. iOS8.1]
- Browser [e.g. stock browser, safari]
- Version [e.g. 22]
**Additional context**
Add any other context about the problem here.

10
.github/ISSUE_TEMPLATE/custom.md vendored Normal file
View file

@ -0,0 +1,10 @@
---
name: Custom issue template
about: Describe this issue template's purpose here.
title: ''
labels: ''
assignees: ''
---

View file

@ -0,0 +1,20 @@
---
name: Feature request
about: Suggest an idea for this project
title: ''
labels: ''
assignees: ''
---
**Is your feature request related to a problem? Please describe.**
A clear and concise description of what the problem is. Ex. I'm always frustrated when [...]
**Describe the solution you'd like**
A clear and concise description of what you want to happen.
**Describe alternatives you've considered**
A clear and concise description of any alternative solutions or features you've considered.
**Additional context**
Add any other context or screenshots about the feature request here.

8
.github/ISSUE_TEMPLATE/question.md vendored Normal file
View file

@ -0,0 +1,8 @@
---
name: Question about: Ask a Question title: ''
labels: 'question' assignees: ''
---
Ask a question...

23
.github/PULL_REQUEST_TEMPLATE.md vendored Normal file
View file

@ -0,0 +1,23 @@
(Thanks for sending a pull request! Please make sure you click the link above to view the contribution guidelines, then
fill out the blanks below.)
What does this implement/fix? Explain your changes.
---------------------------------------------------
Does this close any currently open issues?
------------------------------------------
Any relevant logs, error output, etc?
-------------------------------------
(If its long, please paste to https://ghostbin.com/ and insert the link here.)
Any other comments?
-------------------
Where has this been tested?
---------------------------

20
.github/SECURITY.md vendored Normal file
View file

@ -0,0 +1,20 @@
# Security Policy
## Supported Versions
Use this section to tell people about which versions of your project are currently being supported with security
updates.
| Version | Supported |
| ------- | ------------------ |
| 5.1.x | :white_check_mark: |
| 5.0.x | :x: |
| 4.0.x | :white_check_mark: |
| < 4.0 | :x: |
## Reporting a Vulnerability
Use this section to tell people how to report a vulnerability.
Tell them where to go, how often they can expect to get an update on a reported vulnerability, what to expect if the
vulnerability is accepted or declined, etc.

21
.github/workflows/build.yml vendored Normal file
View file

@ -0,0 +1,21 @@
on: [ push, pull_request ]
name: Build
jobs:
test:
strategy:
matrix:
go-version: [ 1.16.x, 1.15.x, 1.14.x, 1.13.x ]
platform: [ ubuntu-latest, macos-latest, windows-latest ]
runs-on: ${{ matrix.platform }}
steps:
- name: Install Go
if: success()
uses: actions/setup-go@v1
with:
go-version: ${{ matrix.go-version }}
- name: Checkout code
uses: actions/checkout@v1
- name: Run tests
run: go test -v -race -covermode=atomic -coverprofile=coverage.out
- name: Upload coverage to Codecov
run: bash <(curl -s https://codecov.io/bash)

16
.github/workflows/lint.yml vendored Normal file
View file

@ -0,0 +1,16 @@
on: [ push, pull_request ]
name: Linter
jobs:
lint:
name: Lint project using GolangCI Lint
runs-on: ubuntu-latest
steps:
- name: Check out code into the Go module directory
uses: actions/checkout@v1
- name: GolangCI-Lint Action
uses: matoous/golangci-lint-action@v2
with:
config: .golangci.yml
version: latest
only-new-issues: true

22
LICENSE Normal file
View file

@ -0,0 +1,22 @@
MIT License
Copyright (c) 2021 Sherif Abdel-Naby
Copyright (c) 2021 Justin Hammond
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

1
README.md Normal file
View file

@ -0,0 +1 @@
# Go Log Adapter

9
go.mod Normal file
View file

@ -0,0 +1,9 @@
module github.com/Fishwaldo/go-logadapter
go 1.16
require (
github.com/sirupsen/logrus v1.8.1
github.com/stretchr/testify v1.7.0
go.uber.org/zap v1.19.1
)

65
go.sum Normal file
View file

@ -0,0 +1,65 @@
github.com/benbjohnson/clock v1.1.0 h1:Q92kusRqC1XV2MjkWETPvjJVqKetz1OzxZB7mHJLju8=
github.com/benbjohnson/clock v1.1.0/go.mod h1:J11/hYXuz8f4ySSvYwY0FKfm+ezbsZBKZxNJlLklBHA=
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/kr/pretty v0.1.0 h1:L/CwN0zerZDmRFUapSPitk6f+Q3+0za1rQkzVuMiMFI=
github.com/kr/pretty v0.1.0/go.mod h1:dAy3ld7l9f0ibDNOQOHHMYYIIbhfbHSm3C4ZsoJORNo=
github.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ=
github.com/kr/text v0.1.0 h1:45sCR5RtlFHMR4UwH9sdQ5TC8v0qDQCHnXt+kaKSTVE=
github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI=
github.com/pkg/errors v0.8.1 h1:iURUrRGxPUNPdy5/HRSm+Yj6okJ6UtLINN0Q9M4+h3I=
github.com/pkg/errors v0.8.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0=
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/sirupsen/logrus v1.8.1 h1:dJKuHgqk1NNQlqoA6BTlM1Wf9DOH3NBjQyu0h9+AZZE=
github.com/sirupsen/logrus v1.8.1/go.mod h1:yWOB1SBYBC5VeMP7gHvWumXLIWorT60ONWic61uBYv0=
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
github.com/stretchr/testify v1.2.2/go.mod h1:a8OnRcib4nhh0OaRAV+Yts87kKdq0PP7pXfy6kDkUVs=
github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=
github.com/stretchr/testify v1.7.0 h1:nwc3DEeHmmLAfoZucVR881uASk0Mfjw8xYJ99tb5CcY=
github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
github.com/yuin/goldmark v1.3.5/go.mod h1:mwnBkeHKe2W/ZEtQ+71ViKU8L12m81fl3OWwC1Zlc8k=
go.uber.org/atomic v1.7.0 h1:ADUqmZGgLDDfbSL9ZmPxKTybcoEYHgpYfELNoN+7hsw=
go.uber.org/atomic v1.7.0/go.mod h1:fEN4uk6kAWBTFdckzkM89CLk9XfWZrxpCo0nPH17wJc=
go.uber.org/goleak v1.1.11-0.20210813005559-691160354723 h1:sHOAIxRGBp443oHZIPB+HsUGaksVCXVQENPxwTfQdH4=
go.uber.org/goleak v1.1.11-0.20210813005559-691160354723/go.mod h1:cwTWslyiVhfpKIDGSZEM2HlOvcqm+tG4zioyIeLoqMQ=
go.uber.org/multierr v1.6.0 h1:y6IPFStTAIT5Ytl7/XYmHvzXQ7S3g/IeZW9hyZ5thw4=
go.uber.org/multierr v1.6.0/go.mod h1:cdWPpRnG4AhwMwsgIHip0KRBQjJy5kYEpYjJxpXp9iU=
go.uber.org/zap v1.19.1 h1:ue41HOKd1vGURxrmeKIgELGb3jPW9DMUDGtsinblHwI=
go.uber.org/zap v1.19.1/go.mod h1:j3DNczoxDZroyBnOT1L/Q79cfUMGZxlv/9dzN7SM1rI=
golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
golang.org/x/crypto v0.0.0-20191011191535-87dc89f01550/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI=
golang.org/x/lint v0.0.0-20190930215403-16217165b5de/go.mod h1:6SW0HCj/g11FgYtHlgUYUwCkIfeOF89ocIRzGO/8vkc=
golang.org/x/mod v0.4.2/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA=
golang.org/x/net v0.0.0-20190311183353-d8887717615a/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg=
golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg=
golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=
golang.org/x/net v0.0.0-20210405180319-a5a99cb37ef4/go.mod h1:p54w0d4576C0XHj96bSt6lcn1PtDYWL6XObtHCRCNQM=
golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sync v0.0.0-20210220032951-036812b2e83c/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20191026070338-33540a1f6037/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20210330210617-4fbd30eecc44/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20210510120138-977fb7262007 h1:gG67DSER+11cZvqIMb8S8bt0vZtiN6xWYARwirrOSfE=
golang.org/x/sys v0.0.0-20210510120138-977fb7262007/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo=
golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
golang.org/x/tools v0.0.0-20190311212946-11955173bddd/go.mod h1:LCzVGOaR6xXOjkQ3onu1FJEFr0SW1gC7cKk1uF8kGRs=
golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo=
golang.org/x/tools v0.1.5/go.mod h1:o0xws9oXOQQZyjljx8fwUC0k7L1pTE6eaCbjGeHmOkk=
golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
golang.org/x/xerrors v0.0.0-20191011141410-1b5146add898/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127 h1:qIbj1fsPNlZgppZ+VLlY7N33q108Sa+fhmuc+sWQYwY=
gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/yaml.v2 v2.2.8 h1:obN1ZagJSUGI0Ek/LBmuj4SNLPfIny3KsKFopxRdj10=
gopkg.in/yaml.v2 v2.2.8/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
gopkg.in/yaml.v3 v3.0.0-20210107192922-496545a6307b h1:h8qDotaEPuJATrMmW04NCwg7v22aHH28wwpauUhK9Oo=
gopkg.in/yaml.v3 v3.0.0-20210107192922-496545a6307b/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=

121
log.go Normal file
View file

@ -0,0 +1,121 @@
package logadapter
import (
"encoding/json"
"fmt"
"log"
"sync"
"os"
"github.com/Fishwaldo/go-logadapter/utils"
)
type Logger interface {
Trace(message string, params ...interface{})
Debug(message string, params ...interface{})
Info(message string, params ...interface{})
Warn(message string, params ...interface{})
Error(message string, params ...interface{})
Fatal(message string, params ...interface{})
Panic(message string, params ...interface{})
New(name string) (l Logger)
With(key string, value interface{}) (l Logger)
Sync()
}
//DefaultLogger uses Golang Standard Logging Libary
func DefaultLogger() (l *StdLogger) {
stdlogger := log.New(os.Stderr, "sched - ", log.LstdFlags)
stdlog := &StdLogger{Log: *stdlogger, keys: make(map[string]interface{})}
return stdlog
}
type StdLogger struct {
Log log.Logger
keys map[string]interface{}
mx sync.Mutex
level Log_Level
}
type Log_Level int
const (
LOG_TRACE Log_Level = iota
LOG_DEBUG
LOG_INFO
LOG_WARN
LOG_ERROR
LOG_FATAL
LOG_PANIC
)
func (l *StdLogger) Trace(message string, params ...interface{}) {
if l.level <= LOG_TRACE {
l.Log.Printf("TRACE: %s - %s", fmt.Sprintf(message, params...), l.getKeys())
}
}
func (l *StdLogger) Debug(message string, params ...interface{}) {
if l.level <= LOG_DEBUG {
l.Log.Printf("DEBUG: %s - %s", fmt.Sprintf(message, params...), l.getKeys())
}
}
func (l *StdLogger) Info(message string, params ...interface{}) {
if l.level <= LOG_INFO {
l.Log.Printf("INFO: %s - %s", fmt.Sprintf(message, params...), l.getKeys())
}
}
func (l *StdLogger) Warn(message string, params ...interface{}) {
if l.level <= LOG_WARN {
l.Log.Printf("WARN: %s - %s", fmt.Sprintf(message, params...), l.getKeys())
}
}
func (l *StdLogger) Error(message string, params ...interface{}) {
if l.level <= LOG_ERROR {
l.Log.Printf("ERROR: %s - %s", fmt.Sprintf(message, params...), l.getKeys())
}
}
func (l *StdLogger) Fatal(message string, params ...interface{}) {
l.Log.Fatal(fmt.Printf("FATAL: %s - %s", fmt.Sprintf(message, params...), l.getKeys()))
}
func (l *StdLogger) Panic(message string, params ...interface{}) {
l.Log.Panic(fmt.Printf("PANIC: %s - %s", fmt.Sprintf(message, params...), l.getKeys()))
}
func (l *StdLogger) New(name string) Logger {
//nl := &StdLogger{keys: l.keys}
nl := &StdLogger{level: l.level}
nl.Log.SetPrefix(fmt.Sprintf("%s.%s", l.Log.Prefix(), name))
nl.Log.SetFlags(l.Log.Flags())
nl.Log.SetOutput(l.Log.Writer())
return nl
}
func (l *StdLogger) With(key string, value interface{}) Logger {
l.mx.Lock()
defer l.mx.Unlock()
stdlog := &StdLogger{level: l.level, keys: utils.CopyableMap(l.keys).DeepCopy()}
stdlog.Log.SetPrefix(l.Log.Prefix())
stdlog.Log.SetFlags(l.Log.Flags())
stdlog.Log.SetOutput(l.Log.Writer())
stdlog.keys[key] = value
return stdlog
}
func (l *StdLogger) Sync() {
// do nothing
}
func (l *StdLogger) getKeys() (message string) {
l.mx.Lock()
defer l.mx.Unlock()
msg, err := json.Marshal(l.keys)
if err == nil {
return string(msg)
}
return err.Error()
}
func (l *StdLogger) SetLevel(level Log_Level) {
l.level = level
}
func (l *StdLogger) GetLevel() (level Log_Level) {
return l.level
}

115
log_test.go Normal file
View file

@ -0,0 +1,115 @@
package logadapter
import (
"bytes"
"os"
"regexp"
"testing"
)
func TestDefaultLogger(t *testing.T) {
logger := DefaultLogger()
logger.SetLevel(LOG_TRACE)
if logger.level != LOG_TRACE {
t.Errorf("Can't Set Logging Level")
}
if logger.GetLevel() != LOG_TRACE {
t.Error("GetLevel Didn't return Correct Logging Level")
}
}
func captureOutput(l *StdLogger, f func()) string {
var buf bytes.Buffer
l.Log.SetOutput(&buf)
f()
l.Log.SetOutput(os.Stderr)
return buf.String()
}
func TestLogTrace(t *testing.T) {
logger := DefaultLogger()
logger.SetLevel(LOG_TRACE)
output := captureOutput(logger, func() {
logger.Trace("Hello %s", "world")
})
validmsg := regexp.MustCompile(`^.* TRACE: Hello world \- {}`)
if !validmsg.MatchString(output) {
t.Errorf("Log Trace Failed: %s", output)
}
}
func TestLogDebug(t *testing.T) {
logger := DefaultLogger()
logger.SetLevel(LOG_TRACE)
output := captureOutput(logger, func() {
logger.Debug("Hello %s", "world")
})
validmsg := regexp.MustCompile(`^.* DEBUG: Hello world \- {}`)
if !validmsg.MatchString(output) {
t.Errorf("Log Debug Failed: %s", output)
}
}
func TestLogInfo(t *testing.T) {
logger := DefaultLogger()
logger.SetLevel(LOG_TRACE)
output := captureOutput(logger, func() {
logger.Info("Hello %s", "world")
})
validmsg := regexp.MustCompile(`^.* INFO: Hello world \- {}`)
if !validmsg.MatchString(output) {
t.Errorf("Log Info Failed: %s", output)
}
}
func TestLogWarn(t *testing.T) {
logger := DefaultLogger()
logger.SetLevel(LOG_TRACE)
output := captureOutput(logger, func() {
logger.Warn("Hello %s", "world")
})
validmsg := regexp.MustCompile(`^.* WARN: Hello world \- {}`)
if !validmsg.MatchString(output) {
t.Errorf("Log Warn Failed: %s", output)
}
}
func TestLogError(t *testing.T) {
logger := DefaultLogger()
logger.SetLevel(LOG_TRACE)
output := captureOutput(logger, func() {
logger.Error("Hello %s", "world")
})
validmsg := regexp.MustCompile(`^.* ERROR: Hello world \- {}`)
if !validmsg.MatchString(output) {
t.Errorf("Log Error Failed: %s", output)
}
}
func TestLogFatal(t *testing.T) {
//logger := DefaultLogger()
//logger.SetLevel(LOG_TRACE)
//output := captureOutput(logger, func() {
// logger.Fatal("Hello %s", "world")
//})
//validmsg := regexp.MustCompile(`^.* FATAL: Hello world \- {}`)
//if !validmsg.MatchString(output) {
// t.Errorf("Log Fatal Failed: %s", output)
//}
}
func TestLogPanic(t *testing.T) {
logger := DefaultLogger()
logger.SetLevel(LOG_TRACE)
defer func() {
if err := recover(); err == nil {
t.Errorf("Log Panic Recovery Failed")
}
}()
output := captureOutput(logger, func() {
logger.Panic("Hello %s", "world")
})
validmsg := regexp.MustCompile(`^.* PANIC: Hello world \- {}`)
if !validmsg.MatchString(output) {
t.Errorf("Log Panic Failed: %s", output)
}
}

52
loggers/logrus/logrus.go Normal file
View file

@ -0,0 +1,52 @@
package logruslog
import (
"github.com/Fishwaldo/go-logadapter"
"github.com/sirupsen/logrus"
)
var _ logadapter.Logger = (*LruLogger)(nil)
type LruLogger struct {
Lru *logrus.Entry
}
func (l LruLogger) Debug(msg string, keysAndValues ...interface{}) {
l.Lru.Debugf(msg, keysAndValues...)
}
func (l LruLogger) Error(msg string, keysAndValues ...interface{}) {
l.Lru.Errorf(msg, keysAndValues...)
}
func (l LruLogger) Fatal(msg string, keysAndValues ...interface{}) {
l.Lru.Fatalf(msg, keysAndValues...)
}
func (l LruLogger) Info(msg string, keysAndValues ...interface{}) {
l.Lru.Infof(msg, keysAndValues...)
}
func (l LruLogger) Panic(msg string, keysAndValues ...interface{}) {
l.Lru.Panicf(msg, keysAndValues...)
}
func (l LruLogger) Warn(msg string, keysAndValues ...interface{}) {
l.Lru.Warnf(msg, keysAndValues...)
}
func (l *LruLogger) With(key string, value interface{}) logadapter.Logger {
nl := &LruLogger{Lru: logrus.NewEntry(l.Lru.Logger)}
nl.Lru = l.Lru.WithField(key, value)
return nl
}
func (l *LruLogger) Trace(key string, args ...interface{}) {
l.Lru.Tracef(key, args...)
}
func (l *LruLogger) Sync() {
}
func (l *LruLogger) New(name string) logadapter.Logger {
nl := &LruLogger{Lru: logrus.NewEntry(l.Lru.Logger)}
return nl
}
//LogrusDefaultLogger Return Logger based on logrus with new instance
func LogrusDefaultLogger() logadapter.Logger {
// TODO control verbosity
l := &LruLogger{Lru: logrus.NewEntry(logrus.New())}
return l
}

58
loggers/zap/log.go Normal file
View file

@ -0,0 +1,58 @@
package zaplog
import (
"github.com/Fishwaldo/go-logadapter"
"go.uber.org/zap"
)
var _ logadapter.Logger = (*ZapLogger)(nil)
type ZapLogger struct {
Zap *zap.SugaredLogger
}
func (l *ZapLogger) With(key string, value interface{}) logadapter.Logger {
nl := &ZapLogger{Zap: l.Zap.With(key, value)}
return nl
}
func (l *ZapLogger) Trace(message string, params ...interface{}) {
l.Zap.Debugf(message, params...)
}
func (l *ZapLogger) Debug(message string, params ...interface{}) {
l.Zap.Debugf(message, params...)
}
func (l *ZapLogger) Info(message string, params ...interface{}) {
l.Zap.Infof(message, params...)
}
func (l *ZapLogger) Warn(message string, params ...interface{}) {
l.Zap.Warnf(message, params...)
}
func (l *ZapLogger) Error(message string, params ...interface{}) {
l.Zap.Errorf(message, params...)
}
func (l *ZapLogger) Fatal(message string, params ...interface{}) {
l.Zap.Fatalf(message, params...)
}
func (l *ZapLogger) Panic(message string, params ...interface{}) {
l.Zap.Panicf(message, params...)
}
func (l *ZapLogger) New(name string) (nl logadapter.Logger) {
zl := &ZapLogger{Zap: l.Zap}
zl.Zap.Named(name)
return zl
}
func (l *ZapLogger) Sync() {
}
//DefaultLogger Return Default Sched Logger based on Zap's sugared logger
func NewZapLogger() *ZapLogger {
// TODO control verbosity
loggerBase, _ := zap.NewDevelopment(zap.AddCallerSkip(1), zap.AddStacktrace(zap.ErrorLevel))
sugarLogger := loggerBase.Sugar()
return &ZapLogger{
Zap: sugarLogger,
}
}

58
utils/copymap.go Normal file
View file

@ -0,0 +1,58 @@
package utils
type CopyableMap map[string]interface{}
type CopyableSlice []interface{}
// DeepCopy will create a deep copy of this map. The depth of this
// copy is all inclusive. Both maps and slices will be considered when
// making the copy.
func (m CopyableMap) DeepCopy() map[string]interface{} {
result := map[string]interface{}{}
for k,v := range m {
// Handle maps
mapvalue,isMap := v.(map[string]interface{})
if isMap {
result[k] = CopyableMap(mapvalue).DeepCopy()
continue
}
// Handle slices
slicevalue,isSlice := v.([]interface{})
if isSlice {
result[k] = CopyableSlice(slicevalue).DeepCopy()
continue
}
result[k] = v
}
return result
}
// DeepCopy will create a deep copy of this slice. The depth of this
// copy is all inclusive. Both maps and slices will be considered when
// making the copy.
func (s CopyableSlice) DeepCopy() []interface{} {
result := []interface{}{}
for _,v := range s {
// Handle maps
mapvalue,isMap := v.(map[string]interface{})
if isMap {
result = append(result, CopyableMap(mapvalue).DeepCopy())
continue
}
// Handle slices
slicevalue,isSlice := v.([]interface{})
if isSlice {
result = append(result, CopyableSlice(slicevalue).DeepCopy())
continue
}
result = append(result, v)
}
return result
}

48
utils/copymap_test.go Normal file
View file

@ -0,0 +1,48 @@
package utils
import (
"testing"
"github.com/stretchr/testify/require"
)
func TestCopyMap(t *testing.T) {
m1 := map[string]interface{}{
"a": "bbb",
"b": map[string]interface{}{
"c": 123,
},
"c": []interface{} {
"d", "e", map[string]interface{} {
"f": "g",
},
},
}
m2 := CopyableMap(m1).DeepCopy()
m1["a"] = "zzz"
delete(m1, "b")
m1["c"].([]interface{})[1] = "x"
m1["c"].([]interface{})[2].(map[string]interface{})["f"] = "h"
require.Equal(t, map[string]interface{}{
"a": "zzz",
"c": []interface{} {
"d", "x", map[string]interface{} {
"f": "h",
},
},
}, m1)
require.Equal(t, map[string]interface{}{
"a": "bbb",
"b": map[string]interface{}{
"c": 123,
},
"c": []interface{} {
"d", "e", map[string]interface{} {
"f": "g",
},
},
}, m2)
}